62,635
社区成员




public void itemStateChanged(ItemEvent e) {
if (e.getSource() == jRadioButton1) {
System.out.println("jRadioButton1");
} else {
System.out.println("jRadioButton2");
}
}
我改成了由isSelected()来判断是不是被选中, e.getItem() 代表的是触发的控件对不对,两个按钮中间是联动的,如果一个按钮是选中状态,你点了另一个按钮,两个控件都会itemStateChanged,所以你不应该根据e.getItem 来判断,你应该是判断有没有被选中。
e.getItem() 代表的是触发的控件对不对,两个按钮中间是联动的,如果一个按钮是选中状态,你点了另一个按钮,两个控件都会itemStateChanged,所以你不应该根据e.getItem 来判断,你应该是判断有没有被选中。
执行了2次,你是不是两个按钮都监听了?e.getSource() 在每个按钮里面都代表自己一个是jRadioButton1 一个是jRadioButton2 因为是jRadioButton 你又设置在一个ButtonGroup里面所以会联动啊。
import java.awt.GridLayout;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import java.awt.event.WindowListener ;
import java.awt.event.WindowAdapter ;
import java.awt.event.WindowEvent ;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.Container ;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup ;
import java.awt.event.ItemListener ;
import java.awt.event.ItemEvent ;
import javax.swing.ImageIcon ;
import java.awt.Color ;
class MyRadioButtonHandle implements ItemListener{
private JFrame jFrame= new JFrame("Hello World");
private Container cont = jFrame.getContentPane();
private JRadioButton jrb1 = new JRadioButton("男");
private JRadioButton jrb2 = new JRadioButton("女");
private JPanel jPanel= new JPanel();
private ButtonGroup buttonGroup = new ButtonGroup() ;
public MyRadioButtonHandle(){
jPanel.setBorder(BorderFactory.createTitledBorder("请选择性别")) ;
jPanel.setLayout(new GridLayout(1,3));
jPanel.add(jrb1);
jPanel.add(jrb2);
buttonGroup.add(jrb1);
buttonGroup.add(jrb2);
jrb1.addItemListener(this);//监听事件
jrb2.addItemListener(this);
cont.add(jPanel);
this.jFrame.setSize(400,300);
this.jFrame.pack();
this.jFrame.setLocation(300,300);
this.jFrame.setVisible(true);
this.jFrame.addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent e){
System.exit(1);
}
});
}
public void itemStateChanged(ItemEvent e) {
if(e.getItem() == jrb1){
System.out.println("1");//选择jrb1就打印1
jrb1.setForeground(Color.RED);
jrb2.setForeground(Color.black);
}else{
System.out.println("2");
jrb1.setForeground(Color.black);
jrb2.setForeground(Color.BLUE);
}
}
}
public class JRadioButtonDemo{
public static void main(String args[]){
new MyRadioButtonHandle();
}
}
应该是运行了2次
执行了2次,你是不是两个按钮都监听了?e.getSource() 在每个按钮里面都代表自己一个是jRadioButton1 一个是jRadioButton2 因为是jRadioButton 你又设置在一个ButtonGroup里面所以会联动啊。