请看下面的代码
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ComboIssue extends JFrame
{
private JRadioButton rOne, rTwo;
private ButtonGroup group;
private JComboBox combo;
private JLabel label;
public ComboIssue()
{
rOne = new JRadioButton("One");
rOne.addActionListener(new ROneAction());
rTwo = new JRadioButton("Two");
rTwo.addActionListener(new RTwoAction());
group = new ButtonGroup();
group.add(rOne);
group.add(rTwo);
combo = new JComboBox();
combo.addItem("No Values");
combo.addItemListener(new ComboAction());
label = new JLabel("labellLabel");
this.setLayout(new FlowLayout());
this.add(rOne);
this.add(rTwo);
this.add(combo);
this.add(label);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ROneAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
combo.removeAllItems();
combo.addItem("One");
}
}
private class RTwoAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
combo.removeAllItems();
combo.addItem("Two");
}
}
private class ComboAction implements ItemListener
{
public void itemStateChanged(ItemEvent ie)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
label.setText("Selected");
}
}
}
public static void main(String[]args)
{
new ComboIssue();
}
}
这里我期待的是,
- 选择一个单选按钮。它将替换组合框中的值。
- 从组合框中选择一个值。现在 JLabel 文本将设置为“已选择”
但是,这不是正在发生的事情。相反,只要您选择单选按钮,JLabel 文本就会更改!!!为什么是这样?请帮忙!