Java基础案例教程 第八章 GUI ———8.5 Swing

  • Swing组件是由Java编写的,不依赖于本地平台,可以做到跨平台运行
  • 依赖于本地平台的AWT组件称为重量级组件,不依赖的Swing组件称为轻量级组件

  • 大部分的Swing组件都是JComponent类的直接或者间接子类,而JComponent是AWT中java.awt.Container的子类,
  • Swing中有三个组件继承了AWT的Windows类,而不是继承自JComponent类,他们分别是JWindow,JFrame,和JDialog。这三个组件是Swing中的顶级容器,他们都需要依赖本地平台,因此被称为重量级组件。

 

 

一、JFrame

在Swing组件中,最常见的一个就是JFrame,它和Frame一样是一个独立存在的顶级窗口

package cn.itcast.chapter08.example15;

import javax.swing.*;
import java.awt.*;

/**
 * JFrame
 */
public class Example15 extends JFrame {

    public Example15() {
        this.setTitle("JFrameTest");
        this.setSize(250, 300);
        // 定义一个按钮组件
        JButton bt = new JButton("按钮");
        // 设置流式布局管理器
        this.setLayout(new FlowLayout());
        // 添加按钮组件
        this.add(bt);
        // 设置单击关闭按钮时的默认操作
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
	

    //没有main主函数,代码无法运行
    public static void main(String[] args) {
        new Example15();
    }
}

 

 

二、JDialog

JDialog对话框分为两种,模态对话框和非模态对话框

模式对话框:用户需要等到处理完对话框后才能继续与其他窗口交互,

非模式对话框:允许用户在处理对话框的同时与其他窗口交互

package cn.itcast.chapter08.example16;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * JDialog对话框
 */
public class Example16 {
    public static void main(String[] args) {
        // 建立两个按钮
        JButton btn1 = new JButton("模态对话框");
        JButton btn2 = new JButton("非模态对话框");
        JFrame f = new JFrame("DialogDemo");
        f.setSize(300, 250);
        f.setLocation(300, 200);
        f.setLayout(new FlowLayout()); // 为内容面板设置布局管理器
        // 在Container对象上添加按钮
        f.add(btn1);
        f.add(btn2);
        // 设置单击关闭按钮默认关闭窗口
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

        // 定义一个JDialog对话框
        final JDialog dialog = new JDialog(f, "Dialog");  //不下面的按钮点击事件会用到,所以添加 final 
        final JLabel label = new JLabel();        //不下面的按钮点击事件会用到,所以添加 final     
        dialog.setSize(220, 150); // 设置对话框大小
        dialog.setLocation(350, 250); // 设置对话框位置
        dialog.setLayout(new FlowLayout()); // 设置布局管理器
        // 创建按钮对象
        final JButton btn3 = new JButton("确定");
        dialog.add(btn3); // 在对话框的内容面板添加按钮

        // 为"模态对话框"按钮添加单击事件
        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 设置对话框为模态
                dialog.setModal(true);
                // 如果JDialog窗口中没有添加了JLabel标签,就把JLabel标签加上
                if (dialog.getComponents().length == 1) {
                    dialog.add(label);
                }
                // 否则修改标签的内容
                label.setText("模式对话框,点击确定按钮关闭");
                // 显示对话框
                dialog.setVisible(true);
            }
        });

        // 为"非模态对话框"按钮添加单击事件
        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 设置对话框为非模态
                dialog.setModal(false);
                // 如果JDialog窗口中没有添加了JLabel标签,就把JLabel标签加上
                if (dialog.getComponents().length == 1) {
                    dialog.add(label);
                }
                // 否则修改标签的内容
                label.setText("非模式对话框,点击确定按钮关闭");
                // 显示对话框
                dialog.setVisible(true);
            }
        });

        // 为对话框中的按钮添加单击事件
        btn3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();  //释放窗口
            }
        });
    }
}

 

 

三、中间容器

package cn.itcast.chapter08.example17;

import javax.swing.*;
import java.awt.*;

