Reputation: 2542
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.
Upvotes: 0
Views: 2105
Reputation: 285405
One more bit of advice that may not answer your question but should help fix bad programming practice. In general, don't do this:
deferB.addActionListener(this);
What you're doing with this bit of code is making your GUI a listener, and that's asking the GUI class to do too much and leads to creating of "switchboard" action listeners with a bunch of if/else's or a large switch/case statement where you check if the source or action command equals this do that, or if it equals foo do bar... a tricky thing to set up and difficult to debug, modify or extend. I think you're much better off giving each button (or group of similar buttons) its own listener, often as an anonymous inner class or if more complex as a private inner class or even its own stand alone class, something like so:
deferB.addActionListener(new ActionListener() {
actionPerformed(ActionEvent ae) {
// the code for the event should go here
}
});
Upvotes: 2
Reputation: 7070
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.
(JButton)event.getSource();
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.
private JButton button_;
Let me know if you need more clarification.
Upvotes: 4
Reputation: 328556
Save the button in a field. Add this before the method:
private JButton deferB;
and change the code in the method:
...
deferB = new JButton("Defer Staff Key Cutting");
...
That allows you to access deferB
anywhere in the class.
Upvotes: 2