📄 buttonexam.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class buttonExam extends JFrame{
Container container;
JLabel label1 = new JLabel("带图像和文本的JLabel组件",new ImageIcon("image//face.jpg"),JLabel.LEFT);
JTextField text1 = new JTextField("请注意文本的颜色和字体");
JCheckBox boldbox = new JCheckBox("粗体");
JCheckBox italicbox = new JCheckBox("斜体");
JRadioButton blueRadio = new JRadioButton("蓝色");
JRadioButton redRadio = new JRadioButton("红色",true);
public buttonExam() { // 构造函数
super("Swing按钮演示");
container = this.getContentPane();
container.setLayout(new GridLayout(3,1));
container.add(label1);
container.add(text1);
text1.setForeground(Color.RED);
JPanel jpanel1 = new JPanel(); // 定义一个面板
jpanel1.setLayout(new GridLayout(2,2));
ButtonGroup radioGroup = new ButtonGroup(); // 单选按钮组
radioGroup.add(blueRadio);
radioGroup.add(redRadio);
jpanel1.add(boldbox);
jpanel1.add(blueRadio);
jpanel1.add(italicbox);
jpanel1.add(redRadio);
container.add(jpanel1);
// 为两个JCheckBox对象注册监听者
BoxEventHandler Boxhandler = new BoxEventHandler();
boldbox.addItemListener(Boxhandler);
italicbox.addItemListener(Boxhandler);
// 为两个JRadioButton对象注册监听者
RadioEventHandler Radiohandler = new RadioEventHandler();
blueRadio.addItemListener(Radiohandler);
redRadio.addItemListener(Radiohandler);
setSize(400, 200);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// 定义一个处理JCheckBox事件的内部类
private class BoxEventHandler
implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
public void itemStateChanged(ItemEvent e) {
if ( e.getSource() == boldbox )
if ( e.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
if ( e.getSource() == italicbox )
if ( e.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
text1.setFont(new Font( "Serif", valBold + valItalic, 14 ) );
}
}
// 定义一个处理JRadioButton事件的内部类
private class RadioEventHandler
implements ItemListener {
private Color c;
// 实现itemStateChanged()方法
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == blueRadio)
text1.setForeground(Color.BLUE);
if (e.getSource() == redRadio)
text1.setForeground(Color.RED);
}
}
public static void main(String args[]) {
buttonExam obj = new buttonExam();
obj.setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -