案例代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Example8_15 extends JFrame{
private JRadioButton italic;
private JRadioButton bold;
private JLabel label;
private ButtonGroup group;
private JPanel panel;
public Example8_15(){
//创建一个JLabel标签,居中对齐
label = new JLabel("来改变字体形态",JLabel.CENTER);
label.setFont(new Font("宋体",Font.PLAIN,20));//设置标签文本的字体
this. add(label);//在 CENTER域添加标签
panel = new JPanel();
group = new ButtonGroup() ;
//添加单选按钮
addJRadioButton("字体倾斜");
addJRadioButton("字体加粗");
this.add(panel, BorderLayout.SOUTH);
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void addJRadioButton(final String text){
JRadioButton radioButton = new JRadioButton(text);//添加单选按钮
group.add(radioButton);
panel.add(radioButton);//添加监听事件
radioButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int mode = 0;
if("字体倾斜".equals(text)){
mode += Font.ITALIC;
label.setFont(new Font("宋体", mode, 20)) ;
}else if("字体加粗".equals(text)) {
mode += Font.BOLD;
label.setFont(new Font("宋体", mode, 20));
}else{
label.setFont(new Font("宋体", Font.PLAIN,20));
}
}
});
}
public static void main(String[] args){
new Example8_15();
}
}
案例运行图: