我们不知道会发生什么';在JavaGUI中不使用EventQueue.invokeLater()吗?这就是我所做的
当我运行下面的代码时,我的GUI应用程序的多个实例被执行。我不明白为什么会这样。谁能解释一下这里到底发生了什么事我们不知道会发生什么';在JavaGUI中不使用EventQueue.invokeLater()吗?这就是我所做的,java,multithreading,swing,user-interface,Java,Multithreading,Swing,User Interface,当我运行下面的代码时,我的GUI应用程序的多个实例被执行。我不明白为什么会这样。谁能解释一下这里到底发生了什么事 import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class FirstApp { priva
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstApp {
private MyActionListener mal = new MyActionListener();
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FirstApp firstApp = new FirstApp();
} catch (Exception e) {
e.printStackTrace();
}
}
public FirstApp () {
initialize();
}
private void initialize() {
JFrame f = new JFrame();//creating instance of JFrame
f.setSize(400,300);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
JButton b = new JButton("Click Me");//creating instance of JButton
b.setBounds(140,100,120, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
b.addActionListener(new FirstApp().mal);
}
private class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("Hello!");
}
}
}
我认为这与EventQueue.invokeLater()有关,当我们使用WindowBuilder创建一个新的GUI应用程序时,默认情况下,EventQueue.invokeLater()就在那里
我的GUI应用程序有多个实例被执行。我不明白为什么会这样
因为您的代码一直在创建FirstApp类的多个实例
b.addActionListener(new FirstApp().mal);
因此,您创建了一个类,该类尝试向按钮添加ActionListener,但却创建了一个应用程序的新实例,并且循环重复
只需使用:
b.addActionListener(new MyActionListener());
去掉你的“mal”变量
另外,不要使用空布局和设置边界(…)。Swing设计用于布局管理器。学会正确使用秋千
阅读上的Swing教程。是的,应使用invokeLater()。不要删除GUI生成器生成的代码。然而,这不是问题的原因。也许最好知道为什么应该使用invokeLater。所以请查看@shri-see:。