【问题标题】:Image not showing up in Java Swing GUI JFrame图像未显示在 Java Swing GUI JFrame 中
【发布时间】:2018-03-17 01:36:17
【问题描述】:
我有一个调用这个函数的主函数:
private void splashScreen() throws MalformedURLException {
JWindow window = new JWindow();
ImageIcon image = new ImageIcon(new URL("https://i.imgur.com/Wt9kOSU.png"));
JLabel imageLabel = new JLabel(image);
window.add(imageLabel);
window.pack();
window.setVisible(true);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
window.setVisible(false);
window.dispose();
}
我已将图像添加到窗口,打包窗口然后使其可见,框架弹出,但图像未显示在框架中。我相当肯定这段代码应该可以工作?
【问题讨论】:
标签:
java
swing
user-interface
jframe
【解决方案1】:
您正在使用 Thread.sleep(),因此 GUI 处于休眠状态并且无法自行重绘。阅读 Concurrency 上的 Swing 教程部分了解更多信息。
不要使用 Thread.sleep()。
改为使用Swing Timer 将事件安排在 5 秒内。阅读 How to Use Timers 上的 Swing 教程部分了解更多信息。
【解决方案2】:
就像 camickr 所说,Swing Timer 将是处理此问题的正确方法。但是由于创建自定义线程是您将来会做的很多事情,这里有一个“手动”示例来说明如何解决这个问题:
private void showSplashScreen() {
[Create window with everything and setVisible, then do this:]
final Runnable threadCode = () -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(window::dispose); // Closes the window - but does so on the Swing thread, where it needs to happen.
// The thread has now run all its code and will die gracefully. Forget about it, it basically never existed.
// Btw., for the thread to be able to access the window like it does, the window variable either needs to be "final" (((That's what you should do. My mantra is, make EVERY variable (ESPECIALLY method parameters!) final, except if you need them changeable.))), or it needs to be on class level instead of method level.
};
final Thread winDisposerThread = new Thread(threadCode);
winDisposerThread.setDaemon(true); // Makes sure that if your application dies, the thread does not linger.
winDisposerThread.setName("splash window closer timer"); // Always set a name for debugging.
winDisposerThread.start(); // Runs the timer thread. (Don't accidentally call .run() instead!)
// Execution of your program continues here IMMEDIATELY, while the thread has now started and is sleeping for 5 seconds.
}