我得到的主要问题是无法在静态函数sendReceivedata中设置标签... netbeans为所有jcomponents生成的代码是私有的我无法修改它们并且如果我在构造函数中调用sendReceivedata函数 然后程序将执行但不显示gui
主要问题:无法在静态功能中设置标签
public class Server extends javax.swing.JFrame {
static public Socket socket;
public static void sendReceivedata()
{
try
{
ServerSocket serverSocket=new ServerSocket(8181);
jLabel2.setText("Server is waiting for Connection");
while(true)
{
//waiting for connection
socket = serverSocket.accept();
jLabel3.setText("Connected");
//ready for reading message from client
System.out.println("Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String receivemsg=br.readLine();
String receivemsg1=br.readLine();
jLabel4.setText("Data Receive From Client is ");
jLabel5.setText(receivemsg);
jLabel6.setText(receivemsg1);
}
}
catch(Exception e)
{
System.out.println("ab "+e);
}
}
public Server()
{
super("Server Side");
initComponents();
}
public static void main(String args[])
{
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Server().setVisible(true);
}
});
sendReceivedata();
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
答案 0 :(得分:0)
问题是sendReceivedata()
未使用事件调度程序线程(EDT)上下文执行,该上下文是负责更新图形的线程因此,您执行的任何UI操作都不会显示。
要解决此问题,您需要使用SwingUtilities.invokeLater(Runnable run)
。因为,在你的情况下,你正在更新多个标签,我建议你为每个标签都有一个方法,如下所示:
private static updateJLabel2(final String text) {
final JLabel l = jLabel2;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
l.setText(text);
}
}
}
并称之为:
try {
ServerSocket serverSocket=new ServerSocket(8181);
updateJLabel2("Server is waiting for Connection");
...
作为附注,请为您的标签提供更多相关名称。
另外请注意,请不要在sendReceivedata();
之后放置new Server().setVisible(true);
。虽然这样做应与我的答案具有相同的影响,但你也会在UI线程上进行非UI操作,这会导致你的界面冻结。