我是 Java 的新手,所以我不知道出了什么问题。我这里有一段代码,当它被执行时,应该“打开”一个窗口一次,但是每当我在 ButtonHandler
类中扩展类 ColoredWordsExperiment
时,窗口打开得非常快,这几乎导致我的电脑每次都崩溃。如果我省略了扩展名,那么它可以正常工作,但是我将无法在 ButtonHandler
类中使用 ColoredWordsExperiment
类中的对象......在你下面可以找到代码(我遗漏了一些不重要的东西,否则它会变得太长)。
public class ColoredWordsExperiment {
JFrame frame;
ButtonHandler buttonHandler;
ColoredWordsExperiment(){
frame = new JFrame("Colored Words Experiment");
frame.setSize(1200, 150);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1 = new JButton("Matching");
label1 = new JLabel("test");
label1.setPreferredSize(new Dimension(90, 40));
JPanel labelContainer = new JPanel();
labelContainer.add(label1);
JPanel buttonContainer = new JPanel();
buttonContainer.add(button1);
frame.add(buttonContainer, BorderLayout.SOUTH);
frame.add(labelContainer, BorderLayout.NORTH);
buttonHandler = new ButtonHandler();
button1.addActionListener(buttonHandler);
}
public static void main(String[] arg) {
new ColoredWordsExperiment();
}
}
-
public class ButtonHandler extends ColoredWordsExperiment implements ActionListener {
@Override
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("Matching")) {
System.out.println("Matching");
label1.setText("Text changed");
}
}
}
最佳答案
在这种情况下没有理由扩展ColoredWordsExperiment
。您应该简单地实现 ActionListener
。
您实际上是在使用一个附加方法在自身内部初始化另一个 ColoredWordsExperiment
实例。这会导致您的构造函数被再次调用,从而导致重新创建 GUI 窗口。
参见 Inheritance了解更多详情。
如果您想从您的ActionListener
实现中更改ColoredWordsExperiment
中的一个字段,您需要在构造期间传递一个引用。
public class ButtonHandler implements ActionListener {
ColoredWordsExperiment coloredWords;
public ButtonHandler(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Matching")) {
System.out.println("Matching");
coloredWords.label1.setText("Text changed");
}
}
}
在这种情况下,您还可以选择创建匿名内部类。使用此技术,您可以完全摆脱 ButtonHandler
类。
在 ColoredWordsExperiment
而不是
buttonHandler = new ButtonHandler();
button1.addActionListener(buttonHandler);
你可以使用
button1.addActionListener(new ActionListener() {
if (e.getActionCommand().equals("Matching")) {
System.out.println("Matching");
label1.setText("Text changed");
}
});
关于java - 扩展类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331016/