如何知道是否选中了Jcheckbox? [英] How do i know if a Jcheckbox is checked?with GUI
问题描述
你能告诉我详细信息我怎么知道一个jcheckbox是否被选中?方法isSelected不能与我一起工作,它在运行时给我一个异常
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()){//
....................
}
正在运行:
此处
您可以帮助我解决这个问题?
can you please help me with this 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);
由于赋值前的JCheckBox,这段代码声明了局部变量叫做番茄酱大蒜。
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.
同时,ClassName(ProjectInterface?)的私有字段具有相同的名称,但在其他方面不相关。
Meanwhile, the private fields of ClassName (ProjectInterface?) have the same names but are otherwise unrelated. They are left null.
将上述代码移到ClassName构造函数中,并删除赋值前面的JCheckBox。所以你会有:
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);
}
这篇关于如何知道是否选中了Jcheckbox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!