一、图片按钮
package com.massimo.component;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonTest extends JFrame {
public JButtonTest(){
Container container = this.getContentPane();
//将一个图片变为图标
URL url = JButtonTest.class.getResource("qq.png");
Icon icon = new ImageIcon(url);
//把这个图标放在按钮上
JButton button = new JButton();
button.setIcon(icon);
button.setToolTipText("图片按钮");
container.add(button);
this.setVisible(true);
this.setSize(500 , 300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonTest();
}
}
效果:
二、单选按钮
package com.massimo.component;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class SingleBox extends JFrame {
public SingleBox(){
Container container = this.getContentPane();
//单选框
JRadioButton jRadioButton1 = new JRadioButton("JRadioButton1");
JRadioButton jRadioButton2 = new JRadioButton("JRadioButton2");
JRadioButton jRadioButton3 = new JRadioButton("JRadioButton3");
//由于单选框只能选择一个,所以我们要进行分组,一个组中只能选择一个
ButtonGroup group = new ButtonGroup();
group.add(jRadioButton1);
group.add(jRadioButton2);
group.add(jRadioButton3);
container.add(jRadioButton1 , BorderLayout.CENTER);
container.add(jRadioButton2 , BorderLayout.NORTH);
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 SingleBox();
}
}
效果:
四、复选框
package com.massimo.component;
import javax.swing.*;
import java.awt.*;
public class CheckBoxTest extends JFrame {
public CheckBoxTest(){
Container container = this.getContentPane();
//多选框
JCheckBox box1 = new JCheckBox("checkBox1");
JCheckBox box2 = new JCheckBox("checkBox2");
container.add(box1 , BorderLayout.NORTH);
container.add(box2 , BorderLayout.SOUTH);
this.setVisible(true);
this.setSize(500 , 300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new CheckBoxTest();
}
}
效果: