我正在尝试通过LAN创建消息传递应用程序。在AppHost
下,我正在为HostUI
和HostConnect
运行并发线程(一个用于显示UI,另一个用于接收/管理传入和传出连接)。我正在尝试将所有这些类编写为单例类。
我正在尝试使用JTextField(ipField)
在HostUI
setText()
上显示服务器IP地址。然而,在setText()
之后,尽管getText()
ipField
将返回新文本,但UI窗口不会显示更新的文本。
以下是三个类的代码:
APPHOST:
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);
}
}
}
HostConnect:
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;
}
}
HostUI:
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());
}
答案 0 :(得分:0)
与Swing组件(getter或setter)交互时,必须确保从Event Dispatch Thread调用方法。
如果没有,请使用invokeLater:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ipField.setText(addr);
}
});