【发布时间】:2018-01-10 19:07:38
【问题描述】:
我正在制作一个带有与客户端连接的 GUI 的聊天服务器
GUI 由两个文本框组成,一个用于接收文本,一个用于发送文本。最后一件事是发送按钮,我现在遇到了问题。
发送按钮在被按下且消息未发送时冻结(GUI 仍然有效,它只是冻结的按钮)。
我不知道在这里做什么,希望你们能帮助我。任何帮助表示赞赏,谢谢!
代码:
class UdpServer
{
PrintWriter out;
ButtonHandler txButtonHandler;
BufferedReader in;
DatagramSocket socket;
InetAddress ip = null;
int port;
UdpServer (String gport) throws IOException
{
int i = 0;
socket = new DatagramSocket (Integer.parseInt (gport));
txButtonHandler = new ButtonHandler ();
sendButton.addActionListener (txButtonHandler);
new Thread ()
{
public void run ()
{
try
{
rx ();
}
catch (IOException e)
{
}
}
}.start ();
tx ();
System.exit (1);
}
void tx () throws IOException
{
byte[] buf = new byte[256];
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
String toServer;
do
{
toServer = in.readLine();
toServer = toServer + "\n";
buf = toServer.getBytes ();
DatagramPacket packet = new DatagramPacket (buf, toServer.length(), ip, port);
if (ip != null) socket.send(packet);
}
while (toServer != null);
socket.close ();
System.exit (1);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event) //throws IOException
{
try{tx ();} catch (IOException e){}
}
}
void rx () throws IOException
{
byte[] buf = new byte[256];
String fromServer;
do
{
for (int i = 0; i < 256; i ++) buf[i] = 0;
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
fromServer = new String (packet.getData());
ip = packet.getAddress ();
port = packet.getPort ();
//System.out.println (port + ":" + ip);
if (fromServer != null) System.out.print (fromServer);
}
while (fromServer != null);
socket.close ();
System.exit (1);
}
}
【问题讨论】:
-
从一个好的教程中学习如何在 Swing 中进行线程化;在 Internet 上搜索时的一个基本示例给出了此链接:javamex.com/tutorials/threads/swing_ui.shtml
-
@Am_I_Helpful 我从未在 Swing 中完成线程,我将如何开始我的代码?
-
这就是为什么我要求您首先通过教程学习,完全理解它们,然后在您了解 Swing 的线程模型后继续自己的开发。
标签: java button handler actionlistener