One approach is to nest ColorAction
as an inner class in ButtonPanel
, where it has implicit access to the enclosing panel.
Addendum: As noted in comments by @Andrew Thompson and @nachokk, the implicit accessibility can be made explicit by qualifying this
using the enclosing class name. See JLS §15.8.4. Qualified this
for details. In this example, these two invocations are equivalent:
setBackground(backgroundColor);
ButtonPanel.this.setBackground(backgroundColor);
As an more general alternative, consider encapsulating the target panel and color in an Action
, as outlined here.
class ButtonPanel extends JPanel {
public ButtonPanel() {
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
add(yellowButton);
add(blueButton);
add(redButton);
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction redAction = new ColorAction(Color.RED);
ColorAction blueAction = new ColorAction(Color.BLUE);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
private class ColorAction implements ActionListener {
public ColorAction(Color c) {
backgroundColor = c;
}
@Override
public void actionPerformed(ActionEvent event) {
setBackground(backgroundColor);
}
private Color backgroundColor;
}
}