gpt4 book ai didi

java - 使用线程时 Swing GUI 不显示

转载 作者:行者123 更新时间:2023-12-02 06:43:21 24 4
gpt4 key购买 nike

我正在编写一个 IRC 客户端来娱乐,这是程序线程的基本轮廓:

  • 主 Swing 线程
  • 服务器输出的线程
  • (未完成)服务器输入的线程

问题是,当我使用 Thread.start() 启动线程时,它不显示我的 swing gui。我仍然看到调试消息,但 JFrame 上没有任何组件。如果有帮助,这是我的线程代码(我正在使用 O'Reilly java hack 代码:

try{
// Connect directly to the IRC server.
Socket socket = new Socket(server, 6667);
final BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream( )));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream( )));

//pause for a second so that the gui can do its thing
this.sleep(500);

// Log on to the server.
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + login + " 8 * : IRC Custom Client-" + "\r\n");
writer.flush( );

System.out.println("hi this is to verify bla.");

appendTo.append("Sent login request.");

// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
appendTo.append(line);
if (line.indexOf("004") >= 0) {
appendTo.append("You are now logged in!");
}
else if (line.indexOf("433") >= 0) {
appendTo.append("Nickname is already in use.");
return;
}
else if (line.contains("PING")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " : Pinged!!\r\n");
writer.flush( );
}
//after we read the line, sleep.
sleep(10);
}

// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );


// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
appendTo.append(line);
if (line.contains("PING")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " :I got pinged!\r\n");
writer.flush( );
}
else {
// Print the raw line received by the bot.
appendTo.append(line);
}
sleep(10);
}

socket.close();
writer.close();
reader.close();
}
catch (Exception e){

}

这是我启动线程的方式:

new Thread(){

public void run(){
try {
connectToIRC(nickname, login, server, channel);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}.start();

最佳答案

您不应该从主线程以外的线程更新 swing UI。要从其他线程更新 UI,请使用 SwingWorker 类。检查this文章。

关于java - 使用线程时 Swing GUI 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901148/

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