图片按钮:ImageIcon、JButton
1 package com.gui.lesson5; 2 3 import javax.swing.*; 4 import java.awt.*; 5 import java.net.URL; 6 7 public class JButtonDemo1 extends JFrame { 8 9 public JButtonDemo1() { 10 Container container = this.getContentPane(); 11 //将一个图片变为图标 12 URL url = JButtonDemo1.class.getResource("tx.jpg"); 13 Icon icon = new ImageIcon(url); 14 15 //把这个图标放在按钮上 16 JButton button = new JButton(); 17 button.setIcon(icon); 18 button.setToolTipText("图片按钮"); 19 20 //add 21 container.add(button); 22 23 this.setVisible(true); 24 this.setSize(500, 300); 25 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 26 27 28 } 29 30 public static void main(String[] args) { 31 new JButtonDemo1(); 32 } 33 }
鼠标放上去,有个图片按钮四个字,同样的需要把下面的tx.jpg图片放进去
单选框:JRadioButton
1 package com.gui.lesson5; 2 3 import javax.swing.*; 4 import java.awt.*; 5 6 public class JButtonDemo2 extends JFrame { 7 public JButtonDemo2() { 8 Container container = getContentPane(); 9 10 //单选框 11 JRadioButton radioButton1 = new JRadioButton("JRadioButton01"); 12 JRadioButton radioButton2 = new JRadioButton("JRadioButton02"); 13 JRadioButton radioButton3 = new JRadioButton("JRadioButton03"); 14 15 //由于单选框只能选择一个,分组 16 ButtonGroup group = new ButtonGroup(); 17 group.add(radioButton1); 18 group.add(radioButton2); 19 group.add(radioButton3); 20 21 container.add(radioButton1, BorderLayout.CENTER); 22 container.add(radioButton2, BorderLayout.NORTH); 23 container.add(radioButton3, BorderLayout.SOUTH); 24 25 this.setVisible(true); 26 this.setSize(300, 500); 27 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 28 } 29 30 public static void main(String[] args) { 31 new JButtonDemo2(); 32 } 33 }
把按钮添加到组里面,就只能选择一个了
多选框:JCheckBox
1 package com.gui.lesson5; 2 3 import javax.swing.*; 4 import java.awt.*; 5 6 public class JButtonDemo3 extends JFrame { 7 public JButtonDemo3() { 8 Container container = this.getContentPane(); 9 10 //多选框 11 JCheckBox checkBox1 = new JCheckBox("checkBox1"); 12 JCheckBox checkBox2 = new JCheckBox("checkBox2"); 13 14 container.add(checkBox1, BorderLayout.NORTH); 15 container.add(checkBox2, BorderLayout.SOUTH); 16 17 this.setVisible(true); 18 this.setSize(500, 300); 19 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 20 } 21 22 public static void main(String[] args) { 23 new JButtonDemo3(); 24 } 25 }
可以选择多个,复选框嘛