Recently I’ve attempted to make a simple program that would require moving a button across the screen several times, but in order to do this I have to be able to access the JPanel from certain parts of the code which I don’t seem to be able to do, or find an alternative method. Here is a small program that should pinpoint the problems I’m having.
public class ButtonMover extends JFrame
{
public static void main(String[] args) {
new ButtonMover();
}
JButton actionButton;
public ButtonMover() {
JPanel buttonMoverPanel = new JPanel();
buttonMoverPanel.setLayout(new GridBagLayout());
this.add(buttonMoverPanel);
this.setSize(500,500);
this.setResizable(true);
this.setVisible(true);
JButton actionButton = new JButton("Testing Button");
buttonMoverPanel.add(actionButton);
ClickListener c = new ClickListener();
actionButton.addActionListener(c);
}
private class ClickListener
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == actionButton)
buttonMoverPanel.add(new JLabel("Testing Label"));
//insert code to move button here
}
}
}
The |buttonMoverPanel.add(new JLabel(“Testing Label”));| line is the only part that doesn’t work, because I seem unable to make a reference to buttonMoverPanel from that area. While it doesn’t actually cause any errors, it prevents actionButton from doing anything.
If you need to access a variable, here your buttonMoverPanel, then don’t hide it by declaring it in a method or constructor making it only visible in that method or constructor. No, declare it in the class so that it is visible throughout the class.
So again, one improvement for this code is to declare the buttonMoverPanel in the class just the same as you’re currently doing with your actionButton JButton.
Edit: you’re shadowing your actionButton variable — you’re re-declaring it in the constructor, so that the button added to the GUI is not referred to by the actionButton class field. Don’t re-declare it in the class.
In other words the line indicated creates a completely new actionButton variable, one that is only visible in the constructor:
The solution is to not re-declare the variable to rather to use the class field: