从Swing按钮ActionPerformed访问DatagramSocket对象

时间:2013-03-30 17:41:56

标签: java swing sockets udp

我正在使用swing jFrame为我的客户端 - 服务器预订系统创建GUI。我在客户端遇到了问题,我想使用在此声明的DatagramSocket:

public BookingClientUI() throws SocketException {
        DatagramSocket clientSocket = new DatagramSocket(9876);
        initComponents();
        RecvPacket recvProcess = new RecvPacket(clientSocket);
        Thread recvThread = new Thread(recvProcess);
        recvThread.start();
}

稍后在此按钮ActionPerformed:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        String passwordString = new String(passwordfield.getPassword());
        byte[] passwordBytes = passwordString.getBytes();
        byte[] packetData = new byte[1500];
        packetData = SendPacketHandler.packetConstructor(SendOpcodes.REGISTER_USER,usernamefield.getText(),EncryptionHandler.hashPassword(passwordBytes));
        DatagramPacket packet = new DatagramPacket(packetData,packetData.length,InetAddress.getByName("127.0.0.1"),9876);
        clientSocket.send(packet);
    } catch (NoSuchAlgorithmException | UnknownHostException | IOException ex) {
        Logger.getLogger(BookingClientUI.class.getName()).log(Level.SEVERE, null, ex);
    }

}    

显然,行:

        clientSocket.send(packet);

有一个“找不到符号”错误,因为声明的DatagramSocket不在范围内。然而,我不知道如何解决这个问题,因为我只用Java编程了几天。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您只需将套接字存储到稍后可由按钮处理程序访问的类的数据成员中。你还没有详细解释你的类层次结构来说明如何做到这一点。如果按钮处理程序在BookingClientUI内,那很简单。你会有类似的东西:

public BookingClientUI() extends JFrame {

  final DatagramSocket clientSocket;

  public BookingClientUI() throws SocketException {
    // Initialize the data member with the open socket.
    clientSocket = new DatagramSocket(9876);
    initComponents();
    RecvPacket recvProcess = new RecvPacket(clientSocket);
    Thread recvThread = new Thread(recvProcess);
    recvThread.start();
  }

  // Any member function can now use clientSocket, including a button action.

}

在所有这些中,不要忘记(几乎)所有Swing代码必须在UI线程中运行。