我正在尝试实现一个 JButton,根据它是否连接到服务器来显示“连接”或“断开连接”。因此,当我单击“连接”按钮时,它将连接到服务器,然后显示“断开连接”。当我单击“断开连接”时,它将与服务器断开连接,并且按钮将再次显示“连接”。但是,当我单击按钮时,什么也没有发生。
btnConnect.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if (btnConnect.getText().equals("Connect")){
btnConnect.setText("Disconnect");
try {
int portNum = 5520;
String hostAddress = Actual_IP_Address.getText();
sock = new Socket(hostAddress, portNum);
writeSock = new PrintWriter ( sock.getOutputStream(), true);
readSock = new BufferedReader (new InputStreamReader(sock.getInputStream()));
}
catch(Exception ex) {
System.out.println("Error: " + ex);
sock = null;
}
}
if (btnConnect.getText().equals("Disconnect")){
btnConnect.setText("Connect");
try {
readSock.close();
writeSock.close();
sock.close();
sock = null;
}
catch(Exception ex) {
System.out.println("Error: " + ex);
sock = null;
}
}
}}
);
为什么当我单击按钮时它只显示“连接”?
呼如林
DIEA
相关分类