【问题标题】:How do i know if a Jcheckbox is checked?in GUI [closed]我如何知道是否选中了 Jcheckbox?在 GUI [关闭]
【发布时间】:2023-04-11 03:21:02
【问题描述】:

你能详细告诉我如何知道 jcheckbox 是否被选中?方法 isSelected 对我不起作用它在运行时给了我一个异常

{
 Sandwich = new JButton("Tall");
         contentPane.add(Tall);
         Sandwitch.setBounds(350, 110, 90,40);   //in main
         Sandwitch.addActionListener(this);

}
.....

public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();

        String  buttonText = clickedButton.getText();
..........
if(clickedButton.getText()=="Sandwitch"){
        if(Ketchup.getState()&&!Garlic.getState()){//

       itm=new Item(""+m+clickedButton.getText(),3.0);
        xyz.addItem(itm);
       textArea.append(" "+clickedButton.getText()+",");
        textArea.append(" "+itm.getPrice()+"\n");}

          else if(!Ketchup.isSelected()&&Garlic.isSelected()){//

....................
}

它在运行时给出了一个很长的异常

你能帮我解决这个问题吗?

【问题讨论】:

  • 什么是异常??
  • 异常说明了什么......空指针???
  • 你说的非常长的异常是什么意思?
  • 在不知道您遇到的异常情况下,没有人可以帮助您。

标签: java user-interface checkbox jgrasp


【解决方案1】:

不要使用== 来比较字符串!

if (clickedButton.getText()=="Sandwitch"){}

使用equalsequalsIgnoreCase()

if ("Sandwich".equalsIgnoreCase(clickedButton.getText()){
    // do something
}

【讨论】:

  • -1,这不会删除 OP 的异常。
  • 这并没有帮助我摆脱异常。
  • @user3049389 您从未发布过您的异常。我们应该如何知道异常是什么?考虑发布SCCEE 以获得更多帮助。
  • 您在stackoverflow.com/questions/20289002/… 发布了相同的问题,空指针可能是由于某些对象(可能是复选框本身)尚未启动...
猜你喜欢
  • 2013-12-15
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 2015-11-30
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多