GUI Swing 3.5 按钮


3.5 按钮

  • 图片按钮
public class TestButton extends JFrame {
    public TestButton(){
        Container contentPane = getContentPane();
        //获取资源
        URL resource = TestButton.class.getResource("4.jpg");
        //做成图标
        ImageIcon icon = new ImageIcon(resource);
        JButton jButton = new JButton();
        //按钮设置图标
        jButton.setIcon(icon);
        //设置按钮提示
        jButton.setToolTipText("这是一个图片按钮");
        contentPane.add(jButton);
        setVisible(true);
        setBounds(200,200,600,600);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestButton();
    }
}
  • 单选框按钮
public class TestButton02 extends JFrame{
    public TestButton02(){
        Container contentPane = getContentPane();
       /* //获取资源
        URL resource = TestButton.class.getResource("4.jpg");
        //做成图标
        ImageIcon icon = new ImageIcon(resource);*/
        //单选框
        JRadioButton jRadioButton01 = new JRadioButton("jRadioButton01");
        JRadioButton jRadioButton02 = new JRadioButton("jRadioButton02");
        JRadioButton jRadioButton03 = new JRadioButton("jRadioButton03");

        //因为单选框,只能选其中一个,所有要分组,分到一个组中
        //且按钮组只是一个组,不能添加到容器中
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton01);
        buttonGroup.add(jRadioButton02);
        buttonGroup.add(jRadioButton03);

        contentPane.add(jRadioButton01,BorderLayout.NORTH);
        contentPane.add(jRadioButton02,BorderLayout.CENTER);
        contentPane.add(jRadioButton03,BorderLayout.SOUTH);
        setVisible(true);
        setBounds(200,200,600,600);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestButton02();
    }
}
  • 多选按钮
public class TestButton03 extends JFrame {
    public TestButton03(){
        Container contentPane = getContentPane();

        //多选框
        JCheckBox jCheckBox01 = new JCheckBox("checkbox01");
        JCheckBox jCheckBox02 = new JCheckBox("checkbox02");
        JCheckBox jCheckBox03 = new JCheckBox("checkbox03");

        contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
        contentPane.add(jCheckBox01);
        contentPane.add(jCheckBox02);
        contentPane.add(jCheckBox03);

        setVisible(true);
        setBounds(200,200,600,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestButton03();
    }
}

相关