为按钮添加事件
Add an event for button
我有一个 jbutton1,它有一个文本 "Connect",当用户单击 jbutton1 时应用程序运行并且 jbutton1 的文本从 "Connect" 变为 "Disconnect"。现在,当用户再次单击 jbutton1 并且文本为 "Disconnect" 时,应用程序应该关闭。
我在此处提供的代码不会检查任何内容,它会自动关闭我不需要的应用程序。我想检查按钮的文本,如果它是连接的,我应该做一个不同的过程,如果它是断开的,它应该在单击按钮时关闭我的应用程序。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jComboBox2.getSelectedItem()==null)
{
System.out.println("Select one name");
}
else
{
try {
Runtime r = Runtime.getRuntime();
p = Runtime.getRuntime().exec("C:\Program Files");
AS a4sObj = new AS(new String[]{jComboBox2.getSelectedItem().toString()});
} catch (IOException ex) {
Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
这是错误的
if(jButton1.getText()== "Disconnect")
,看看 this great answer 来检查原因并学习如何比较 java
中的字符串
你应该这样做:
if("Disconnect".equalsIgnoreCase(jButton1.getText()))
改为
直接把setText
移到最后:
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
我有一个 jbutton1,它有一个文本 "Connect",当用户单击 jbutton1 时应用程序运行并且 jbutton1 的文本从 "Connect" 变为 "Disconnect"。现在,当用户再次单击 jbutton1 并且文本为 "Disconnect" 时,应用程序应该关闭。
我在此处提供的代码不会检查任何内容,它会自动关闭我不需要的应用程序。我想检查按钮的文本,如果它是连接的,我应该做一个不同的过程,如果它是断开的,它应该在单击按钮时关闭我的应用程序。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jComboBox2.getSelectedItem()==null)
{
System.out.println("Select one name");
}
else
{
try {
Runtime r = Runtime.getRuntime();
p = Runtime.getRuntime().exec("C:\Program Files");
AS a4sObj = new AS(new String[]{jComboBox2.getSelectedItem().toString()});
} catch (IOException ex) {
Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
这是错误的
if(jButton1.getText()== "Disconnect")
,看看 this great answer 来检查原因并学习如何比较 java
你应该这样做:
if("Disconnect".equalsIgnoreCase(jButton1.getText()))
改为
直接把setText
移到最后:
if(jButton1.getText()== "Disconnect") // I wanted to change this line of code
{
System.exit(0);
}
jButton1.setText("Disconnect"); //This sets connect button to disconnect