/** 演示Label */ import javax.swing.*; public class LabelDemo { public static void main(String[] args) { JFrame jFrame = new JFrame("This is a JLabel demo"); jFrame.setSize(300,200); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); jFrame.setContentPane(contentPane); // 构造时, 设置标签内容 JLabel label1 = new JLabel("-------------Label1---------------"); // 构造后, 设置标签内容 JLabel label2 = new JLabel(); label2.setText("-------------Label2---------------"); contentPane.add(label1); contentPane.add(label2); jFrame.setVisible(true); } }
import javax.swing.*; /** 普通按钮 */ public class JButtonDemo { public static void main(String[] args) { JFrame jFrame = new JFrame("This is a JButton demo"); jFrame.setSize(300, 200); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); jFrame.setContentPane(contentPane); // 构造时, 设置 按钮名 JButton okButton = new JButton("ok"); // 构造后, 设置 按钮名 JButton cancelButton = new JButton(); cancelButton.setText("cancel"); contentPane.add(okButton); contentPane.add(cancelButton); jFrame.setVisible(true); return; } }
JRadioButtonDemo1.java
import javax.swing.*; /** 无 ButtonGrop, 所有单选按钮可以同时选中 */ public class JRadioButtonDemo1 { public static void main(String[] args) { JFrame jFrame = new JFrame("this is a JRadioButton demo"); jFrame.setSize(300, 200); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); jFrame.setContentPane(contentPane); JRadioButton footballRadio = new JRadioButton("足球", true); JRadioButton basketballRadio = new JRadioButton("篮球"); contentPane.add(footballRadio); contentPane.add(basketballRadio); jFrame.setVisible(true); return; } }
import javax.swing.*; /** 有 ButtonGrope */ class JRadioButtonDemo2 { public static void main(String[] args) { JFrame jFrame = new JFrame("this is a JRadioButton demo"); jFrame.setSize(300, 200); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); jFrame.setContentPane(contentPane); // 创建 JRadioButton 实例 JRadioButton footballRadio = new JRadioButton("足球"); JRadioButton basketballRadio = new JRadioButton("篮球"); // 将 radio 添加进 逻辑分组 ButtonGroup likesGroup = new ButtonGroup(); likesGroup.add(footballRadio); likesGroup.add(basketballRadio); // contentPane.add(likesGroup); // error, ButtonGroup 为逻辑组件 contentPane.add(footballRadio); contentPane.add(basketballRadio); jFrame.setVisible(true); return; } }
import javax.swing.*; /** 复选框 */ public class JCheckboxDemo { public static void main(String[] args) { JFrame jFrame = new JFrame("JCheckbox demo"); jFrame.setSize(300, 200); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); jFrame.setContentPane(contentPane); JCheckBox footballCheckBox = new JCheckBox("足球"); JCheckBox basketballCheckBox = new JCheckBox("篮球"); contentPane.add(footballCheckBox); contentPane.add(basketballCheckBox); jFrame.setVisible(true); return; } }