Java学习-GUI编程-图片按钮、单选框、多选框
图片按钮
public class JButtonDemo extends JFrame {
public JButtonDemo(){
Container container = this.getContentPane();
URL resource = JButtonDemo.class.getResource("tx.jpg");
Icon icon = new ImageIcon(resource);
JButton jButton = new JButton();
jButton.setIcon(icon);
jButton.setToolTipText("这是一个图片按钮");
container.add(jButton);
this.setVisible(true);
this.setBounds(100,100,500,600);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
运行程序,鼠标悬浮在图片上会有提示:
单选按钮
public class JButtonDemo extends JFrame {
public JButtonDemo(){
Container container = this.getContentPane();
URL resource = JButtonDemo.class.getResource("tx.jpg");
Icon icon = new ImageIcon(resource);
JRadioButton radioButton1 = new JRadioButton("1");
JRadioButton radioButton2 = new JRadioButton("2");
JRadioButton radioButton3 = new JRadioButton("3");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
container.add(radioButton1,BorderLayout.NORTH);
container.add(radioButton2,BorderLayout.CENTER);
container.add(radioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(100,100,100,100);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
复选按钮
public class JButtonDemo extends JFrame {
public JButtonDemo(){
Container container = this.getContentPane();
URL resource = JButtonDemo.class.getResource("tx.jpg");
Icon icon = new ImageIcon(resource);
JCheckBox checkBox1 = new JCheckBox("1");
JCheckBox checkBox2 = new JCheckBox("2");
JCheckBox checkBox3 = new JCheckBox("3");
container.add(checkBox1,BorderLayout.WEST);
container.add(checkBox2,BorderLayout.CENTER);
container.add(checkBox3,BorderLayout.EAST);
this.setVisible(true);
this.setBounds(100,100,100,100);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo();
}
}
运行程序,可以多选: