因为数据库查询时间较长,想点击按钮后显示等待图片,查询完成后让图片隐藏,图片放在一个jlabel里,然后放在JFrame的中。我是先把jlabel的visible设为false,点按钮后为true,执行完后又为false,但是整个过程图片都不会显示出来,特来请教
------最佳解决方案--------------------------------------------------------
下面这个小例子,大概是你说的意思,主要是使用 SwingWorker
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
/**
*
* @date 13/11/2012
*/
public class LoadingPage extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
}
JFrame f = new JFrame("Test Loading");
f.getContentPane().add(new LoadingPage(), BorderLayout.CENTER);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
private JButton buttonLoad;
private JLabel labelLoading;
private ImageLoadingWorker worker;
LoadingPage() {
super(new FlowLayout(FlowLayout.CENTER, 50, 50));
buttonLoad = new JButton("Load Image");
labelLoading = new JLabel("Loading ..."); // 这里替换成你的图片 new JLabel(Icon);
worker = new ImageLoadingWorker();
setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
buttonLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showComponent(labelLoading);
worker.execute();
}