我正在尝试使用基本的GUI在此处生成UDP服务器。我遇到的问题是将Datagram
套接字从main方法移到其自己的方法时,可以将GUI停止显示的内容输出到jTextArea
了。我相信它与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中完成。您可以在上面链接的文档中检查如何完成。