gpt4 book ai didi

Java 图形用户界面正在卡住

转载 作者:行者123 更新时间:2023-11-29 09:49:59 26 4
gpt4 key购买 nike

为什么当我单击“输入”执行我的程序时,我的应用程序卡住了?

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import java.io.*;
import java.net.*;

public class KnockKnockUI{

private Socket kkSocket = null;
private PrintWriter out = null;
private BufferedReader in = null;
JTextArea clientArea;
JTextArea serverArea;
public KnockKnockUI(){

establishConnection();
initComponents();

}

public void initComponents(){

JFrame frame = new JFrame("Chat");
frame.setVisible(true);
frame.setSize(320,189);
frame.getContentPane().setLayout(null);

serverArea = new JTextArea();
serverArea.setLineWrap(true);
serverArea.setBounds(10, 11, 284, 45);
frame.getContentPane().add(serverArea);

clientArea = new JTextArea();
clientArea.setBounds(10, 67, 284, 46);
frame.getContentPane().add(clientArea);

JButton btnEnter = new JButton("Enter");
btnEnter.setBounds(96, 124, 89, 23);
frame.getContentPane().add(btnEnter);

btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
in.readLine();
}catch(Exception e){

}
String fromUser = clientArea.getText();
try {
fromUser = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
serverArea.setText(fromUser);
}
});

}

public void establishConnection(){

//Establishes Connection
try {
kkSocket = new Socket("localhost", 4444);
//
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}

}
public static void main(String[] args){
KnockKnockUI ui = new KnockKnockUI();
}
}

这是一个使用 Java 的简单聊天客户端,还有其他我没有包含的类。像服务器类和协议(protocol)类

最佳答案

当您按下回车键时,将执行以下操作:

try {
in.readLine();
} catch (Exception e) {
}

String fromUser = clientArea.getText();

try {
fromUser = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}

serverArea.setText(fromUser);

这段代码正在 Event Dispatch Thread 上执行,它处理所有 Swing 事件。您对 in.readLine() 的调用将阻塞,直到从您的 Socket 获得一行输入,导致未处理的事件备份,从而导致您的程序停止响应。如果您想执行耗时的任务,请查看 SwingWorker (SwingWorker tutorial)。

旁注:捕获 Exception 而不打印其堆栈跟踪几乎总是一个坏主意。如果不是不可能的话,它会使您的代码问题更难发现。

关于Java 图形用户界面正在卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9406636/

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