gpt4 book ai didi

执行网络代码后 Java UI 白屏

转载 作者:行者123 更新时间:2023-12-02 06:05:36 27 4
gpt4 key购买 nike

我想在我的游戏中实现网络功能,但是我有一个很大的问题。当我尝试创建 JFrame 组件时,执行网络代码后,它总是显示为白屏。虽然网络可以工作,但我无法以任何方式让用户界面工作。这是网络代码:

package progtech2bea;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class NetworkController implements Runnable {

public Main base;
private MainMenu mm;
private String ip;
private int port = 22222;
public int pnum;

private Thread thread;
private Socket socket;
private DataOutputStream os;
private DataInputStream is;

private ServerSocket serversocket;

private int errcount = 0;
private boolean commerror;

private boolean client;
private boolean accepted = false;

public void beginServer(String ip, MainMenu mm)
{
this.ip = ip;
this.mm = mm;
if (!connect()) {
initalizeServer();
pnum = 1;
}
else
{
pnum = 2;
}

thread = new Thread(this, "WaterWar");
thread.run();
}

@Override
public void run() {
while (true) {
tick();
//m.repaint();

if (!client && !accepted) {
listenServerRequest();
}
}

}

private boolean connect() {
try {
socket = new Socket(ip, port);
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
accepted = true;
mm.dispose();
base.showMain();
base.moveToP2StartView();
System.out.println("Successfully connected");
} catch (IOException e) {
System.out.println("No active server, initalizing new one");
return false;
}

return true;
}

private void initalizeServer() {
try {
serversocket = new ServerSocket(port, 8, InetAddress.getByName(ip));
} catch (Exception e) {
System.out.println("Error initalizing the server");
}

client = false;
}

public void listenServerRequest() {
Socket s = null;

try {
s = serversocket.accept();
os = new DataOutputStream(s.getOutputStream());
is = new DataInputStream(s.getInputStream());
accepted = true;
System.out.println("The client successfully connected");
base.showMain();
mm.dispose();
} catch (IOException e) {
System.out.println("Error");
}
}

public void tick() {

}
}

如果网络代码没有运行,jFrame 工作得很好。以下内容不起作用,它会在单独的类中调用:

//the jFrame component initalizing all the UI elements inside
Main m = new Main(jTextField1.getText(),jComboBox1.getSelectedIndex());
//calls the NetworkController's beginServer() method, trying to establish
//connection/start a server
nc.beginServer(jTextField2.getText(),this);

有什么问题吗?

最佳答案

想通了。必须在此可运行对象之外进行线程初始化,然后将其运行为:

Thread t = new Thread(new Runnable() {...});
t.start();

关于执行网络代码后 Java UI 白屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942044/

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