gpt4 book ai didi

java - Swing 表单无法正确显示

转载 作者:行者123 更新时间:2023-11-30 06:15:09 24 4
gpt4 key购买 nike

我正在尝试使用基本的 GUI 生成 UDP 服务器。我遇到的问题是,当我将 Datagram 套接字从 main 方法移动到它自己的方法时,以便我可以输出到 jTextArea 我的 GUI 停止显示。我相信它与 setVisible(true) 有关,但无论我做什么,我似乎都无法让它正确显示,任何帮助将不胜感激

package Assignment1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UDPServer extends javax.swing.JFrame {

public UDPServer() throws IOException {
initComponents();
setVisible(true);
FileRead();
runServer();
}


/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

ClearLog = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
TextArea = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

ClearLog.setText("Clear Log");
ClearLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClearLogActionPerformed(evt);
}
});

TextArea.setColumns(20);
TextArea.setRows(5);
jScrollPane1.setViewportView(TextArea);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addComponent(ClearLog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(ClearLog)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void ClearLogActionPerformed(java.awt.event.ActionEvent evt) {
TextArea.setText("");
}

public static void main(String args[]) throws IOException {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
/* try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(UDPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UDPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UDPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UDPServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new UDPServer().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(UDPServer.class.getName()).log(Level.SEVERE, null, ex);
}


}
}

);
}



public void FileRead() throws IOException {

String file_name = "C:/Users/Ross/Documents/NetBeansProjects/Assignment1/src/Assignment1/Data.txt";

try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();

int i;
for (i=0; i < aryLines.length; i++) {
System.out.println(aryLines[i]);
}
}
catch (IOException e) {
System.out.println( e.getMessage());
}
}

public void runServer(){

try(DatagramSocket aSocket = new DatagramSocket(8789)) {

byte[] buffer = new byte[1000];

DatagramPacket request = new DatagramPacket(buffer, buffer.length);

while(true)
{
aSocket.receive(request);
TextArea.setText("Client Request: " + new String(request.getData(), 0, request.getLength()));
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),
request.getAddress(), request.getPort());
aSocket.send(reply);
}
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e) {System.out.println("IO: " + e.getMessage());
}
}

public void SetText(){

TextArea.setText("Hello");
TextArea.append("This is a test");

}

// Variables declaration - do not modify
private javax.swing.JButton ClearLog;
private javax.swing.JTextArea TextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}

最佳答案

发生这种情况是因为您正在调用 The Event Dispatch Thread 上的 runServer 方法。 。如果 runServer 方法阻塞,那么您的用户界面将不会更新。

一个快速解决方案是按如下方式更新构造函数,以便 runServer 在其自己的线程中运行。

public UDPServer() throws IOException {
initComponents();
setVisible(true);
FileRead();
new Thread(()->runServer()).start();
}

但是您应该在 EDT 中进行任何 UI 更新。例如,TextArea.setTex 应在 EDT 中完成。您可以在上面链接的文档中查看如何完成此操作。

关于java - Swing 表单无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49380054/

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