首页 > 解决方案 > IntelliJ IDEA 在我尝试运行代码时创建大量新窗口

问题描述

我正在 IntelliJ 中制作一个非常简单的程序。它进展顺利,如果运行正常,我仍然会取得进展。我单击运行按钮,编译时它没有给我任何错误,但它会很快打开大量窗口,当我停止程序时它会全部关闭。这有效地阻止了我的进步,我开始没有时间完成这项工作了。有人有解决办法吗?

代码:

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUI implements ActionListener {

    JFrame frame;
    JPanel panel;
    JLabel label;
    public String output;
    public String input;

    public GUI() {
        panel = new JPanel();

        frame = new JFrame();
        frame.setSize(500,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(panel);

        panel.setLayout(null);

        label = new JLabel("Input");
        label.setBounds(10, 20, 80, 25);
        panel.add(label);

        JTextField inputText = new JTextField(20);
        inputText.setBounds(100, 20, 165, 25);
        panel.add(inputText);

        JLabel outputLabel = new JLabel("Password");
        outputLabel.setBounds(10, 50, 80, 25);
        panel.add(outputLabel);

        JTextField outputText = new JTextField();
        outputText.setBounds(100, 50, 165, 25);
        panel.add(outputText);

        JButton button = new JButton("Convert");
        button.setBounds(10, 80, 80, 25);
        button.addActionListener(new GUI());
        panel.add(button);

        JLabel successLabel = new JLabel("");
        successLabel.setBounds(10, 110, 300, 25);
        panel.add(successLabel);

        frame.setVisible(true);

        input = inputText.getText();
        output = outputLabel.getText();
    }

    public static void main(String[] args) {
        new GUI();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}

标签: javaintellij-idea

解决方案


感谢您使用代码更新您的帖子。实际上,您已经创建了一个无限循环!

问题在于:

button.addActionListener(new GUI());

GUI每次实例化类时,您都在创建该类的新GUI实例。明白了吗?

我认为您想使用类的当前实例GUI作为您的动作侦听器,因此正确的方法是:

button.addActionListener(this);

希望有帮助。


推荐阅读