during the setup this function is called
private JPanel Defer()
{
defer = new JPanel();
defer.setLayout(new BoxLayout(defer, BoxLayout.Y_AXIS));
JButton deferB = new JButton("Defer Staff Key Cutting");
Color col = colour.getColour("White");
deferB.setBackground(col);
deferB.setActionCommand(def);
deferB.addActionListener(this);
defer.add(deferB);
return defer;
}
It works fine and the listener reacts. The thing is I want to change the colour of the button when it is clicked and later on when I try to use the same code I have here for the colour it throws and exception claiming that deferB is not real.
As it is created in the function I know it is local but the button must exist some how for it to be shown on screen.
How can I access the button deferB to change its colour outside the function?
Also if anyone can explain how a local variable can be used throughout the program like it is being used that would be great as it does not make sense to me.
Inside the action Listener, you got to call the .getSource() method. This method returns object, so you got to cast it. Or make it a private instance variable. Then you can access it anywhere.
From what i can tell from your code, the class your working in is an action listener. Which means in your “actionPerformed(ActionEvent event)” method, you want to change the color. (because that’s the method that gets called when it is clicked. In that method, you can either do event.getSource(), or just use the variable name if you have it as an instance variable.
Let me know if you need more clarification.