gpt4 book ai didi

java - 谁能解释一下这段代码中 javax.swing.SwingUtilities.invokeLater 的用法

转载 作者:行者123 更新时间:2023-11-30 11:01:25 26 4
gpt4 key购买 nike

我发现这段代码很奇怪。因为在括号关闭之前还有另一个函数。你能解释一下它是如何工作的吗?

javax.swing.SwingUtilities.invokeLater(new Runnable() {     
public void run() {
createAndShowGUI();
}
});

------ 完整代码如下。此代码不属于我。我在谷歌搜索时找到了它。

package pkginterface;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Interface extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

public Interface() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout());
JButton button = new JButton("Java Code Geeks - Java Examples");
//add Button
add(button);
//set action listeners for buttons
button.addActionListener(this);
// define a custom short action command for the button
button.setActionCommand("Geeks");
// add button to frame
add(button);
}

@Override
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if (action.equals("Geeks")) {
System.out.println("Button pressed!");
}
}

private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new Interface();
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

最佳答案

它将事件发布到 Swing 的事件调度线程。该事件导致在 EDT 线程上调用 createAndShowUi() 方法。

关于java - 谁能解释一下这段代码中 javax.swing.SwingUtilities.invokeLater 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com