gpt4 book ai didi

JAVA:JLabel 未随事件变化

转载 作者:行者123 更新时间:2023-12-01 15:08:44 24 4
gpt4 key购买 nike

我正在尝试使用 GUI 来下载 HTTP 链接,当单击开始下载按钮时,将开始下载,下载正在工作,但当按照 ActionListener 中声明的那样开始下载时,标签不会更改。请帮助我。

这是代码

下载开始和完成时标签应更改。

public class SwingGUI2 extends javax.swing.JFrame {    
private javax.swing.JLabel jLabel1;
private javax.swing.JButton jButton1;
private URLConnection connect;

private SwingGUI2() {
setLayout(new FlowLayout());

jLabel1 = new javax.swing.JLabel();
jLabel1.setText("");
add(jLabel1);

jButton1 = new javax.swing.JButton();
jButton1.setText("Start Download");
add(jButton1);

jButton1.addActionListener(new java.awt.event.ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});


pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setText("Download Started"); //NOT WORKING
try {
String DownURL = "http://www.number1seed.com/music/flymetothemoon.mp3";
URL url = new URL(DownURL);
connect = url.openConnection();
File file = new File("download");

BufferedInputStream BIS = new BufferedInputStream(connect.getInputStream());
BufferedOutputStream BOS = new BufferedOutputStream(new FileOutputStream(file.getName()));
int current;
while((current = BIS.read())>=0) BOS.write(current);
BOS.close();
BIS.close();

jLabel1.setText("Completed"); //NOT WORKING

} catch (Exception e) {}
}


public static void main(String[] args) throws ClassNotFoundException, InstantiationException {
try {
javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (IllegalAccessException ex) {
Logger.getLogger(SwingGUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(SwingGUI2.class.getName()).log(Level.SEVERE, null, ex);
}

java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SwingGUI2 gui = new SwingGUI2();
gui.setVisible(true);
gui.setSize(300,200);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}

}

最佳答案

您正尝试从事件调度程序线程运行下载,导致您的 GUI 在执行任务时卡住。

看看SwingWorker作为后台线程执行下载任务。您的 actionPerformed 方法应该如下所示:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setText("Download Started");
SwingWorker sw = new SwingWorker() {
public Object doInBackground(){
try {
// ...
// Do the whole download thing
} catch (Exception e) {
e.printStackTrace();
}

jLabel1.setText("Completed");
return null;
}
};
sw.execute();
}

注意:确保你没有吞下这个catch中的异常,否则你将无法看到是否发生了任何错误。

关于JAVA:JLabel 未随事件变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12604483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com