读书人

怎的点击JButton执行数据库查询显示图

发布时间: 2012-12-27 10:17:10 作者: rapoo

怎样点击JButton执行数据库查询显示图片,执行完图片隐藏
因为数据库查询时间较长,想点击按钮后显示等待图片,查询完成后让图片隐藏,图片放在一个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();
}


});

showComponent(buttonLoad);
}

private void showComponent(Component c) {

assert SwingUtilities.isEventDispatchThread();

removeAll();
add(c);
revalidate();
repaint();
}

private class ImageLoadingWorker extends SwingWorker<Void, Void> {

@Override
protected Void doInBackground() throws Exception {

Thread.sleep(3000L); // 这里的 sleep 3秒,模拟你从数据库读取图片的工作时间
return null;
}

@Override
protected void done() {

showComponent(buttonLoad); // 读取完成以后,把 label 再换成 JButton
}
}
}


[其他解释]
懒得看楼主的,你要是更大多数软件一样做个等待界面,完全可以用JWINDOW搞一个。然后setvisible。用JFrame觉得不太好。
[其他解释]
顶顶顶顶顶顶顶顶顶顶
[其他解释]
说详细点啊。
[其他解释]
引用:
说详细点啊。

JFame中的JLabel
private ImageIcon waitIco;
private JLabel icoLab;
waitIco=new ImageIcon("res/waiting.gif");
waitLab=new JLabel(waitIco);
waitLab.setVisible(false);

执行某个费时的方法
public class SSButton implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
String staD=MainUI.staDTxt.getText();
String staA=MainUI.staATxt.getText();
if(staD.equals(""))
JOptionPane.showMessageDialog(new JFrame(),"请输入出发站!");
else if(staA.equals("")){
JOptionPane.showMessageDialog(new JFrame(),"请输入到达站!");
}else{
MainUI.waitLab.setVisible(true);
MainUI.selSS(staD, staA);
MainUI.waitLab.setVisible(false);
}
}
}

读书人网 >J2SE开发

热点推荐