在我的java应用程序中有60个按钮组,每组有两个单选按钮是或否按钮。如何知道哪个组,按钮被选中
import javax.swing.*;
class buttonGroup{
JToggleButton yes[],no[];
JPanel yesNo[];
ButtonGroup group[];
public void init()
{
yesNo=new JPanel[60];
yes=new JToggleButton[60];
no=new JToggleButton[60];
group=new ButtonGroup[60];
for(int i=0;i<60;i++)
{
yesNo[i]=new JPanel();
yes[i]=new JToggleButton("yes");
no[i]=new JToggleButton("no");
group[i]=new ButtonGroup();
yesNo[i].add(yes[i]);
yesNo[i].add(no[i]);
group[i].add(yes[i]);
group[i].add(no[i]);
}
}
}
答案 0 :(得分:0)
在 actionPerformed 方法中,使用 getSource()来了解触发操作的位置
public void actionPerformed (ActionEvent ae){
if(ae.getSource.equals(//put the object here ){
// implementation here
}
}
答案 1 :(得分:0)
尝试这样的事情:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
class buttonGroup implements ActionListener
{
JToggleButton yes[], no[];
JPanel yesNo[];
ButtonGroup group[];
public void init()
{
yesNo = new JPanel[60];
yes = new JToggleButton[60];
no = new JToggleButton[60];
group = new ButtonGroup[60];
for(int i = 0; i < 60; i++)
{
yesNo[i] = new JPanel();
yes[i] = new JToggleButton("yes");
yes[i].setName("yes" + " " + i);
yes[i].addActionListener(this);
no[i] = new JToggleButton("no");
no[i].setName("no" + " " + i);
no[i].addActionListener(this);
group[i] = new ButtonGroup();
yesNo[i].add(yes[i]);
yesNo[i].add(no[i]);
group[i].add(yes[i]);
group[i].add(no[i]);
}
}
public void actionPerformed(ActionEvent sE)
{
if(sE.getSource() instanceof JToggleButton)
{
JToggleButton oSourceButton = (JToggleButton) sE.getSource();
System.out.println("Button " + oSourceButton.getName() + " was pressed...");
// do whatever...
}
}
}