我有一个功能齐全的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分开。这将允许您使用主线程进行逻辑流程显示Splashscreen,然后开始通过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);
}
});
}