If you need to access a variable, here is your ButtonMoverPanel, then do not hide it by declaring it in a method or constructor, making it visible only in this method or constructor. No, declare it in the class so that it is visible throughout the class.
So, one improvement for this code is to declare buttonMoverPanel in the class just like you are doing with your actionButton JButton right now.
Edit: you are obscuring your actionButton variable - you are re-declaring it in the constructor, so the button added in the GUI is not called the field of the actionButton class. Do not repeat the announcement in the classroom.
In other words, the specified line creates a completely new variable actionButton, which is visible only in the constructor:
JButton actionButton; JPanel buttonMoverPanel = new JPanel(); public ButtonMover() { buttonMoverPanel.setLayout(new GridBagLayout()); this.add(buttonMoverPanel); this.setSize(500, 500); this.setResizable(true); this.setVisible(true); JButton actionButton = new JButton("Testing Button");
The solution is to not re-declare the variable rather to use the class field:
JButton actionButton; JPanel buttonMoverPanel = new JPanel(); public ButtonMover() { buttonMoverPanel.setLayout(new GridBagLayout()); this.add(buttonMoverPanel); this.setSize(500, 500); this.setResizable(true); this.setVisible(true); actionButton = new JButton("Testing Button");
source share