【问题标题】:Add an event for button为按钮添加事件
【发布时间】:2016-03-17 04:26:56
【问题描述】:

当用户单击应用程序运行的 jbutton1 并且 jbutton1 的文本从“连接”更改为“断开连接”时,我的 jbutton1 具有文本“连接”。现在再次当用户单击 jbutton1 并且文本是“断开连接”时,应用程序应该关闭。

我在这里给出的代码不会检查它会自动关闭我不想要的应用程序的任何内容。我想检查按钮的文本,如果它是连接的,我应该做一个不同的过程,如果它是断开的,它应该在单击按钮时关闭我的应用程序。

  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);
}

【问题讨论】:

标签: java swing jbutton


【解决方案1】:

只需将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

【讨论】:

  • 谢谢你的回答,它工作正常。但是现在,一旦我单击断开连接,我给 n 运行时的文件夹就会再次打开
  • @SruthiAcg:将if 块移动到事件处理程序的顶部
【解决方案2】:

这是错误的 if(jButton1.getText()== "Disconnect") ,看看this great answer 看看原因并学习如何在java中比较字符串

你应该这样做:

if("Disconnect".equalsIgnoreCase(jButton1.getText()))

改为

【讨论】:

  • 在这种情况下,== 实际上按预期工作,因为字符串文字是内部化的。
  • @ammoQ 但这是个坏习惯
  • 在这种情况下,PO 只是运气好,但其意图是比较内容而不是参考。作为@MadProgrammer cmets,这是一个坏习惯,会破坏应用程序,并且会带来难以发现的错误......
  • MadProgrammer:我同意。无论如何,我不喜欢通过检查按钮上的文本来测试程序内部状态的想法,因此将== 替换为equals 仍然不能使它成为一个好程序。
  • @Xoce웃Пepeúpa 我只是指出了这一点,因为您的回答并不能解决手头的问题。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多