【发布时间】:2015-03-26 22:39:53
【问题描述】:
我有一个 SplashScreen 类,它显示图像和进度条,直到某些数据库被初始化。我希望在启动画面结束后打开一个新窗口。我有以下代码:
主类
public class Gui{
private static final String IMG_PATH = "../opt/images/splashscreendef.jpg";
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Gui ui = new Gui();
}
});
}
private inTouchGui() {
InitSplashScreen splash = null;
splash = new InitSplashScreen();
try {
splash.initUI();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedImage img = null;
try {
img = ImageIO.read(new File(IMG_PATH));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(null, label);
}
}
闪屏类
public class InitSplashScreen {
private JDialog dialog;
private JProgressBar progress;
public void initUI() throws MalformedURLException {
showSplashScreen();
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>(){
@Override
protected Void doInBackground() throws Exception {
Thread thread = new Thread(new InitProcess());
thread.start();
int i = 0;
while (thread.isAlive()){
i++;
Thread.sleep(200);// Loading of databases
publish(i);// Notify progress
}
if (i < 10){
for (i = 0; i < 100; i++){
Thread.sleep(50);// We simulate loading even if database is fully loaded
publish(i);// Notify progress
}
}
return null;
}
@Override
protected void process(List<Integer> chunks) {
progress.setValue(chunks.get(chunks.size() - 1));
}
@Override
protected void done() {
hideSplashScreen();
}
};
worker.execute();
}
protected void hideSplashScreen() {
dialog.setVisible(false);
dialog.dispose();
}
protected void showSplashScreen() throws MalformedURLException {
dialog = new JDialog((Frame) null);
dialog.setModal(false);
dialog.setUndecorated(true);
JLabel background = new JLabel(new ImageIcon("splashscreendef.jpg"));
background.setLayout(new BorderLayout());
dialog.add(background);
progress = new JProgressBar();
background.add(progress, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
当我运行代码时,我同时获得了启动屏幕和图像窗口,我尝试使用worker.get(),但屏幕上什么也没有出现。你能给我一些建议吗?我对 Java Swing 还很陌生。
顺便说一句,例如,是否有可能实现一个像这样的登录窗口(可能意味着不是疯狂的代码负载和使其工作的时间)?
http://designsparkle.com/wp-content/uploads/2014/06/a-simple-html-css-login-for.jpg
感谢您的建议。
【问题讨论】:
标签: java swing concurrency swingworker