Java Swing程序设计-18章
1.Swing概论
Swing是用于创建图形用户界面(GUI)的一组API(应用程序编程接口)。Swing提供了丰富的组件,用于构建用户友好的界面,包括按钮、文本框、标签、列表、表格等。以下是Swing的一些关键概念和特点:
- 轻量级组件: Swing组件是轻量级的,这意味着它们不依赖于底层平台的窗口系统,而是由Java绘制。这使得Swing应用程序在不同平台上具有一致的外观和感觉。
- MVC架构: Swing采用了模型-视图-控制器(MVC)架构的设计模式。这意味着Swing组件的表示(视图)与用户交互(控制器)和数据(模型)分离,使得应用程序更易于维护和扩展。
- 事件处理: Swing使用事件模型来处理用户交互。当用户与Swing组件交互时,例如点击按钮或输入文本,相关的事件被触发,应用程序可以捕获并响应这些事件。
- 布局管理器: Swing提供了多种布局管理器,用于定义和控制组件在容器中的布局。这有助于确保在不同大小和分辨率的屏幕上,界面仍然能够良好地显示。
- 图形绘制: 通过
Graphics
类,Swing允许开发者进行自定义的图形绘制。这使得创建自定义组件和图形效果变得可行。 - 多线程: 由于Swing是基于Java的多线程模型的,因此它允许在单独的线程中处理用户界面操作,以保持界面的响应性。
一个简单的Swing应用程序通常包括创建顶层容器(如JFrame
),向容器中添加Swing组件,设置布局管理器,并处理与用户的交互事件。Swing的灵活性和丰富的功能使其成为Java图形界面开发的首选工具之一。
1.-27代码及运行结果
1.-27代码及运行结果尾巴
1-27代码汇总
1.
package eighteen;
import java.awt.*;
import javax.swing.*;
public class JfreamTest {
public static void main(String args[]){
JFrame jf = new JFrame();
jf.setTitle("创建一个Jframe窗体");
Container container = jf.getContentPane();
JLabel jl = new JLabel("这是一个JFrame窗体");
jl.setHorizontalAlignment(SwingConstants.CENTER);
container.add(jl);
jf.setSize(300,150);
jf.setLocation(320,240);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
2.
package eighteen;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MyJDialog extends JDialog{
public MyJDialog(MyFrame frame){
super(frame,"第一个JDialog窗体",true);
Container container = getContentPane();
container.add(new JLabel("这是一个对话框"));
setBounds(120,120,100,100);
}
}
public class MyFrame extends JFrame{
public MyFrame(){
Container container = getContentPane();
container.setLayout(null);
JButton bl = new JButton("弹出对话框");
bl.setBounds(10,10,100,21);
bl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MyJDialog dialog = new MyJDialog(MyFrame.this);
dialog.setVisible(true);
}
});
container.add(bl);
setSize(200,200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
new MyFrame();
}
}
3.
package eighteen;
import javax.swing.*;
public class Demo1 {
public static void main(String[] args){
Object o[] = {new JButton("是的"),new JButton("再想想")};
Icon icon = new ImageIcon("src/20220909223037.png");
JOptionPane.showOptionDialog(null,
"你备好了吗",
"注意了",
JOptionPane.DEFAULT_OPTION,
JOptionPane.DEFAULT_OPTION,
icon,o,null);
}
}
4.
package eighteen;
import javax.swing.*;
public class Demo2 {
public static void main(String[] args) {
int answer =JOptionPane.showConfirmDialog
(null,
"确定离开吗?",
"标题",
JOptionPane.YES_NO_CANCEL_OPTION);
}
}
5.
package eighteen;
import javax.swing.*;
public class Demo3 {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog
(null,"请输入您的名字");
}
}
6.
package eighteen;
import javax.swing.*;
public class Demo4 {
public static void main(String[] args) {
JOptionPane.showConfirmDialog(null, "您与服务器断开了连接", "发生错误", JOptionPane.YES_NO_OPTION);
}
}
7.
package eighteen;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class AbsolutePosition extends JFrame {
public AbsolutePosition() {
setTitle("本窗体使用绝对布局");
setLayout(null);
setBounds(0,0,300,150);
Container c=getContentPane();
JButton b1 =new JButton("按钮1");
JButton b2 =new JButton("按钮2");
b1.setBounds(10, 30, 80, 30);
b2.setBounds(60,70, 100, 20);
c.add(b1);
c.add(b2);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new AbsolutePosition();
}
}
8.
package eighteen;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class FlowLayoutPosition extends JFrame {
public FlowLayoutPosition() {
setTitle("本窗体使用流布局管理器");
Container c =getContentPane();
setLayout(new FlowLayout(FlowLayout.RIGHT,10,10));
for(int i=0;i<10;i++) {
c.add(new JButton("button"+i));
}
setSize(3300,200);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setFocusable(true);
}
public static void main(String[] args) {
new FlowLayoutPosition();
}
}
9.
package eighteen;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class BorderLayoutPosition extends JFrame {
public BorderLayoutPosition() {
setTitle("这个窗体使用边界布局管理器");
Container c=getContentPane();
setLayout(new BorderLayout());
JButton centerBtn =new JButton("中");
JButton northBtn =new JButton("北");
JButton southBtn =new JButton("南");
JButton westBtn =new JButton("西");
JButton eastBtn =new JButton("东");
c.add(centerBtn,BorderLayout.CENTER);
c.add(northBtn,BorderLayout.NORTH);
c.add(southBtn,BorderLayout.SOUTH);
c.add(westBtn,BorderLayout.WEST);
c.add(eastBtn,BorderLayout.EAST);
setSize(350,200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new BorderLayoutPosition();
}
}
10.
package eighteen;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class GridLayoutPosition extends JFrame {
public GridLayoutPosition() {
Container c=getContentPane();
setLayout(new GridLayout(7,3,5,5));
for(int i=0;i<20;i++) {
c.add(new JButton("button"+i));
}
setSize(300,300);
setTitle("这是一个使用网格布局管理器的窗体");
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new GridLayoutPosition();
}
}
11.
package eighteen;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class JPanelTest extends JFrame {
public JPanelTest() {
Container c =getContentPane();
//将整个容器设置为2行2列的网格布局,组件水平间隔10像素,垂直间隔10像素
c.setLayout(new GridLayout(2,2,10,10));
//初始化一个面板,此面板使用1行4列的网格布局,组件水平间隔10像素,垂直间隔10像素
JPanel p1 =new JPanel(new GridLayout(1,4,10,10));
//初始化一个面板,此面板使用边界布局
JPanel p2 =new JPanel(new BorderLayout());
//初始化一个面板,此面板使用1行2列的网格布局,组件水平间隔10像素,垂直间隔10像素
JPanel p3 =new JPanel(new GridLayout(1,2,10,10));
//初始化一个面板,此面板使用2行1列的网格布局,组件水平间隔10像素,垂直间隔10像素
JPanel p4 =new JPanel(new GridLayout(2,1,10,10));
//给每个面板都添加边框和标题,使用BorderFactory 工厂类生成带标题的边框对象
p1.setBorder(BorderFactory.createTitledBorder("面板1"));
p2.setBorder(BorderFactory.createTitledBorder("面板2"));
p3.setBorder(BorderFactory.createTitledBorder("面板3"));
p4.setBorder(BorderFactory.createTitledBorder("面板4"));
//向面板1中添加按钮
p1.add(new JButton("b1"));
p1.add(new JButton("b1"));
p1.add(new JButton("b1"));
p1.add(new JButton("b1"));
//向面板2中添加按钮
p2.add(new JButton("b2"),BorderLayout.WEST);
p2.add(new JButton("b2"),BorderLayout.EAST);
p2.add(new JButton("b2"),BorderLayout.NORTH);
p2.add(new JButton("b2"),BorderLayout.SOUTH);
p2.add(new JButton("b2"),BorderLayout.CENTER);
//向面板3中添加按钮
p3.add(new JButton("b3"));
p3.add(new JButton("b3"));
//向面板4中添加按钮
p4.add(new JButton("b4"));
p4.add(new JButton("b4"));
//向容器中添加面板
c.add(p1);
c.add(p2);
c.add(p3);
c.add(p4);
setTitle("在这个窗体中使用了面板");
setSize(500,300);//窗体宽高
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);//关闭动作
}
public static void main(String[] args) {
JPanelTest test=new JPanelTest();
test.setVisible(true);
}
}
12.
package eighteen;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class JScrollPaneTest extends JFrame{
public JScrollPaneTest() {
Container c = getContentPane();
JTextArea ta = new JTextArea(20, 50);
JScrollPane sp = new JScrollPane(ta);
c.add(sp);
setTitle("带滚动条的文字编译器");
setSize(400, 200);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
JScrollPaneTest test = new JScrollPaneTest();
test.setVisible(true);
}
}
13.
package eighteen;
import javax.swing.*;
import java.awt.*;
public class JlabelTest extends JFrame {
public JlabelTest(){
Container container = getContentPane();
JLabel jl = new JLabel("JFrame窗体");
container.add(jl);
setSize(200,100);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
new JlabelTest();
}
}
14.
package eighteen;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class MyImageIcon extends JFrame {
public MyImageIcon(){
Container container = getContentPane();
JLabel jl = new JLabel("这是一个JFrame窗体");
URL url = MyImageIcon.class.getResource("/20220909223037.png");
Icon icon = new ImageIcon(url);
jl.setIcon(icon);
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setOpaque(true);
container.add(jl);
setSize(2200,1200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new MyImageIcon();
}
}
15.
package eighteen;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JButtonTest extends JFrame {
public JButtonTest(){
Icon icon = new ImageIcon("/src/20220909223037.png");
setLayout(new GridLayout(3,2,5,5));
Container c =getContentPane();
JButton btn[] = new JButton[6];
for(int i =0;i< btn.length;i++){
btn[i] = new JButton();
c.add(btn[i]);
}
btn[0].setText("不可用");
btn[0].setEnabled(false);
btn[1].setText("有背景色");
btn[1].setBackground(Color.YELLOW);
btn[2].setText("無邊框");
btn[2].setBorderPainted(false);
btn[3].setText("有邊框");
btn[3].setBorder(BorderFactory.createLineBorder(Color.RED));
btn[4].setIcon(icon);
btn[4].setToolTipText("圖片按鈕");
btn[5].setText("可點擊");
btn[5].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(JButtonTest.this, "點擊按鈕");
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("創建不用樣式按鈕");
setBounds(100,100,400,200);
}
public static void main(String[] args){
new JButtonTest();
}
}
16.
package eighteen;
import javax.swing.*;
public class RadioButtonTest extends JFrame {
public RadioButtonTest(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("單選按鈕的使用");
setBounds(100,100,240,120);
getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("請選擇性別:");
lblNewLabel.setBounds(5,5,120,15);
getContentPane().add(lblNewLabel);
JRadioButton rbtnNormal = new JRadioButton("男");
rbtnNormal.setSelected(true);
rbtnNormal.setBounds(40,30,75,22);
getContentPane().add(rbtnNormal);
JRadioButton rbtnPwd = new JRadioButton("女");
rbtnPwd.setBounds(120,30,75,22);
getContentPane().add(rbtnPwd);
ButtonGroup group = new ButtonGroup();
group.add(rbtnNormal);
group.add(rbtnPwd);
}
public static void main(String[] args){
RadioButtonTest frame = new RadioButtonTest();
frame.setVisible(true);
}
}
17.
package eighteen;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CheckBoxTest extends JFrame {
public CheckBoxTest(){
setBounds(100,100,170,110);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
JCheckBox c1 = new JCheckBox("1");
JCheckBox c2 = new JCheckBox("2");
JCheckBox c3 = new JCheckBox("3");
c.add(c1);
c.add(c2);
c.add(c3);
JButton btn = new JButton("打印");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(c1.getText()+"按钮选中状态:"+c1.isSelected());
System.out.println(c2.getText()+"按钮选中状态:"+c2.isSelected());
System.out.println(c3.getText()+"按钮选中状态:"+c3.isSelected());
}
});
c.add(btn);
setVisible(true);
}
public static void main(String[] args){
new CheckBoxTest();
}
}
18.
package eighteen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JComboBoxTest extends JFrame{
public JComboBoxTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("下拉列表框的使用");
setBounds(100,100,317,147);
getContentPane().setLayout(null);
JLabel lblNewLabel =new JLabel("请使用证件:");
lblNewLabel.setBounds(28,14,80,15);
getContentPane().add(lblNewLabel);
JComboBox<String>comboBox = new JComboBox<String>();
comboBox.addItem("抑郁证");
comboBox.addItem("学生证");
comboBox.addItem("神经证");
comboBox.addItem("魔怔");
comboBox.setEditable(true);
getContentPane().add(comboBox);
JLabel lblResult = new JLabel("");
lblResult.setBounds(0,57,146,15);
getContentPane().add(lblResult);
JButton btnNewButton =new JButton("确定");
btnNewButton.setBounds(200,10,67,23);
getContentPane().add(btnNewButton);
btnNewButton.addActionListener((ActionListener) new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
lblResult.setText("您的选择是:"+comboBox.getSelectedItem());
}
});
}
public static void main(String[] args) {
JComboBoxTest frame = new JComboBoxTest();
frame.setVisible(true);
}
}
19.
package eighteen;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JListTest extends JFrame {
public JListTest(){
Container cp = getContentPane();
cp.setLayout(null);
String[] contents = {"列表1","列表2","列表3","列表4","列表5"};
JList<String> jl =new JList<>(contents);
JScrollPane js = new JScrollPane(jl);
js.setBounds(10,10,100,189);
cp.add(js);
JTextArea area = new JTextArea();
JScrollPane scrollPane = new JScrollPane(area);
scrollPane.setBounds(118,10,73,80);
cp.add(scrollPane);
JButton btnNewButton = new JButton("确认");
btnNewButton.setBounds(120,96,71,23);
cp.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
java.util.List<String> values = jl.getSelectedValuesList();
area.setText("");
for(String value:values){
area.append(value+"\n");
}
}
});
setTitle("在这个窗体中使用了列表框");
setSize(217,167);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String args[]){
new JListTest();
}
}
20.
package eighteen;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextFieldTest extends JFrame {
public JTextFieldTest() {
Container c = getContentPane();
c.setLayout(new FlowLayout());
JTextField jt = new JTextField("请点击清除按钮");
jt.setColumns(20);
jt.setFont(new Font("宋体",Font.PLAIN,20));
JButton jb = new JButton("清除");
jt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jt.setText("触发事件");
}
});
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(jt.getText());
jt.setText("");
jt.requestFocus();
}
});
c.add(jt);
c.add(jb);
setBounds(100,100,250,110);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JTextFieldTest();
}
}
21.
package eighteen;
import javax.swing.*;
import java.awt.*;
public class JTextAreaTest extends JFrame {
public JTextAreaTest(){
setSize(200,100);
setTitle("定义自动换行的文本域");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container cp = getContentPane();
JTextArea jt = new JTextArea("文本域",10,10);
jt.setLineWrap(true);
cp.add(jt);
setVisible(true);
}
public static void main(String[] args){
new JTextAreaTest();
}
}
22.
package eighteen;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JTableDemo extends JFrame{
public static void main(String[] args) {
JTableDemo frame =new JTableDemo();
frame.setVisible(true);
}
public JTableDemo() {
setTitle("创建可以滚动的表格");
setBounds(100,100,240,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnNames = {"A","B"};
//定义表格数据组
String[][] tableValues = {{"A1","B1",},{"A2","B2"},{"A3","B3"},
{"A4","B4"},{"A5","B5"}};
JTable table =new JTable(tableValues,columnNames);
JScrollPane scrollPane =new JScrollPane(table);
getContentPane().add(scrollPane,BorderLayout.CENTER);
}
}
23.
package eighteen;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class SortingTable extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SortingTable frame = new SortingTable();
frame.setVisible(true);
}
public SortingTable() {
setTitle("表格模型与表格");
setBounds(100,100,240,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane,BorderLayout.CENTER);
String [] columnNames = {"A","B"};
String[][] tableValues = {{"A1","B1"},{"A2","B2"},{"A3","B3"}};
DefaultTableModel tableModel = new DefaultTableModel(tableValues,columnNames);
JTable table = new JTable(tableModel);
table.setRowSorter(new TableRowSorter<>(tableModel));
scrollPane.setViewportView(table);
}
}
24.
package eighteen;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
public class AddAndDeleteDemo extends JFrame{
private DefaultTableModel tableModel;
private JTable table;
private JTextField aTextField;
private JTextField bTextField;
public static void main(String[] args) {
AddAndDeleteDemo frame = new AddAndDeleteDemo();
frame.setVisible(true);
}
public AddAndDeleteDemo() {
setTitle("维护表格模型");
setBounds(100,100,520,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane,BorderLayout.CENTER);
String[] columnNames = {"A","B"};
String[][] tableValues = {{"A1","B1"},{"A2","B2"},{"A3","B3"}};
tableModel = new DefaultTableModel(tableValues,columnNames);
table = new JTable(tableModel);
table.setRowSorter(new TableRowSorter<>(tableModel));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int selectedRow = table.getSelectedRow();
Object oa = tableModel.getValueAt(selectedRow, 0);
Object ob = tableModel.getValueAt(selectedRow, 1);
aTextField.setText(oa.toString());
bTextField.setText(ob.toString());
}
});
scrollPane.setViewportView(table);
JPanel panel = new JPanel();
getContentPane().add(panel,BorderLayout.SOUTH);
panel.add(new JLabel("A:"));
aTextField = new JTextField("A4",10);
panel.add(aTextField);
panel.add(new JLabel("B:"));
bTextField = new JTextField("B4",10);
panel.add(bTextField);
JButton addButton = new JButton("添加");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] rowValues = {aTextField.getText(),
bTextField.getText()};
tableModel.addRow(rowValues);
int rowCount = table.getRowCount() + 1;
aTextField.setText("A" + rowCount);
bTextField.setText("B" + rowCount);
}
});
panel.add(addButton);
JButton upButton = new JButton("修改");
upButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if(selectedRow != -1) {
tableModel.setValueAt(aTextField, selectedRow, 0);
tableModel.setValueAt(bTextField, selectedRow, 0);
}
}
});
panel.add(upButton);
JButton delButton = new JButton("删除");
delButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if(selectedRow != -1) {
tableModel.removeRow(selectedRow);
}
}
});
panel.add(delButton);
}
}
25.
package eighteen;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleEvent extends JFrame{
private JButton jb = new JButton("我是按鈕");
public SimpleEvent(){
setLayout(null);
setSize(200,100);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container cp = getContentPane();
cp.add(jb);
jb.setBounds(10,10,150,30);
jb.addActionListener(new jbAction());
setVisible(true);
}
class jbAction implements ActionListener{
public void actionPerformed(ActionEvent arg0){
jb.setText("我被點擊了");
}
}
public static void main(String[] args){
new SimpleEvent();
}
}
26.
package eighteen;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JTextField;
/**
* 虚拟键盘(键盘的按下与释放)
*/
public class KeyBoard extends JFrame { // 创建"键盘"类继承JFrame
// 声明窗体中的成员组件
private JPanel contentPane;
private JTextField textField;
private JButton btnQ;
private JButton btnW;
private JButton btnE;
private JButton btnR;
private JButton btnT;
private JButton btnY;
private JButton btnU;
private JButton btnI;
private JButton btnO;
private JButton btnP;
private JButton btnA;
private JButton btnS;
private JButton btnD;
private JButton btnF;
private JButton btnG;
private JButton btnH;
private JButton btnJ;
private JButton btnK;
private JButton btnL;
private JButton btnZ;
private JButton btnX;
private JButton btnC;
private JButton btnV;
private JButton btnB;
private JButton btnN;
private JButton btnM;
Color green = Color.GREEN;// 定义Color对象,用来表示按下键的颜色
Color white = Color.WHITE;// 定义Color对象,用来表示释放键的颜色
ArrayList<JButton> btns = new ArrayList<JButton>();// 定义一个集合,用来存储所有的按键ID
// 自定义一个方法,用来将容器中的所有JButton组件添加到集合中
private void addButtons() {
for (Component cmp : contentPane.getComponents()) {// 遍历面板中的所有组件
if (cmp instanceof JButton) {// 判断组件的类型是否为JButton类型
btns.add((JButton) cmp);// 将JButton组件添加到集合中
}
}
}
/**
* 主方法
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { // 使得Runnable中的的run()方法在the system EventQueue的指派线程中被调用
public void run() {
try {
KeyBoard frame = new KeyBoard(); // 创建KeyBoard对象
frame.setVisible(true); // 使frame可视
frame.addButtons();// 初始化存储所有按键的集合
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 创建JFrame窗体
*/
public KeyBoard() { // KeyBoard的构造方法
setTitle("\u865A\u62DF\u952E\u76D8\uFF08\u6A21\u62DF\u952E\u76D8\u7684\u6309\u4E0B\u4E0E\u91CA\u653E\uFF09"); // 设置窗体题目
setResizable(false); // 不可改变窗体宽高
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗体关闭的方式
setBounds(100, 100, 560, 280); // 设置窗体的位置和宽高
/**
* 创建JPanel面板contentPane置于JFrame窗体中,并设置面板的背景色、边距和布局
*/
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
/**
* 创建按钮button置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
*/
btnQ = new JButton("Q");
btnQ.setBackground(white);
btnQ.setVerticalAlignment(SwingConstants.TOP);
btnQ.setHorizontalAlignment(SwingConstants.LEADING);
btnQ.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnQ.setBounds(0, 60, 47, 45);
contentPane.add(btnQ);
/**
* 创建按钮button_2置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
*/
btnW = new JButton("W");
btnW.setBackground(white);
btnW.setVerticalAlignment(SwingConstants.TOP);
btnW.setHorizontalAlignment(SwingConstants.LEADING);
btnW.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnW.setBounds(55, 60, 49, 45);
contentPane.add(btnW);
/**
* 创建按钮button_3置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
*/
btnE = new JButton("E");
btnE.setBackground(white);
btnE.setVerticalAlignment(SwingConstants.TOP);
btnE.setHorizontalAlignment(SwingConstants.LEADING);
btnE.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnE.setBounds(110, 60, 45, 45);
contentPane.add(btnE);
/**
* 创建按钮button_4置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
*/
btnR = new JButton("R");
btnR.setBackground(white);
btnR.setVerticalAlignment(SwingConstants.TOP);
btnR.setHorizontalAlignment(SwingConstants.LEADING);
btnR.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnR.setBounds(165, 60, 45, 45);
contentPane.add(btnR);
/**
* 创建按钮button_5置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
*/
btnF = new JButton("F");
btnF.setBackground(white);
btnF.setVerticalAlignment(SwingConstants.TOP);
btnF.setHorizontalAlignment(SwingConstants.LEADING);
btnF.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnF.setBounds(195, 125, 45, 45);
contentPane.add(btnF);
/**
* 创建按钮button_6置于面板contentPane中,设置按钮的背景色、位置、宽高以及按钮中的字体位置、内容、样式
*/
btnD = new JButton("D");
btnD.setBackground(white);
btnD.setVerticalAlignment(SwingConstants.TOP);
btnD.setHorizontalAlignment(SwingConstants.LEADING);
btnD.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnD.setBounds(137, 125, 45, 45);
contentPane.add(btnD);
btnT = new JButton("T");
btnT.setVerticalAlignment(SwingConstants.TOP);
btnT.setHorizontalAlignment(SwingConstants.LEADING);
btnT.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnT.setBackground(white);
btnT.setBounds(220, 60, 45, 45);
contentPane.add(btnT);
btnY = new JButton("Y");
btnY.setVerticalAlignment(SwingConstants.TOP);
btnY.setHorizontalAlignment(SwingConstants.LEADING);
btnY.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnY.setBackground(white);
btnY.setBounds(275, 60, 45, 45);
contentPane.add(btnY);
btnU = new JButton("U");
btnU.setVerticalAlignment(SwingConstants.TOP);
btnU.setHorizontalAlignment(SwingConstants.LEADING);
btnU.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnU.setBackground(white);
btnU.setBounds(330, 60, 45, 45);
contentPane.add(btnU);
btnI = new JButton("I");
btnI.setVerticalAlignment(SwingConstants.TOP);
btnI.setHorizontalAlignment(SwingConstants.LEADING);
btnI.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnI.setBackground(white);
btnI.setBounds(385, 60, 45, 45);
contentPane.add(btnI);
btnO = new JButton("O");
btnO.setVerticalAlignment(SwingConstants.TOP);
btnO.setHorizontalAlignment(SwingConstants.LEADING);
btnO.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnO.setBackground(white);
btnO.setBounds(440, 60, 46, 45);
contentPane.add(btnO);
btnP = new JButton("P");
btnP.setVerticalAlignment(SwingConstants.TOP);
btnP.setHorizontalAlignment(SwingConstants.LEADING);
btnP.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnP.setBackground(white);
btnP.setBounds(495, 60, 45, 45);
contentPane.add(btnP);
btnA = new JButton("A");
btnA.setVerticalAlignment(SwingConstants.TOP);
btnA.setHorizontalAlignment(SwingConstants.LEADING);
btnA.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnA.setBackground(white);
btnA.setBounds(23, 125, 45, 45);
contentPane.add(btnA);
btnS = new JButton("S");
btnS.setVerticalAlignment(SwingConstants.TOP);
btnS.setHorizontalAlignment(SwingConstants.LEADING);
btnS.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnS.setBackground(white);
btnS.setBounds(82, 125, 45, 45);
contentPane.add(btnS);
btnG = new JButton("G");
btnG.setVerticalAlignment(SwingConstants.TOP);
btnG.setHorizontalAlignment(SwingConstants.LEADING);
btnG.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnG.setBackground(white);
btnG.setBounds(251, 125, 45, 45);
contentPane.add(btnG);
btnH = new JButton("H");
btnH.setVerticalAlignment(SwingConstants.TOP);
btnH.setHorizontalAlignment(SwingConstants.LEADING);
btnH.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnH.setBackground(white);
btnH.setBounds(306, 125, 45, 45);
contentPane.add(btnH);
btnJ = new JButton("J");
btnJ.setVerticalAlignment(SwingConstants.TOP);
btnJ.setHorizontalAlignment(SwingConstants.LEADING);
btnJ.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnJ.setBackground(white);
btnJ.setBounds(361, 125, 45, 45);
contentPane.add(btnJ);
btnK = new JButton("K");
btnK.setVerticalAlignment(SwingConstants.TOP);
btnK.setHorizontalAlignment(SwingConstants.LEADING);
btnK.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnK.setBackground(white);
btnK.setBounds(416, 125, 47, 45);
contentPane.add(btnK);
btnL = new JButton("L");
btnL.setVerticalAlignment(SwingConstants.TOP);
btnL.setHorizontalAlignment(SwingConstants.LEADING);
btnL.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnL.setBackground(white);
btnL.setBounds(471, 125, 45, 45);
contentPane.add(btnL);
btnZ = new JButton("Z");
btnZ.setVerticalAlignment(SwingConstants.TOP);
btnZ.setHorizontalAlignment(SwingConstants.LEADING);
btnZ.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnZ.setBackground(white);
btnZ.setBounds(39, 190, 45, 45);
contentPane.add(btnZ);
btnX = new JButton("X");
btnX.setVerticalAlignment(SwingConstants.TOP);
btnX.setHorizontalAlignment(SwingConstants.LEADING);
btnX.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnX.setBackground(white);
btnX.setBounds(107, 190, 45, 45);
contentPane.add(btnX);
btnC = new JButton("C");
btnC.setVerticalAlignment(SwingConstants.TOP);
btnC.setHorizontalAlignment(SwingConstants.LEADING);
btnC.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnC.setBackground(white);
btnC.setBounds(178, 190, 45, 45);
contentPane.add(btnC);
btnV = new JButton("V");
btnV.setVerticalAlignment(SwingConstants.TOP);
btnV.setHorizontalAlignment(SwingConstants.LEADING);
btnV.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnV.setBackground(white);
btnV.setBounds(250, 190, 45, 45);
contentPane.add(btnV);
btnB = new JButton("B");
btnB.setVerticalAlignment(SwingConstants.TOP);
btnB.setHorizontalAlignment(SwingConstants.LEADING);
btnB.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnB.setBackground(white);
btnB.setBounds(315, 190, 45, 45);
contentPane.add(btnB);
btnN = new JButton("N");
btnN.setVerticalAlignment(SwingConstants.TOP);
btnN.setHorizontalAlignment(SwingConstants.LEADING);
btnN.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnN.setBackground(white);
btnN.setBounds(382, 190, 47, 45);
contentPane.add(btnN);
btnM = new JButton("M");
btnM.setVerticalAlignment(SwingConstants.TOP);
btnM.setHorizontalAlignment(SwingConstants.LEADING);
btnM.setFont(new Font("Times New Roman", Font.PLAIN, 14));
btnM.setBackground(white);
btnM.setBounds(449, 190, 48, 45);
contentPane.add(btnM);
/**
* 创建面板panel置于面板contentPane中,设置面板panel的位置、宽高、TitledBorder、背景色以及布局方式(边界布局)
*/
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "文本显示区", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBackground(Color.WHITE);
panel.setBounds(0, 0, 540, 45);
contentPane.add(panel);
panel.setLayout(new BorderLayout(0, 0));
/**
* 创建文本框textField置于面板panel的中间
*/
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() { // 文本框添加键盘事件的监听
char word;
@Override
public void keyPressed(KeyEvent e) { // 按键被按下时被触发
word = e.getKeyChar();// 获取按下键表示的字符
for (int i = 0; i < btns.size(); i++) {// 遍历存储按键ID的ArrayList集合
// 判断按键是否与遍历到的按键的文本相同
if (String.valueOf(word).equalsIgnoreCase(btns.get(i).getText())) {
btns.get(i).setBackground(green);// 将指定按键颜色设置为绿色
}
}
}
@Override
public void keyReleased(KeyEvent e) { // 按键被释放时被触发
word = e.getKeyChar();// 获取释放键表示的字符
for (int i = 0; i < btns.size(); i++) {// 遍历存储按键ID的ArrayList集合
// 判断按键是否与遍历到的按键的文本相同
if (String.valueOf(word).equalsIgnoreCase(btns.get(i).getText())) {
btns.get(i).setBackground(white);// 将指定按键颜色设置为白色
}
}
}
});
panel.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
}
}
27.
package eighteen;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MouseEventDemo extends JFrame { // 继承窗体类JFrame
public static void main(String args[]) {
MouseEventDemo frame = new MouseEventDemo();
frame.setVisible(true); // 设置窗体可见,默认为不可见
}
/**
* 判断按下的鼠标键,并输出相应提示
*
* @param e 鼠标事件
*/
private void mouseOper(MouseEvent e) {
int i=e.getButton();
if(i==MouseEvent.BUTTON1)
System.out.println("按下的是鼠标左键");
else if (i==MouseEvent.BUTTON2)
System.out.println("按下的是鼠标中键");
else if (i==MouseEvent.BUTTON3)
System.out.println("按下的是鼠标右键");
}
public MouseEventDemo() {
super(); // 继承父类的构造方法
setTitle("鼠标事件示例"); // 设置窗体的标题
setBounds(100, 100, 500, 375); // 设置窗体的显示位置及大小
// 设置窗体关闭按钮的动作为退出
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel label = new JLabel();
label.addMouseListener(new MouseListener() {
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("光标移入组件");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("鼠标按键被按下,");
mouseOper(e);
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("鼠标按键被释放,");
mouseOper(e);
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("单机了鼠标按键,");
mouseOper(e);
int clickCount = e.getClickCount();
System.out.println("单机次数为"+clickCount+"下");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("光标移除组件");
}
});
getContentPane().add(label, BorderLayout.CENTER);
}
}
EventDemo();
frame.setVisible(true); // 设置窗体可见,默认为不可见
}
/**
* 判断按下的鼠标键,并输出相应提示
*
* @param e 鼠标事件
*/
private void mouseOper(MouseEvent e) {
int i=e.getButton();
if(i==MouseEvent.BUTTON1)
System.out.println("按下的是鼠标左键");
else if (i==MouseEvent.BUTTON2)
System.out.println("按下的是鼠标中键");
else if (i==MouseEvent.BUTTON3)
System.out.println("按下的是鼠标右键");
}
public MouseEventDemo() {
super(); // 继承父类的构造方法
setTitle("鼠标事件示例"); // 设置窗体的标题
setBounds(100, 100, 500, 375); // 设置窗体的显示位置及大小
// 设置窗体关闭按钮的动作为退出
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel label = new JLabel();
label.addMouseListener(new MouseListener() {
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("光标移入组件");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("鼠标按键被按下,");
mouseOper(e);
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("鼠标按键被释放,");
mouseOper(e);
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("单机了鼠标按键,");
mouseOper(e);
int clickCount = e.getClickCount();
System.out.println("单机次数为"+clickCount+"下");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("光标移除组件");
}
});
getContentPane().add(label, BorderLayout.CENTER);
}