Java 如何从动态JCheckBox中获取值?
我创建了动态Java 如何从动态JCheckBox中获取值?,java,swing,jcheckbox,Java,Swing,Jcheckbox,我创建了动态JCheckBox,我不知道在检查时如何获取它们的值 当我单击复选框时,我想获取值并将它们放入SQL查询 类似:query=从表中选择checkbox1、checkbox2 这是我的动态复选框代码: roll[K] = new JCheckBox(); roll[K].setText(metaData.getColumnLabel(columnIndex)); roll[K].setBounds(X,Y,150,30); Y = Y+3
JCheckBox
,我不知道在检查时如何获取它们的值
当我单击复选框时,我想获取值并将它们放入SQL查询
类似:query=从表中选择checkbox1、checkbox2
这是我的动态复选框代码:
roll[K] = new JCheckBox();
roll[K].setText(metaData.getColumnLabel(columnIndex));
roll[K].setBounds(X,Y,150,30);
Y = Y+30;
Rectangle r = jPanel3.getBounds();
int h=r.height;
if (Y>=h-50){
Y=0;
X=X+200;
}
jPanel3.add(roll[K]);
您可以像这样设置复选框项侦听器
roll[K].setActionCommand(Integer.toString(k));
roll[K].addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
//this is not necessary and depends upon you, how do u want
// use this
int id = Integer.parseInt(Integer.getSource().getActionCommand())
//can apply switch case on ID to take appropriate action based on ID
if (e.getStateChange() == 1)
System.out.println("Checked");
else
System.out.println("un-Checked");
}
});
因为你是在循环中添加它们,所以我认为
roll[K]
它意味着循环?如果可以避免循环,则更好,否则可以将命令id与复选框相关联,并在listeneri中比较命令id。此代码中出现错误:int id=Integer.parseInt(Integere.getSource().getActionCommand());它现在应该可以工作了,如果不能,那么肯定会有一些打字错误的问题,因为我在这里直接编写了这段代码,您可以很容易地识别它