/**
 * 向中间容器添加按钮
 */
public class Example17 extends JFrame {  //直接继承 JFrame 使代码简洁
    public Example17() {
        this.setTitle("PanelDemo");

        // 定义一个JPanel面板
        JPanel panel = new JPanel();
        // 在JPanel面板中添加四个按钮
        panel.add(new JButton("按钮1"));
        panel.add(new JButton("按钮2"));
        panel.add(new JButton("按钮3"));
        panel.add(new JButton("按钮4"));


        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane();
        // 设置水平滚动条策略--滚动条一直显示
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        // 设置垂直滚动条策略--滚动条需要时显示
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        // 设置JPanel面板在滚动面板中显示
        scrollPane.setViewportView(panel);


        // 将滚动面板添加到窗体的CENTER区域
        this.add(scrollPane, BorderLayout.CENTER);

        // 将一个按钮添加到窗体的SOUTH区域
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(400, 250);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new Example17();
    }
}

 

四、文本组件

 

            

 

后面会用到的组件, 在创建时 添加  final

final JTextArea chatContext = new JTextArea(20, 40); 
final JTextField inputText = new JTextField(10);


 String context = inputText.getText();
 if (context != null && !context.trim().equals("")) {
       chatContext.append("本人:" + context + "\n");
 } else {
       chatContext.append("聊天信息不能为空\n");
 }
 inputText.setText("");  // clear the input box

判断字符串是否为空

if (content != null && !content.trim().equals(""))   //trim 去掉空格

 

package cn.mytest18;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author wangyue
 * @version 1.0
 * @date 2019/7/6 12:05
 * @describe: practice JTextField and JTextArea component
 */
public class Test18 extends JFrame {
    //the constructor name is the same as the class name
    public Test18() {
        this.setLayout(new BorderLayout());  //setting window layout
        this.setTitle("聊天窗口");
        this.setSize(400, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        //upper part
        final JTextArea chatContext = new JTextArea(20, 40);
        JScrollPane scrollPane = new JScrollPane(chatContext); // ????? if we add JTextArea later,we  can't see the scroll
//        JScrollPane scrollPane=new JScrollPane();
        chatContext.setEditable(false);
        this.add(scrollPane, BorderLayout.CENTER);
//        scrollPane.add(chatContext);


        //following part
        Label label = new Label("聊天信息");
        final JTextField inputText = new JTextField(10);
        JButton sendButton = new JButton("发送");
        //create a panel to store following components
        JPanel followPanel = new JPanel();
        followPanel.add(label);
        followPanel.add(inputText);
        followPanel.add(sendButton);
        this.add(followPanel, BorderLayout.SOUTH);


        //add an event for the button
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String context = inputText.getText();
                if (context != null && !context.trim().equals("")) {
                    chatContext.append("本人:" + context + "\n");
                } else {
                    chatContext.append("聊天信息不能为空\n");
                }
                inputText.setText("");

            }
        });

        this.setVisible(true);  //first add components and finally diaplay window
    }

    
    public static void main(String[] args) {
        new Test18();

    }

}

                 

 

 

五、按钮组件

1、JChectBox

package cn.itcast.chapter08.example19;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * JCheckBox组件
 */
public class Example19 extends JFrame {
    private JCheckBox italic;
    private JCheckBox bold;
    private JLabel label;

    public Example19() {

        //upper part
        label = new JLabel("传智播客欢迎你!", JLabel.CENTER); // create JLabel  ,label is center
        label.setFont(new Font("宋体", Font.PLAIN, 20));// setting label's font
        this.add(label); // 在CENTER域添加标签


        //following part
        JPanel panel = new JPanel();  // 创建一个JPanel面板
        // 创建两个JCheckBox复选框
        italic = new JCheckBox("ITALIC");
        bold = new JCheckBox("BOLD");

        // 为复选框定义ActionListener监听器
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int mode = 0;
                if (bold.isSelected())
                    mode += Font.BOLD;
                if (italic.isSelected())
                    mode += Font.ITALIC;
                label.setFont(new Font("宋体", mode, 20));
            }
        };
        // 为两个复选框添加监听器
        italic.addActionListener(listener);
        bold.addActionListener(listener);
        // 在JPanel面板面板添加复选框
        panel.add(italic);
        panel.add(bold);

        // 在SOUTH域添加JPanel面板
        this.add(panel, BorderLayout.SOUTH);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(300, 300);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new Example19();
    }
}

                                         

 

 

 

2、JRadioButton

 

监听器是一种内部类

 //create radio buttton ActionListener
        //inner class
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Color color = null;
                if (button1.isSelected()) {
                    color = Color.gray;
                } else if (button2.isSelected()) {
                    color = Color.pink;
                } else if (button3.isSelected()) {
                    color = Color.YELLOW;
                }
                //change pallet's color
                pallet.setBackground(color);
            }
        };

后面用到了pallet  ,buttons  ,设置为final

//create a pallet
final JPanel pallet = new JPanel();
this.add(pallet, BorderLayout.CENTER);

//following part
final JRadioButton button1 = new JRadioButton("灰色");
final JRadioButton button2 = new JRadioButton("粉色");
final JRadioButton button3 = new JRadioButton("黄色");

 

几个单选按钮必须放在一个组里,才能识别是否单选,

但是按钮组不能放在panel 或者frame中,

 //create a button group     must have a group,they are radio
 ButtonGroup group = new ButtonGroup();
 group.add(button1);
 group.add(button2);
 group.add(button3);
package cn.myTest20;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author wangyue
 * @version 1.0
 * @date 2019/7/6 15:21
 * @describe: the use of JRadioButton
 */
public class MyTest20 extends JFrame {

    public MyTest20() {
        //create a pallet
        final JPanel pallet = new JPanel();
        this.add(pallet, BorderLayout.CENTER);

        //following part
        final JRadioButton button1 = new JRadioButton("灰色");
        final JRadioButton button2 = new JRadioButton("粉色");
        final JRadioButton button3 = new JRadioButton("黄色");
        //create a button group     must have a group,they are radio
        ButtonGroup group = new ButtonGroup();
        group.add(button1);
        group.add(button2);
        group.add(button3);

        //create a panel
        JPanel panel = new JPanel();
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        this.add(panel, BorderLayout.SOUTH);    //can't put the group in the window directly

        //create radio buttton ActionListener
        //inner class
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Color color = null;
                if (button1.isSelected()) {
                    color = Color.gray;
                } else if (button2.isSelected()) {
                    color = Color.pink;
                } else if (button3.isSelected()) {
                    color = Color.YELLOW;
                }
                //change pallet's color
                pallet.setBackground(color);
            }
        };

        button1.addActionListener(listener);
        button2.addActionListener(listener);
        button3.addActionListener(listener);


        this.setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

    }


    public static void main(String[] args) {
        new MyTest20();

    }
}

                                             

 

3、JComboBox

 

                    

package cn.itcast.chapter08.example21;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * JComboBox组件
 */
public class Example21 extends JFrame {
	private JComboBox comboBox; // 定义一个JComboBox组合框
	private JTextField field; // 定义一个JTextField文本框

	public Example21() {

		// 创建JPanel面板
		JPanel panel = new JPanel();
		comboBox = new JComboBox();
		// 为组合框添加选项
		comboBox.addItem("请选择城市");
		comboBox.addItem("北京");
		comboBox.addItem("天津");
		comboBox.addItem("南京");
		comboBox.addItem("上海");
		comboBox.addItem("重庆");
		// 为组合框添加事件监听器
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String item = (String) comboBox.getSelectedItem();
				if ("请选择城市".equals(item)) {
					field.setText("");
				} else {
					field.setText("您选择的城市是:" + item);
				}
			}
		});
		field = new JTextField(20);
		panel.add(comboBox); // 在面板中添加组合框
		panel.add(field); // 在面板中添加文本框

		// 在内容面板中添加JPanel面板
		this.add(panel, BorderLayout.NORTH);
		this.setSize(350, 100);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	public static void main(String[] args)
	{
		new Example21();
	}
}

 

六、菜单组件

1、下拉式菜单

创建下拉式菜单需要3个组件:JMenuBar(菜单栏) 、JMenu(菜单)、JMenuItem(菜单项)

                                   

package cn.itcast.chapter08.example22;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 菜单的创建和使用
 */
public class Example22 extends JFrame {

    public Example22() {
        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        this.setJMenuBar(menuBar); // 将菜单栏添加到JFrame窗口中

        // 创建菜单
        JMenu menu = new JMenu("操作");
        menuBar.add(menu); // 将菜单添加到菜单栏上

        // 创建两个菜单项
        JMenuItem item1 = new JMenuItem("弹出窗口");
        JMenuItem item2 = new JMenuItem("关闭");
        menu.add(item1); // 将菜单项添加到菜单中
        menu.addSeparator(); // 添加一个分隔符
        menu.add(item2);


        // 为菜单项添加事件监听器
        item1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 创建一个JDialog窗口
                JDialog dialog = new JDialog(Example22.this, true);
                dialog.setTitle("弹出窗口");
                dialog.setSize(200, 200);
                dialog.setLocation(50, 50);
                dialog.setVisible(true);
            }
        });

        item2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });


        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(300, 300);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new Example22();
    }
}

 

 

2、弹出式菜单 JPopupMenu

                                 

package cn.itcast.chapter08.example23;

import java.awt.event.*;
import javax.swing.*;

/* 
* 弹出式菜单(右键菜单) JPopupMenu
* */

public class Example23 extends JFrame {
	private JPopupMenu popupMenu;

	public Example23() {

		// 创建一个JPopupMenu菜单
		//弹出式菜单不需要 菜单栏
		popupMenu = new JPopupMenu();

		// 创建三个JMenuItem菜单项
		JMenuItem refreshItem = new JMenuItem("refresh");
		JMenuItem createItem = new JMenuItem("create");
		JMenuItem exitItem = new JMenuItem("exit");
		// 为exitItem菜单项添加事件监听器
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		// 往JPopupMenu菜单添加菜单项
		popupMenu.add(refreshItem);
		popupMenu.add(createItem);
		popupMenu.addSeparator();
		popupMenu.add(exitItem);

		// 为JFrame窗口添加clicked鼠标事件监听器
		this.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				// 如果单击的是鼠标的右键,显示JPopupMenu菜单
				if (e.getButton() == e.BUTTON3) {
					popupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});

		this.setSize(300, 300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	public static void main(String[] args) {
		new Example23();
	}
}

 

3、JTable

                               

package cn.itcast.chapter08.example24;
import javax.swing.*;
/**
 * JTable
 */
public class Example24 {

	//创建JFrame窗口
	JFrame jf = new JFrame("简单表格");
	
	//声明JTable类型的变量table
	JTable table;
	// 1.定义一维数组作为列标题
	Object[] columnTitle = { "姓名", "年龄", "性别" };
	// 2.定义二维数组作为表格行对象数据
	Object[][] tableDate = { 
			new Object[] { "李清照", 29, "女" },
			new Object[] { "苏格拉底", 56, "男" }, 
			new Object[] { "李白", 35, "男" },
			new Object[] { "弄玉", 18, "女" }, 
			new Object[] { "虎头", 2, "男" } 
	 };
    // 3.使用JTable对象创建表格
	public void init() {
		// 以二维数组和一维数组来创建一个JTable对象
		table = new JTable(tableDate, columnTitle);
		// 将JTable对象放在JScrollPane中,并将该JScrollPane放在窗口中显示出来
		jf.add(new JScrollPane(table));
		//设置自适应JFrame窗体大小
		jf.pack();
		//设置单击关闭按钮时默认为退出
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//设置窗体可见
		jf.setVisible(true);
	}
	public static void main(String[] args) {
		new Example24().init();
	}
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值