题目来源:大工慕课 链接
作者:Caleb Sung
题目要求
实现一个能够改变显示单词的字体风格和大小的GUI。
参考代码
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class FontTest {
public static void main(String[] args) {
new FontFrame();
}
}
@SuppressWarnings("serial")
class FontFrame extends JFrame {
JCheckBox bold = new JCheckBox("Bold");
JCheckBox italic = new JCheckBox("Italic");
JRadioButton small = new JRadioButton("Small");
JRadioButton medium = new JRadioButton("Medium");
JRadioButton large = new JRadioButton("Large");
JRadioButton extra_large = new JRadioButton("Extra Large");
int fontSize;
JLabel display;
public FontFrame() {
setTitle("Change Font");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
display = new JLabel();
display.setText("The quick brown fox jump over the lazy dog.");
display.setFont(new Font("Serif", Font.PLAIN, 10));
add(display, BorderLayout.CENTER);
JPanel btnp = new JPanel();
btnp.add(bold);
btnp.add(italic);
btnp.add(small);
btnp.add(medium);
btnp.add(large);
btnp.add(extra_large);
ButtonGroup bg = new ButtonGroup();
bg.add(small);
bg.add(medium);
bg.add(large);
bg.add(extra_large);
small.setSelected(true);
add(btnp, BorderLayout.SOUTH);
bold.addActionListener(e -> {
changeFont();
});
italic.addActionListener(e -> {
changeFont();
});
small.addActionListener(e -> {
changeFont();
});
medium.addActionListener(e -> {
changeFont();
});
large.addActionListener(e -> {
changeFont();
});
extra_large.addActionListener(e -> {
changeFont();
});
pack();
}
void changeFont() {
int mode = Font.PLAIN;
if (bold.isSelected())
mode += Font.BOLD;
if (italic.isSelected())
mode += Font.ITALIC;
if(small.isSelected())
fontSize = 10;
else if (medium.isSelected())
fontSize = 20;
else if (large.isSelected())
fontSize = 30;
else if (extra_large.isSelected())
fontSize = 50;
display.setFont(new Font("Serif", mode, fontSize));
pack();
validate();
}
}
运行效果
界面下方的选项卡中有单选也有复选框。详细效果请大家自己在实现后体验一下~