简体   繁体   English

为什么按下此JButton后没有响应?

[英]Why is this JButton not responding after being pressed?

I am in the early stages of working with a server and client connections through sockets. 我处于通过套接字处理服务器和客户端连接的早期阶段。 In my "ServerMain" class, I give the server a port to run on through a JTextField, which enters it through an ActionListener on a JButton. 在我的“ ServerMain”类中,我为服务器提供了一个端口,该端口可通过JTextField运行,该端口通过JButton上的ActionListener进入该端口。 As soon as I press the button, it greys out, and the JTextArea below it stops appending text. 一旦按下按钮,它就会变灰,并且它下面的JTextArea会停止添加文本。 What changes do I need to make so that the button and textarea both continue working after the server starts up? 我需要进行哪些更改,以便服务器启动后按钮和文本区域都能继续工作?

ServerMain: ServerMain:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class ServerMain extends JFrame{

  GraphicPanel m;
  final static String newLine = "\n";
  public static void main(String[] args) {

    ServerMain s = new ServerMain("Testing Server");
    s.setUpUI();
    s.pack();
    s.setVisible(true);
  }

  private void setUpUI() {
      m = new GraphicPanel(this);
      m.initialize();
      this.add(m);
      this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
  }
  public void hostPort(String port){
    System.out.println("Running hostPort method");
    int p=-1;
    try{
         p= Integer.parseInt(port);
    }
    catch(Exception e){
        JOptionPane.showInternalMessageDialog(this, "Must enter a number(0 - 65500) for the port");

    }
    m.print(""+p);
    m.print("Running Try.");
    try {
        System.out.println("About to create socket");
        @SuppressWarnings("resource")

        ServerSocket serverSocket = new ServerSocket(p);
        m.print("got the socket."+serverSocket);
        Socket[] clientSocket = new Socket[2];
        clientSocket[0] = serverSocket.accept();
        clientSocket[1] = serverSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket[0].getInputStream()));
        m.print("Server Socket Initialized.");
        System.out.println("S");
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            m.print(inputLine);
            m.print("Client: "+in.readLine());
        }
    }
    catch (IOException e) {
        m.print("Exception caught when trying to listen on port "
                + port + " or listening for a connection "+newLine+e+newLine);
        m.print(e.getMessage());
    }

}

  public ServerMain(String s){
      super(s);
  }

}

And finally the GraphicPanel: 最后是GraphicPanel:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class GraphicPanel extends JPanel{
  private String ip = "";
  private String port = "";
  private JTextField txt_port = new javax.swing.JTextField(20);
  private JTextArea txa_info;
  private JButton but_conDC;
  private ServerMain s;
  final static String newLine = "\n";
  public GraphicPanel(ServerMain serv){
      this.s = serv;
      this.setPreferredSize(new Dimension(800,200));
  }

  public void initialize(){

      txa_info = new JTextArea(10,70);
      but_conDC = new JButton("Connect");
      txt_port.setLocation(100, 100);

      add(txt_port);
      but_conDC.addActionListener(new ActionListener(){

          @Override
          public void actionPerformed(ActionEvent e) {
              port = txt_port.getText();
              System.out.println(port + " was in the text box");
              if(port.equals("")){
                  emptyPort();
                  return;
              }
              but_conDC.setText("Disconnect");
              repaint();
              txa_info.setText("Hosting on port "+port);
              s.hostPort(port);
          }
      });
      but_conDC.setSize(5, 5);
      add(but_conDC);
      txa_info.setSize(800, 100);
      txa_info.setEditable(false);

      add(txa_info);
  }

  public void print(String s){
      txa_info.append(s);
  }

  public void emptyPort() {
      txa_info.append("ERROR: Attempted to host with no port! Try entering something like 4444"+newLine);
  }
}

In your button's action, you basically open a server socket and wait for some communication. 在操作按钮时,基本上是打开服务器套接字并等待一些通信。 As you do this in the same thread as the UI is in, you block the tread, and make further interaction with the UI impossible. 当您在与UI相同的线程中执行此操作时,您将踩到踏板,并无法与UI进行进一步的交互。

You'll need to start a different thread and go into inter-thread communication between the UI-thread (called AWT Event Handler Thread in Java, in case you want to look it up) and whichever thread you start for your communication. 您将需要启动一个不同的线程,并进入UI线程(在Java中称为AWT事件处理程序线程,以防您要查找它)与为通信而启动的任何线程之间进行线程间通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM