java - 扩展类时出错

标签 java extend

我是 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");
    }
});

参见 Anonymous Classes

关于java - 扩展类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331016/

相关文章:

css - 将 2 个 div 扩展到页面底部

css - Sass嵌套扩展内部是自己的父级

java - 连接到 SoftHSM java

java - Selenium 'browserName was not a boolean' InvalidArgumentException,无法解决

java - 有没有办法让 Java8 持续一年的时间占闰年?

jquery - 扩展已扩展的 jqueryUI 工具提示小部件

java - 是否可以在 Java 8 中扩展枚举?

Java 按字典顺序比较顶点

java - Jsoup链接选择

Android 扩展 EditText