GUI编程
03 Swing
3.5 JButton
- 图片置于按钮之上的JButton:
package com.duo.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo01 extends JFrame {
public JButtonDemo01() {
Container contentPane = getContentPane();
URL url = JButtonDemo01.class.getResource("通用头像.jpg");
assert url != null;
ImageIcon imageIcon = new ImageIcon(url);
JButton jButton = new JButton();
jButton.setIcon(imageIcon);
jButton.setToolTipText("Fire");
contentPane.add(jButton);
setTitle("JButton测试窗口");
setVisible(true);
setSize(650, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo01();
}
}
运行结果:
如上所示,当鼠标悬浮于按钮之上时,会有tip显示。
- 单选按钮 & 多选按钮
- 单选按钮JRadioButton:
package com.duo.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo02 extends JFrame {
public JButtonDemo02() {
Container contentPane = getContentPane();
//单选按钮框,只能选择一个。通常要对按钮进行分组
JRadioButton jRadioButton1 = new JRadioButton("按钮1");
JRadioButton jRadioButton2 = new JRadioButton("按钮2");
JRadioButton jRadioButton3 = new JRadioButton("按钮3");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jRadioButton1);
buttonGroup.add(jRadioButton2);
buttonGroup.add(jRadioButton3);
contentPane.add(jRadioButton1, BorderLayout.NORTH);
contentPane.add(jRadioButton2, BorderLayout.CENTER);
contentPane.add(jRadioButton3, BorderLayout.SOUTH);
setTitle("单选按钮测试窗口");
setVisible(true);
setSize(650, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
运行结果:
- 多选按钮JCheckBox:
package com.duo.lesson05;
import javax.swing.*;
import java.awt.*;
public class JButtonDemo03 extends JFrame {
public JButtonDemo03() {
Container contentPane = getContentPane();
//多选按钮框
JCheckBox jCheckBox1 = new JCheckBox("A");
JCheckBox jCheckBox2 = new JCheckBox("B");
contentPane.add(jCheckBox1, BorderLayout.NORTH);
contentPane.add(jCheckBox2, BorderLayout.SOUTH);
setTitle("多选按钮测试窗口");
setVisible(true);
setSize(650, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
运行结果: