[英]How to find out which automatic generated checkbox is selected?
I must create a hardware shop in java where a customer can select items he wants to order from a list with checkboxes and the quantity with spinners. 我必须在Java中创建一个五金店,客户可以在其中从带有复选框的列表中选择要订购的物品,并从微调器中选择要订购的物品。 I can generate the list of items through a for-loop (the items come from a Query to the database and return in an arrayList)
我可以通过for循环生成项目列表(这些项目从Query到数据库并返回到arrayList中)
this is my for loop: 这是我的for循环:
ArrayList stringList = new ArrayList();
stringList = cond.getOnderdelen(); // he gets the items from the database (method in other class)
itemArea.add(new JLabel("Naam en prijs")); // itemArea is my JPanel
for (int i = 0; i < stringList.size(); i++) {
System.out.println(stringList.get(i));
String item = (String) stringList.get(i);
String checknummer = Integer.toString(i);
check = new JCheckBox(checknummer);
check.setText(item);
JSpinner spin = new JSpinner();
itemArea.setLayout(new BoxLayout(itemArea, BoxLayout.Y_AXIS));
itemArea.add(check); // I add the components to the JPanel..
itemArea.add(spin);
I get a nice boxlayout with 10+ items. 我得到了一个不错的BoxLayout,包含10多个项目。 But now the tricky part: how to know which checkbox is selected??
但是现在棘手的部分是:如何知道选中了哪个复选框? So I can make a button MAKE ORDER.
所以我可以按一下按钮。 It can only find the value of the last generated checkbutton ( so from the last item of the database)
它只能找到最后生成的检查按钮的值(因此从数据库的最后一项开始)
if(e.getSource() == orderBtn)
{
System.out.println("Button has been pressed");
state = check.isSelected(); // state is a boolean variable.
if(state == true)
{
System.out.println("True: checkbox is selected!");
}
The problem would be solved if I can make more checkboxes with variabel names, like with the counter 'i' from the FOR loop. 如果我可以创建更多带有可变名称的复选框,例如FOR循环中的计数器“ i”,则将解决该问题。 Then I can check whether checkbox1, checkbox2, checkbox3.
然后,我可以检查checkbox1,checkbox2,checkbox3。 .. is selected?
..被选中? But how?
但是如何?
Thanks in advance, Diederik Verstraete Student Business Engineer Ghent 在此先感谢Diederik Verstraete学生业务工程师Ghent
You can make multiple checkboxes and save them for later use in an array or collection. 您可以创建多个复选框,并将其保存以供以后在数组或集合中使用。 If you ActionListener is external to your class above, you will have to pass in the collection of checkboxes to the ActionListener somehow.
如果您的ActionListener在上述类的外部,则必须以某种方式将复选框集合传递给ActionListener。 If you use an anonymous one though, you can directly refer to your checkboxes.
如果您使用匿名方式,则可以直接引用您的复选框。
public class MyWindow extends JFrame()
{
private List<JCheckBox> checkboxes = new LinkedList<JCheckBox>();
public MyWindow()
{
for (int i = 0; i < numOrders; ++i)
checkboxes.add(new JCheckBox(String.valueOf(i));
}
// Not sure where you're action listener is, but here's the callback
public void actionPerformed(ActionEvent event)
{
for (JCheckBox checkbox : checkboxes)
System.out.println(checkbox.isSelected());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.