单选按钮组控制字体大小

package swing;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class RadioButtonTest {
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   @Override
   public void run() {
    RadioButtonFrame frame = new RadioButtonFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
   }
  });
 }
}

class RadioButtonFrame extends JFrame {
 public RadioButtonFrame() {
  this.setTitle("RadioButton Test");
  this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  
  label = new JLabel("The quick brown fox jumps over the lazy dog.");
  label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
  this.add(label, BorderLayout.CENTER);
  
  buttonPanel = new JPanel();
  group = new ButtonGroup();
  
  addRadioButton("Small", 8);
  addRadioButton("Medium", 12);
  addRadioButton("Large", 18);
  addRadioButton("Extra large", 36);
  
  this.add(buttonPanel, BorderLayout.SOUTH);
 }
 
 private void addRadioButton(String name, final int size) {
  boolean selected = size == DEFAULT_SIZE;
  JRadioButton button = new JRadioButton(name, selected);
  group.add(button);
  buttonPanel.add(button);
  
  ActionListener listener = new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent event) {
    label.setFont(new Font("Serif", Font.PLAIN, size));
   }
  };
  
  button.addActionListener(listener);
 }

 public static final int DEFAULT_WIDTH = 400;
 public static final int DEFAULT_HEIGHT = 200;
 
 private JPanel buttonPanel;
 private ButtonGroup group;
 private JLabel label;
 
 private static final int DEFAULT_SIZE = 12;
}

阅读更多
个人分类: swing
上一篇左上角的小图标
下一篇平铺一张图像
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