我设定了三个JRadioButton和一个ButtonGroup,我想在改变单选按钮时在控制台输出按钮名字,我应该这么写
时间: 2024-05-12 09:16:57 浏览: 48
您可以在每个 JRadioButton 对象上添加状态更改侦听器,然后从侦听器中获取按钮的名称并输出到控制台。示例代码如下:
```java
JRadioButton radioButton1 = new JRadioButton("Button 1");
JRadioButton radioButton2 = new JRadioButton("Button 2");
JRadioButton radioButton3 = new JRadioButton("Button 3");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
radioButton1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (radioButton1.isSelected()) {
System.out.println("Selected: " + radioButton1.getText());
}
}
});
radioButton2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (radioButton2.isSelected()) {
System.out.println("Selected: " + radioButton2.getText());
}
}
});
radioButton3.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (radioButton3.isSelected()) {
System.out.println("Selected: " + radioButton3.getText());
}
}
});
```
当单选按钮状态更改时,会调用相应的 ChangeListener,并检查选中的按钮是否是当前按钮,如果是,则将按钮的名称输出到控制台。
阅读全文