Question

OK so i dynamically made a line of J Buttons on a J Panel with a null layout using this code:

int Y = 100;
int X = 100;
for(x=1, x<=20, x++){
    button = new JButton(x);
    button.setLayout(null);
    button.setSize(100, 100);
    button.setLocation(X,Y);
    button.setVisible(true);
    panel.add(button); 

    X += 100;

    //action listener
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //should print out the location of the button that was clicked
            System.out.println(button.getLocation());
        }
    });
}

and i when i press on of does button i want it to print its location on the panel but instead it prints out the location of the last button that was added every time, please help.

take note that i am a very new to programming

Was it helpful?

Solution

The button variable is being redefined everytime you run the loop, so when you finally call your actionPerformed method, you are reading the data of the last button. The loop finished before any event happened and saved the reference of the last button created in the button variable.

You need to reference the button from the event object, because it contains a reference to the button that is the source of the event:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //should print out the location of the button that was clicked
        System.out.println( ((JButton)e.getSource()).getLocation() );
    }
});

The addActionListener method is called 20 times, but the actionPerformed method is called asynchronously and only when an action event (ex: button click) happens. The ActionEvent object contains information about the event, which includes the source of the event, which is your button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top