这个小程序展示的是:是有三个单选按钮改变Label内容。这里有几个需要注意的地方:
1. 单选按钮要组成组,则需要ButtonGroup类来定义一组相关的单选按钮。
2. 每个单选按钮都要添加到按钮组中,每个按钮还要独自添加到面板中。
3. ButtonGroup对象不是一个组织对象并显示组建的容器;这只是定义共同起作用、组成一组相关选项的按钮组的方法。ButtonGroup对象可以保证当选中组内另一个按钮时,自动关闭当前选中的按钮。
实际效果如图:
QuoteOptions.java
import javax.swing.JFrame;
public class QuoteOptions {
public static void main(String[] args) {
JFrame frame = new JFrame("Quote Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new QuoteOptionsPanel());
frame.pack();
frame.setVisible(true);
}
}
QuoteOptionsPanel.java
import javax.swing.JRadioButton;
import .....
public class QuoteOptionsPanel extends JPanel{
private JLabel quote;
private JRadioButton comedy, philosophy, carpentry;
private String comedyQuote, philosophyQuote, carpentryQuote;
//在Panel中设置一个Label和三个RadioButton控制它的内容
public QuoteOptionsPanel() {
comedyQuote = "I love you what you are!";
philosophyQuote = "I think, therefore I am.";
carpentryQuote = "Never,never give up.";
quote = new JLabel(comedyQuote);
quote.setFont(new Font("Helvetica", Font.ROMAN_BASELINE, 24));
comedy = new JRadioButton("Comedy", true);
comedy.setBackground(Color.green);
philosophy = new JRadioButton("philosophy");
philosophy.setBackground(Color.green);
carpentry = new JRadioButton("carpentry");
carpentry.setBackground(Color.green);
ButtonGroup group = new ButtonGroup();
group.add(comedy);
group.add(philosophy);
group.add(carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener(listener);
philosophy.addActionListener(listener);
carpentry.addActionListener(listener);
add(quote);
add(comedy);
add(philosophy);
add(carpentry);
setBackground(Color.green);
setPreferredSize(new Dimension(300, 100));
}
//所有单选按钮的监听器
private class QuoteListener implements ActionListener {
//根据按下的单选按钮设置标签的内容
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == comedy)
quote.setText(comedyQuote);
else
if(source == philosophy)
quote.setText(philosophyQuote);
else
quote.setText(carpentryQuote);
}
}