首先:我知道我所做的是糟糕的设计。我正在尝试这个以获得更好的Java感觉 - 什么是可能的,什么不是,为什么?使用派生类的Java Swing控件为自己创建侦听器
我写了下面的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
@SuppressWarnings("serial")
class ButtonFrame extends JFrame
{
private final static int DEFAULT_WIDTH = 300;
private final static int DEFAULT_HEIGHT = 200;
private final JPanel buttonPanel;
public ButtonFrame()
{
this.setTitle("Button Frame");
this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
PanelButton yellowButton = new PanelButton("Yellow", Color.YELLOW, this);
PanelButton redButton = new PanelButton("Red", Color.RED, this);
PanelButton blueButton = new PanelButton("Blue", Color.BLUE, this);
this.buttonPanel = new JPanel();
this.buttonPanel.add(yellowButton);
this.buttonPanel.add(redButton);
this.buttonPanel.add(blueButton);
// add panel to frame
this.add(this.buttonPanel);
}
}
@SuppressWarnings("serial")
class PanelButton extends JButton implements ActionListener
{
private final Color buttonColor;
private final ButtonFrame containingFrame;
public PanelButton(String title, Color buttonColor,
ButtonFrame containingFrame)
{
super(title);
this.buttonColor = buttonColor;
this.containingFrame = containingFrame;
this.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event)
{
this.containingFrame.setBackground(this.buttonColor);
}
}
但是,这是行不通的。我从调试器看到actionPerformed()
正在被调用,它有预期的值。我无法理解这里发生的事情。有人可以帮帮我吗?
+ +1为单独的解决方案。我要解释为什么他不工作,你的工作表明如何做得更好。那里有良好的二元性。 –
感谢您的回答。 –