关闭

单选按钮组控制字体大小

标签: radiobuttonbuttonstringclass
701人阅读 评论(0) 收藏 举报
分类:

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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:104290次
    • 积分:1770
    • 等级:
    • 排名:千里之外
    • 原创:85篇
    • 转载:0篇
    • 译文:0篇
    • 评论:37条
    文章分类
    最新评论