动态更新JLabel以显示更改状态消息,以便在单击按钮时进行处理

use*_*196 1 java swing jlabel event-dispatch-thread thread-sleep

我想显示状态消息,当单击按钮触发的处理达到不同的处理阶段时,动态更新.你能帮忙吗?这是我使用的代码,但不起作用.它总是在函数结束时显示状态msg,而不是在执行时显示中间状态msgs.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.*;

import java.net.*;
import java.io.*;

public class MainApplet extends JApplet {
  JButton gstbtn = new JButton("Connect to Gst Hotspot");
  JButton wifibtn = new JButton("Connect to existing Wifi networks");
  JLabel status = new JLabel();
  JPanel toppanel = null, nwConfigDialog = null;
  final JFrame f= new JFrame();
  JTextField ssidTxt;
  JPasswordField pwdTxt;
  JOptionPane opt;

  public void init() {

    gstbtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Gst Hotspot connect workflow triggered");
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        status.setText("");
        toppanel.repaint();
        if(connectToHotSpot()) { //todo: Connect to gst hotspot
                try {
                        status.setText("connected to Local Gst Box Wifi Hotspot");
                        status.repaint();
                        Thread.sleep(20*1000);
                        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                } catch(Exception ex) {
                        System.err.println("connect to hotspot: Sleep Exception: " + ex.getMessage());
                }
                //showNwConfigDialog(f);
        } else {
                status.setText("Unable to connect to Local Gst Box Wifi Hotspot");
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
      }
    });

    wifibtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Wifi n/w connect workflow triggered");
      }
    });

    toppanel = new JPanel(new GridLayout(4,4,4,4));
    gstbtn.setPreferredSize(new Dimension(5,5));
    wifibtn.setPreferredSize(new Dimension(5,5));
    setContentPane(toppanel);
    getContentPane().add(gstbtn);
    getContentPane().add(wifibtn);
    getContentPane().add(status);
  }
}
Run Code Online (Sandbox Code Playgroud)

dic*_*c19 5

它总是在函数结束时显示状态msg,而不是在执行时显示中间状态msgs.

这是因为此Thread.sleep()调用阻止了事件调度线程(EDT),它是执行Swing组件创建/更新和事件处理的单个特殊线程,因此在此线程解锁之前,GUI无法重新绘制/更新自身:

gstbtn.addActionListener(new ActionListener() {
    ...
    Thread.sleep(20*1000);
    ...
}
Run Code Online (Sandbox Code Playgroud)

要避免此问题,您应该使用SwingWorker在后台线程中执行繁重的任务,让EDT可以自由更新GUI并发布中间结果.这里有很多例子,只需看看标签.


边注

除了开发一个的JApplet我建议你开发一个Swing应用程序和使用Java Web Start的分配/从网络启动应用程序.