gpt4 book ai didi

Java gui,尝试转换为 gui 时的客户端问题

转载 作者:行者123 更新时间:2023-12-02 04:54:45 25 4
gpt4 key购买 nike

我用java制作了一个客户端/服务器程序,我已经按照我想要的方式使用cmd完美地工作了,现在我正在尝试将代码的客户端转换为GUI,但是我在打印时遇到问题客户端消息并从文本字段和服务器消息读取客户端输入,这是我到目前为止所做的,编译时没有错误,但 gui 它本身不运行,任何帮助都是值得赞赏的。这是客户端代码:

import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;

public class TcpClient
{

public static void main(String[] args)
{

try
{
new TcpClient().start();
}

catch(Exception e)
{
System.out.println("Major Error" + e.getMessage());
e.printStackTrace();
}

}

public void start() throws IOException
{
JFrame build = new JFrame("Client");
JTextField serv = new JTextField();
JTextField clie = new JTextField();
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

serv.setBounds(50,210,300,50);
build.add(serv);

clie.setBounds(350,210,300,50);
build.add(clie);
//=====================================================================
Socket clientSocket = null;
InetAddress hostA = null;
PrintWriter clientOutput = null;
BufferedReader clientInput = null;
BufferedReader standardInput = null;
try
{

hostA = InetAddress.getLocalHost();
clientSocket = new Socket(hostA.getHostName(), 5600);
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new PrintWriter(clientSocket.getOutputStream(), true);
standardInput = new BufferedReader(new InputStreamReader(System.in));
String serverMsg, clientMsg;

//read from a socket and respond back to server
while((serverMsg = clientInput.readLine()) != null)
{
serv.setText("Server Saying - " + serverMsg);
if(serverMsg.equals("exit"))
break;

clientMsg = standardInput.readLine();
if(clientMsg != null)
{
clie.setText("Client Saying - " + clientMsg);
clientOutput.println(clientMsg);
}
}

}

catch(UnknownHostException e)
{

System.exit(1);
}

catch(IOException e)
{

System.exit(1);
}

finally
{
//clean up time
clientOutput.close();
clientInput.close();
standardInput.close();
clientSocket.close();

}
//=====================================================================
build.setLayout(null);
build.setSize(700,600);
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
build.setVisible(true);
build.setResizable(false);
}
}

最佳答案

正如评论中提到的,您应该学习多线程,尤其是 EDT

现在发生的事情是你的代码和 GUI 互相妨碍正常工作。通过让 GUI 在 EDT 上运行,您的应用程序可以在不阻碍 GUI 的情况下运行。当应用程序有与您的 GUI 相关的报告更改时,您只需在时机到来时通知 EDT。

关于Java gui,尝试转换为 gui 时的客户端问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28898418/

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