swing 学习笔记四(单选按钮JRadioButton )

/**
 * 单选按钮
 * @time 下午10:48:14
 * @author  retacn yue
 * @Email  [email protected]
 */
public class Test_RadioButtonDemo extends JPanel {
JLabel pictute;
static String aString = "A";
static String bString = "B";
static String cString = "C";
static String dString = "D";
static String eString = "E";


private static final long serialVersionUID = 1L;


/**
* 构造器
*/
private Test_RadioButtonDemo() {


JRadioButton aButton = new JRadioButton(aString);
aButton.setMnemonic('a');
aButton.setActionCommand(aString);
aButton.setBackground(Color.pink);


JRadioButton bButton = new JRadioButton(bString);
aButton.setMnemonic('b');
aButton.setActionCommand(aString);
aButton.setBackground(Color.pink);


JRadioButton cButton = new JRadioButton(cString);
aButton.setMnemonic('c');
aButton.setActionCommand(aString);
aButton.setBackground(Color.pink);


JRadioButton dButton = new JRadioButton(dString);
aButton.setMnemonic('d');
aButton.setActionCommand(aString);
aButton.setBackground(Color.pink);


JRadioButton eButton = new JRadioButton(eString);
aButton.setMnemonic('e');
aButton.setActionCommand(aString);
aButton.setBackground(Color.pink);


// 将单选按钮放到同一组中
ButtonGroup group = new ButtonGroup();
group.add(aButton);
group.add(bButton);
group.add(cButton);
group.add(dButton);
group.add(eButton);


// 给按钮添加监听
RadioListener listener = new RadioListener();
aButton.addActionListener(listener);
bButton.addActionListener(listener);
cButton.addActionListener(listener);
dButton.addActionListener(listener);
eButton.addActionListener(listener);


// 将按钮添加到面板中
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(0, 1));
radioPanel.add(aButton);
radioPanel.add(bButton);
radioPanel.add(cButton);
radioPanel.add(dButton);
radioPanel.add(eButton);


// 添加图片控件
pictute = new JLabel(new ImageIcon("images/+" + aString + ".gif"));
pictute.setPreferredSize(new Dimension(200, 200));
setBackground(Color.pink);
setLayout(new BorderLayout());
add(radioPanel, BorderLayout.WEST);
add(pictute);
}


/**

* @time 4:49:05 PM
* @author retacn yue
* @Email [email protected]
*/
class RadioListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
// 更换图片
pictute.setIcon(new ImageIcon("images/" + e.getActionCommand() + ".gif"));
}


}


public static void main(String[] args) {
JFrame frame = new JFrame("Test_RadioButtonDemo");
Test_RadioButtonDemo test_RadioButtonDemo = new Test_RadioButtonDemo();
frame.setSize(300, 300);
frame.setBackground(Color.pink);
frame.setContentPane(test_RadioButtonDemo);
frame.setVisible(true);


frame.addWindowListener(new WindowAdapter() {


@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}


});


}
}

你可能感兴趣的:(c,swing,String,Class,email)