Java JTextField 在 setText() 之后不更新文本



我正在尝试通过局域网创建一个消息传递应用程序。在 AppHost 下,我正在运行用于 HostUIHostConnect的并发线程(一个用于显示 UI,另一个用于接收/管理传入和传出连接(。我正在尝试将所有这些类编写为单例类。

我正在尝试使用 setText()HostUI 上的JTextField(ipField)上显示服务器 IP 地址。但是,setText()后,UI 窗口不会显示更新的文本,尽管getText() TO ipField 将返回新文本。

下面是这三个类的代码:

应用主机:

public class AppHost {
    public static AppHost instance;
    Thread[] threads = new Thread[2];
    final int CONNECTION = 0;
    final int UI = 1;
    ExecutorService executor = Executors.newFixedThreadPool(threads.length);
    public AppHost()
    {
        instance = this;
        //address = getHostIPAddress();
        threads[UI] = new Thread(new HostUI());
        threads[CONNECTION] = new Thread(new HostConnect());
        for (Thread t: threads) {
             executor.execute((Runnable) t);
             System.out.println("Running: "+t);
        }
    }
}

主机连接:

public class HostConnect implements Runnable {
    public static HostConnect instance;
    private int port = 9000;
    InetAddress address; //Host Address. Server will be hosted here.
    ServerSocket server;
    Socket s;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    public HostConnect()
    {   
        instance = this;
        try {
            server = new ServerSocket(port);
            System.out.println("Server Init Success.");
            address = getHostIPAddress();

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    public void run()
    {
        try{
            s = server.accept();
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream());
        }
        catch (Exception e)
        {
           e.printStackTrace(); 
        }
    }
    public InetAddress getHostIPAddress() 
    {
        try{
            InetAddress thisIP = InetAddress.getLocalHost();
            return thisIP;
        }
        catch(UnknownHostException e){
            return null;
        }
    }
    public InetAddress getAddress()
    {
        return address;
    }
}

主机用户界面:

public class HostUI extends javax.swing.JFrame implements Runnable {
    static HostUI instance;
    public HostUI() {
        initComponents();
        instance = this;
    }
    public void run() {
    new HostUI().setVisible(true);
    String addr = ""+HostConnect.instance.address;
    this.ipField.setText(addr);
    //System.out.println(ipField.getText());
}     

与 Swing 组件(getter 或 setter(交互时,必须确保从事件调度线程调用方法。

如果没有,请使用 invokeLater:

SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            ipField.setText(addr);
        }
});

最新更新