我想創建一個加載消息,在加載信息時將在屏幕上彈出。我將爲它調用initLoadingPanel()方法,以便JFrame可見。我的問題是如何關閉它?Java Swing實用程序
我的代碼如下。
public class DataMigration extends JFrame{
private JFrame frmDataMigration;
private JFrame loader;
private JButton btnProcess;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DataMigration window = new DataMigration();
window.frmDataMigration.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DataMigration() {
initialize();
}
private void initialize() {
LoggerImp.startLog(CLASS_NAME, "initialize()");
frmDataMigration = new JFrame();
btnProcess = new JButton("Load");
btnProcess.setEnabled(false);
btnProcess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
SwingWorker <CSV, CSV> worker = new SwingWorker<CSV, CSV>() {
@Override
protected CSV doInBackground() throws Exception {
return FileReaderCSVHelper.fileReader(dirName.getText(), fileName.getText());
}
@Override
protected void done() {
try {
csv = doInBackground();
generateTableList(csv.getCsvTitle(), stateController.getFieldNames());
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (Exception e){
}
loader.dispose();
}
};
worker.execute();
}
});
frmDataMigration.getContentPane().add(btnProcess);
}
public void initLoadingPanel(){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
loader = new JFrame("Loading....");
ImageIcon img = new ImageIcon("loader.gif");
loader.add(new JLabel(" Loading...", img, JLabel.CENTER));
loader.setAlwaysOnTop(true);
loader.pack();
loader.setSize(448, 497);
loader.setVisible(true);
loader.setLocationRelativeTo(null);
}
});
}
我遇到下面的錯誤,當我打電話loader.dispose()線程「AWT-EventQueue-0」中的異常java.lang.NullPointerException – newbie
這是(大概)因爲你在'run'方法內的本地上下文中聲明瞭'loader'。而不是'JFrame loader = new JFrame(「Loading ....」);',你可以嘗試'loader = new JFrame(「Loading ....」);',假設'loader'被聲明爲一個實例變量。另外請注意,您應該在EDT的環境中調用'dispose'以及 – MadProgrammer
請參閱我上面的代碼 – newbie