图片按钮
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonTest extends JFrame {
public JButtonTest() {
Container container = this.getContentPane();
//将一个图片变为图标
URL resource = JButtonTest.class.getResource("lena.jpg");
Icon icon = new ImageIcon(resource);
//把图标放在按钮上
JButton jButton = new JButton();
jButton.setIcon(icon);
jButton.setToolTipText("图片按钮");
//把按钮放在容器里
container.add(jButton);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonTest();
}
}
运行结果为:
按钮上添加了一张图像,当鼠标移到按钮上时,显示“图片按钮”四个字
单选框
import javax.swing.*;
import java.awt.*;
public class JButtonTest2 extends JFrame {
public JButtonTest2() {
Container container = this.getContentPane();
//单选框
JRadioButton jRadioButton1 = new JRadioButton("JRadioButton1");
JRadioButton jRadioButton2 = new JRadioButton("JRadioButton2");
JRadioButton jRadioButton3 = new JRadioButton("JRadioButton3");
//分组,同一个组的button只能选择一个
ButtonGroup group = new ButtonGroup();
group.add(jRadioButton1);
group.add(jRadioButton2);
group.add(jRadioButton3);
container.add(jRadioButton1,BorderLayout.NORTH);
container.add(jRadioButton2,BorderLayout.CENTER);
container.add(jRadioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonTest2();
}
}
运行结果为:
三个按钮只能选择其中一个
多选框
import javax.swing.*;
import java.awt.*;
public class JButtonTest3 extends JFrame {
public JButtonTest3() {
Container container = this.getContentPane();
//多选框
JCheckBox jCheckBox1 = new JCheckBox("jCheckBox1");
JCheckBox jCheckBox2 = new JCheckBox("jCheckBox2");
container.add(jCheckBox1,BorderLayout.SOUTH);
container.add(jCheckBox2,BorderLayout.NORTH);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonTest3();
}
}
运行结果为:
两个按钮可以同时选择