![](/img/trans.png)
[英]Java swing JTable doesn't show scroll bar when using JScrollPane
[英]Swing GUI doesn't show when using thread
我正在為一個有趣的IRC客戶端編程,這是程序線程的基本概要:
問題是,當我使用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類。 看看這篇文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.