java - 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) {
}
}
解决方案
感谢您使用代码更新您的帖子。实际上,您已经创建了一个无限循环!
问题在于:
button.addActionListener(new GUI());
GUI
每次实例化类时,您都在创建该类的新GUI
实例。明白了吗?
我认为您想使用类的当前实例GUI
作为您的动作侦听器,因此正确的方法是:
button.addActionListener(this);
希望有帮助。
推荐阅读
- java - 如何在多个 SpringBootTests 之间重用 Testcontainers?
- c# - 调用 draw rect 有时什么都不做
- winapi - 如何使用 Win32 或 MFC 获取 Windows 系统的正确关机时间
- google-cloud-platform - 在 GCP 中闲置期间是否有与私有 IP 实例相关的任何费用?
- redis - 我们可以在 C# 中使用过期时间在 Redis 列表中添加值吗?
- c# - EventLog Reader 忽略 C# 中的系统事件跟踪
- python - Xpath 变量和分页
- amazon-web-services - 在 serverless.yaml 中向 s3 存储桶添加策略时遇到问题
- python - 带有postgresql的django rest框架中的时区感知日期问题
- python - 如何在我的 csv 文件中保留 unicode 字符代码?