这篇文章似乎是重复的,但我不理解同样的解决方案。我无法理解为什么jbutton只在我点击两次时才有效。
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String address = jTextField1.getText();
Socket sock = null;
try {
InetAddress addr;
sock = new Socket(address, 80);
addr = sock.getInetAddress();
sock.close();
jLabel2.setText("Status: Online");
} catch (IOException ex) {
jLabel2.setText("Status: Offline");
}
}
});
}
答案 0 :(得分:1)
jButton1MouseClicked
会建议已通过Netbeans在按钮上注册MouseListener
。
使用ActionListener
处理程序删除jButton1MouseClicked
的注册...
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String address = jTextField1.getText();
Socket sock = null;
try {
InetAddress addr;
sock = new Socket(address, 80);
addr = sock.getInetAddress();
sock.close();
jLabel2.setText("Status: Online");
} catch (IOException ex) {
jLabel2.setText("Status: Offline");
}
}
话虽如此,请返回Netbeans表单编辑器并删除与该按钮关联的mouseClicked
处理程序,并手动添加ActionListener
(在调用initComponents
之后)或& #34;动作"处理程序通过Netbeans表单编辑器
原因是,按钮可以通过其他方式操作,例如键盘