Java Swing adding mouse Listener (inner class) for an array of buttons leads to malfunction

Ok, so the program I want to build is simple. There are five buttons named from 0 to 4. If any of the buttons are pressed, then the number 0 to 4 is printed in console.

enter image description here

I have used a GridLayout to place the buttons in the frame. And to set up each button I have created a method, inicializarIG().

This inicializarIG() method creates an array of 5 buttons and inside a for loop it does:

  • Create an instance of a button for each cell in the array of buttons.
  • Set up a mouseListener for each button. The value to print in each Listener is different, it is determined by the index of the loop (AND I WANT TO DO IT BY USING THE INDEX!).
  • Add The button to the main frame.

Surprisingly, This simple program doesn´t work properly. It always print the number “5” no matter what button is pressed:

enter image description here

NOTE: I had to put the index var outside the inicializarIG() method in order to fulfill the var scope for the Listeners. I don’t know if the problem is related, just saying in cause it might help.


import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;

public class IGrafica {

    private JFrame frame;
    public int index=0;

    public IGrafica(){
        frame = new JFrame();


    public void configureFrame(){
        frame.getContentPane().setLayout(new GridLayout(1,5)); //

    public void inicializarIG(){


        JButton [] botones = new JButton [5];

        //Loop to set up buttons and add the mouseListener
        for (index = 0; index < botones.length; index++) {
            botones[index] = new JButton(Integer.toString(index));

            //Set up each listener 
            botones[index].addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {

            //Add the button


    public void visualizate(){

    public static void main(String[] args) {        
        IGrafica window = new IGrafica();
        EventQueue.invokeLater(new Runnable() {
            public void run() {


Thank you in advance. Any idea will be welcomed.



First of all, don’t use a MouseListener for this, but rather use an ActionListener, since this works best for buttons. Next of all, you need to remember that your listener is a class of its own, and it needs a variable of its own to store its own index, else it uses the final value of the loop index which is not what you want. Either this or use the ActionEvent’s actionCommand property, a value which will match the text of the button. So:

botones[index].addActionListener(new MyActionListener(index));


// a private inner class
private class MyActionListener implements ActionListener {
    private int index;

    public MyActionListener(int index) {
        this.index = index;

    public void actionPerformed(ActionEvent e) {
        System.out.println("index is: " + index);
        System.out.println("Action Command is: " + e.getActionCommand());

Or if you want to use an anonymous inner class:

        botones[index].addActionListener(new ActionListener() {
            private int myIndex;

                this.myIndex = index;

            public void actionPerformed(ActionEvent e) {
                System.out.println("index is: " + myIndex);

How to set in Spring with Annotations and pure Java

How would one go about setting up the following in Spring using only Java and annotations.

<property name="" value="update"/>

I amIt should be possible and I do believe it is a lot cleaner to make projects xml free.

PS: This shouldn’t be important but I’m running this on Heroku.


Added this to the class where the dataSource() is and it fixed my issue.

final Properties hibernateProperties() {
    final Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty("", "update");
    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    hibernateProperties.setProperty("hibernate.show_sql", "true");

    return hibernateProperties;

Full example is here

EDIT PS: For this line hibernateProperties.setProperty("","update"); check out this stackoverflow question to figure out the best value if update isn’t right for you.


Debug Cordova Plugin

How do you debug the non-js portion of a cordova plugin? I have found several discussions on Stack Overflow, but none of them have given me an answer on how I throw my plugin into an IDE, and be able to breakpoint it.

Debugging the JS is no problem and makes sense, but I have no idea how to either print out a log from the android/ios side or hit breakpoints.

I am in the process of making a small change to InAppBrowser to allow Cookie read/writing and I desperately need to know how to monitor this.

Any help would be vastly appreciated.


Create a new cordova project

cordova create debugPlugins com.debug.plugis debugPlugins

go to the new folder

cd debugPlugins

add ios and android platforms

cordova platform add ios android

and the inAppBrowser plugin (or any other you want to debug)

cordova plugin add cordova-plugin-inappbrowser

When you added android and ios platforms, two native project where created, you can open and debug them.

  • For ios, go to platforms/ios and open the debugPlugins.xcodeproj
  • For android open android studio, go to File->New->Import Project and select the platforms/android folder

Android WebView app crashing in emulator: null Application Context?

I’m developing a very simple Android app on a Mac in AndroidStudio and I’ve created an AVD based on the Nexus S. The app compiles with no issues, the emulator launches and then I get errors in logcat and the app crashes. In the emulator, an error dialog displays with the message “Unfortunately App has stopped”

Here’s the logcat output (error level):

10-01 13:59:27.813  14114-14114/ E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
10-01 13:59:27.832  14114-14114/ E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-01 13:59:27.832  14114-14114/ E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-01 13:59:27.832  14114-14114/ E/chromium﹕ [] No suitable EGL configs found.
10-01 13:59:27.832  14114-14114/ E/chromium﹕ [] GLSurfaceEGL::InitializeOneOff failed.
10-01 13:59:27.832  14114-14114/ E/chromium﹕ [] GLSurface::InitializeOneOff failed
10-01 13:59:27.854  14114-14114/ E/DataReductionProxySettingListener﹕ No DRP key due to exception:java.lang.ClassNotFoundException:
10-01 13:59:28.530  14114-14165/ A/chromium﹕ [] Check failed: kGLImplementationNone != GetGLImplementation() (0 vs. 0)
10-01 13:59:28.530  14114-14165/ A/libc﹕ Fatal signal 6 (SIGABRT), code -6 in tid 14165 (GpuThread)

I’m assuming that the first error related to ApplicationContext is the cause of the other errors, but I’m not sure about that. I’ve tried about 10 different methods for setting context, but the ApplicationContext error persists.

My main questions: Is the ApplicationContext error the root cause of the crash? If not, what is? What might I try to fix it?

Here’s the complete application code for reference:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
package="" >
        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
            <uses-permission android:name="android.permission.INTERNET" />
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebSettings;

public class MainActivity extends AppCompatActivity {

    private String appUrl = "";

    protected void onCreate(Bundle savedInstanceState) {

        WebView myWebView = (WebView) findViewById(;
        myWebView.setWebViewClient(new MyWebViewClient());

        WebSettings webSettings = myWebView.getSettings();



import android.content.Intent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyWebViewClient extends WebViewClient {

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("")) {
            return false;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        return true;


Here’s the logcat output

That is not a Java stack trace, and therefore is not what you’re looking for.

I’m assuming that the first error related to ApplicationContext is the cause of the other errors, but I’m not sure about that

That is some spurious message that you will see, even from apps that run fine.

If not, what is?

As ozbek notes, your <uses-permission> element needs to be moved outside of <application> and made a direct child of <manifest>. Your Java stack trace should mention a missing INTERNET permission.

It is possible that there are other problems, but that’s definitely one.


How can I animate a calculated position with JQuery

So I have a variable with a calculated position that centers the element with JQuery, reason I did this is because I will not know the width of the element so I made it dynamic like so.

var $x = $("#line").outerWidth();

var $result = "calc( 50% - " + $x +"px / 2 )";

Then I tried to animate it to the center (value of $result) like so:

        "left": $result,
        "top" : "15px"

    }, 1000 );

Sadly this did not work, only the top value moved.

Any advice is greatly appreciated, thank you.


jsBin demo

If you already use calc (CSS3) than you’ll have nothing against using in your CSS:

Using CSS3 transition and calc()

    transition: 1s;
    /*...other stuff...*/

and in your jQuery (instead of .animate())

var outW2 = $("#line").outerWidth() / 2;

  left : "calc(50% - "+ outW2 +"px)",
  top  : 70

Using .animate() and negative margin (for centering)

For all older browsers, you can simply use .animate() as you did,
moving the element to 50% but also to a -half-width left margin (to center it):

var outW2 = $("#line").outerWidth() / 2;

  left: "50%",
  marginLeft : -outW2
}, 1000);

jsBin demo (crossbrowser solution)

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..