我有一个功能齐全的 GUI,可以启动与已连接 USB 设备的连接。该启动过程大约需要 3 秒。在那段时间里,我想向用户显示一个启动屏幕,告诉他/她程序正在启动。我创建了一个“SplashFrame”类(JFrame 的扩展),它创建一个带有两个标签的面板并将它们放在框架上。
但是,我确实遇到一个问题,即 SplashFrame 仅在其他“主”框架的设置过程完成后才完全加载。这意味着在我有意关闭 SplashFrame 之前,两个标签都不可读。如何在启动主框架之前“强制”SplashFrame 完全加载?
这是我的主要方法
private static JFrame frame;
private static SplashFrame splash;
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
splash = new SplashFrame();
long startTime = System.currentTimeMillis();
frame = new CFSMainFrame();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Total time: " + ((float)totalTime/1000) + " seconds!");
splash.closeFrame();
}
});
}
这是我的splashFrame
public class SplashFrame extends JFrame{
private static JFrame frame;
public SplashFrame(){
frame = new JFrame("Loading...");
frame.setLayout(new BorderLayout());
frame.setSize(300, 150);
ImageIcon img = new ImageIcon("resources/mini_logo.png");
frame.setIconImage(img.getImage());
JPanel pane = splashPanel();
frame.add(pane);
createAndShowGUI();
}
private JPanel splashPanel(){
JPanel pane = new JPanel(new BorderLayout());
ImageIcon loadingImg = new ImageIcon("resources/logo.png");
JLabel imageLabel = new JLabel();
imageLabel.setIcon(loadingImg);
JLabel loadingLabel = new JLabel("Loading");
loadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
loadingLabel.setVerticalAlignment(SwingConstants.CENTER);
loadingLabel.setPreferredSize(new Dimension(150, 165));
pane.add(imageLabel, BorderLayout.CENTER);
pane.add(loadingLabel, BorderLayout.PAGE_END);
return pane;
}
private void createAndShowGUI(){
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
public void closeFrame(){
frame.setVisible(false);
frame.dispose();
}
最佳答案
我建议您将 USB 连接逻辑与 UI 分开。这将允许您使用主线程进行逻辑流程显示启动画面,然后开始通过 USB 连接,如果连接则显示应用程序屏幕。 只是一个粗略的例子:
public static void main(String[] args) {
final SplashFrame splash = new SplashFrame();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
splash.pack();
splash.setVisible(true);
}
});
USBConnection usbConnection = new USBConnection();
boolean success = usbConnection.connect();
if(!success){
System.err.println("Could not connect to USB device.");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
splash.setVisible(false);
splash.dispose();
}
});
return;
}
final CFSMainFrame application = new CFSMainFrame(usbConnection);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
splash.setVisible(false);
splash.dispose();
application.pack();
application.setVisible(true);
}
});
}
关于java - 在打开新的 JFrame 之前完全加载 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37294930/