How do i know if a Jcheckbox is checked?with GUI [

2019-09-23 01:40发布

This question already has an answer here:

can you tell me in details how do i know if a jcheckbox is checked or not? method isSelected didn't work with me it gives me an exception while running

{
    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()){//

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

it gives this very long exception while running: Here

can you please help me with this problem?

The code you Boann asked me about

1条回答
时光不老,我们不散
2楼-- · 2019-09-23 02:12

Here is the problem:

JCheckBox Ketchup = new JCheckBox();
Ketchup.setText("Ketchup");
Ketchup.setSize(50,25);
contentPane.add(Ketchup);
Ketchup.setBounds(175, 100, 175,25);

JCheckBox Garlic = new JCheckBox();
Garlic.setText("Garlic");
Garlic.setSize(50,25);
contentPane.add(Garlic);
Garlic.setBounds(175, 120, 175,25);

Because of the "JCheckBox" in front of the assignments, this code is declaring local variables called Ketchup and Garlic. Outside the method, those variables don't exist any more.

Meanwhile, the private fields of ClassName (ProjectInterface?) have the same names but are otherwise unrelated. They are left null.

Move the above code into the ClassName constructor, and remove the "JCheckBox" in front of the assignments. So you'll have:

private JCheckBox Ketchup;
private JCheckBox Garlic;

public ClassName() {
    Ketchup = new JCheckBox();
    Ketchup.setText("Ketchup");
    Ketchup.setSize(50,25);
    add(Ketchup);
    Ketchup.setBounds(175, 100, 175,25);

    Garlic = new JCheckBox();
    Garlic.setText("Garlic");
    Garlic.setSize(50,25);
    add(Garlic);
    Garlic.setBounds(175, 120, 175,25);
}
查看更多
登录 后发表回答