gpt4 book ai didi

java - 当另一个对象中的线程触发事件时,Swing 接口(interface)不更新组件

转载 作者:行者123 更新时间:2023-12-01 13:16:48 25 4
gpt4 key购买 nike

我到处查看了之前提出的问题,虽然有些用户也遇到了类似的问题,但没有一个解决方案对我有用。

我的问题是我有一个 Swing 界面(主应用程序),它提供了使用套接字的图形方式。该程序允许用户在客户端或服务器模式下打开/关闭 UDP 或 TCP 协议(protocol)的套接字。管理 TCP 服务器连接的类,提供用于触发事件(客户端连接、客户端断开、新消息等)的接口(interface)。主应用程序实现了该接口(interface),并相应地升级了 Swing 接口(interface)。

主应用程序是这样的:

    public class mainapp implements TCPServerListener{

private tcpServer TCPServer;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainapp window = new mainapp()
window.frmUdptcpPruebas.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


private void startTCPServer(){


TCPServer= new tcpServer(new mainapp(), "");
TCPServer.setListeningIP(this.textFieldIpLocal.getText() );
TCPServer.startTcpServer();


}


/**
* Create the application.
*/
public pruebas() {
initialize();

}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
.
.The swing interface has many more components, but Im just showing the
.connect button to make the code more readable
.
btnConectar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
boton_conectar_presionado();
startTCPServer();
}
});
.
.
.
.
}


@Override
public void onMessageReceived_TCPserver(byte[] b, String id,
Socket remote) {


}

@Override
public void onClientConnected(final String id) {
System.out.println("id");
EventQueue.invokeLater(new Runnable() {
public void run() {
comboBoxClients.addItem(id);
}
});

}

@Override
public void onClientDisconnected(final String id) {



}

@Override
public void errorDetectedTCPserver(String errmsg) {


}
}

因此,每次有新客户端连接时,都会执行 onClientConnected 方法中的代码。我知道代码确实被执行了,因为它打印了客户端的 id,但组合框永远不会升级(无论我是否更改 EDT 线程内的接口(interface))。我还检查了插入前后的combobox.itemcount,是插入item,只是没有升级界面。

我还尝试了这里建议的许多解决方案,例如使用刷新、验证、重新验证和长时间等。

所以,这是怎么回事?是因为该事件是从另一个对象中的线程触发的吗??

最佳答案

您似乎正在创建两个 mainapp 实例,一个在 main 方法中,另一个在 startTCPServer 中。

大概是在显示的 main 方法中创建的实例,而在连接客户端套接字时接收回调的 startTCPServer 中创建的实例。

在方法 startTCPServer 中,行:

TCPServer= new tcpServer(new mainapp(), "");

应该阅读:

TCPServer= new tcpServer(this, "");

关于java - 当另一个对象中的线程触发事件时,Swing 接口(interface)不更新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409768/

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