Java-GUI-Swing入门笔记(从界面的创建到事件监听)

2022-07-15 08:09:53

GUI的概念

图形用户界面(Graphical User Interface,简称 GUI,又称图形用户接口)是指采用图形方式显示的计算机操作用户界面。

JAVA的GUI开发包

Java提供了三个主要包做GUI开发:
java.awt 包:主要提供字体/布局管理器
javax.swing 包[商业开发常用]:主要提供各种组件(窗口/按钮/文本框)
java.awt.event 包:事件处理,后台功能的实现。

Swing

swing组件可分为三大部分
(1)顶层容器JFrame,JDialog
(2)中间容器JPanel,JOptionPane,JScrollPane,JLayeredPane 等
(3)基本组件JLabel,JButton,JTextField,JPasswordField,JRadioButton 等。
在这里插入图片描述
参考大佬的博客

1如何创建一个窗口

package learn;import javax.swing.JFrame;

public class demo{
	public static voidmain(String[] args){
		JFrame f=newJFrame("小窗口");//新建一个顶级容器JFrame并给它一个标题:小窗口
		f.setBounds(2,3,400,600);//在屏幕中的位置为(2,3)为窗体的左上角,宽和高分别为400,600.
		f.setVisible(true);//设置为显示,这个语句一定要有}}

关于JFrame

继承自顶级窗口Frame.
JFrame的构成如下
在这里插入图片描述
可以发现JFrame由上方的菜单栏和下方的内容窗格组成.
我们加零件就在这个ContentPane上加.
更进一步的
在这里插入图片描述
好像有点深了,博主水平有限,就先到此为止了,以后有机会再进一步…

关于JFrame的一些博客:(该部分内容转载自此文)
JFrame的进一步理解

2往里面加入小零件吧

package learn;import javax.swing.JButton;import javax.swing.JFrame;

public class demo{
	public static voidmain(String[] args){
		JFrame f=newJFrame("小窗口");
		f.setBounds(0,0,1000,1000);
		f.setVisible(true);for(int i=0;i<10;i++){
			JButton btn=newJButton("按钮");
			btn.setSize(100,100);//设置宽和高
			btn.setLocation(100*i,100*i);//设置左上角的位置
			f.getContentPane().add(btn);//往JFrame里添加button}}}

运行后可以发现,我们原来的窗口里多了十个按钮.

3.更多的零件

为了更好的组合零件,我们需要JPanel.
JPanel 是 Java图形用户界面(GUI)工具包swing中的面板容器类,包含在javax.swing 包中,是一种轻量级容器,可以加入到JFrame窗体中。
JPanel默认的布局管理器是FlowLayout,其自身可以嵌套组合,在不同子容器中可包含其他组件(component),如JButton、JTextArea、JTextField 等,功能是对窗体上的这些控件进行组合。
演示效果
在这里插入图片描述

package learn;import java.awt.FlowLayout;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextField;

public class demo{
	public static voidmain(String[] args){
		JFrame f=newJFrame("小窗口");
		f.setBounds(0,0,400,400);
		JPanel jp=newJPanel();placeComponents(jp);
		f.getContentPane().add(jp);
		f.setVisible(true);}
	public static voidplaceComponents(JPanel panel){
		panel.setLayout(null);
		JLabel userLabel=newJLabel("User:");
  
  
        userLabel.setBounds(10,20,80,25);
        panel.add(userLabel);
        JTextField userText=newJTextField(20);
        userText.setBounds(100,20,165,25);
        panel.add(userText);// 输入密码的文本域
        JLabel passwordLabel=newJLabel("Password:");
        passwordLabel.setBounds(10,50,80,25);
        panel.add(passwordLabel);/* 
         *这个类似用于输入的文本域
         * 但是输入的信息会以点号代替,用于包含密码的安全性
         */
        JPasswordField passwordText=newJPasswordField(20);
        passwordText.setBounds(100,50,165,25);
        panel.add(passwordText);// 创建登录按钮
        JButton loginButton=newJButton("login");
        loginButton.setBounds(10,80,80,25);
        panel.add(loginButton);}}

主要有这么几个类:JButton,JLabel,JPanel,JTextField,JPasswordField.
可以发现其中比较特别的是JPanel这个类,其他的类都是加在这个类上的,这个类最终才加到JFrame上.

对JFrame添加组件有两种方式:

1)用getContentPane()方法获得JFrame的内容面板,再对其加入组件:frame.getContentPane().add(childComponent)
2)建立一个Jpanel或JDesktopPane之类的中间容器,把组件添加到容器中,用setContentPane()方法把该容器置为JFrame的内容面板:
 JPanel contentPane=new JPanel();
 ……//把其它组件添加到Jpanel中;
 frame.setContentPane(contentPane);
 //把contentPane对象设置成为frame的内容面板

关于setVisible()方法;

有时间的读者可以试试调换一下该语句的顺序,你会发现有些组件更新后别没有显示.
所以该语句一般要放到最后面.
替代语句:?博主暂时未知

从静止到变化:事件监听

上面我们创建的界面并不具有交互效果,我们希望一些按钮能够生效,该如何做呢?
我们需要事件监听器去实现这个功能

在事件处理的过程中,主要涉及三类对象。
Event(事件):用户对组件的一次操作称为一个事件,以类的形式出现。例如,键盘操作对应的事件类是 KeyEvent。
Event Source(事件源):事件发生的场所,通常就是各个组件,例如按钮 Button。
Event Handler(事件处理者):接收事件对象并对其进行处理的对象事件处理器,通常就是某个 Java 类中负责处理事件的成员方法。
在这里插入图片描述

由于同一个事件源上可能发生多种事件,因此,Java 采取了授权模型(Delegation Model),事件源可以把在其自身上所有可能发生的事件分别授权给不同的事件处理者来处理。例如,在 Panel 对象上既可能发生鼠标事件,也可能发生键盘事件,该 Panel 对象可以授权给事件处理者 a 来处理鼠标事件,同时授权给事件处理者 b 来处理键盘事件。

有时也将事件处理者称为监听器,主要原因在于监听器时刻监听事件源上所有发生的事件类型,一旦该事件类型与自己所负责处理的事件类型一致,就马上进行处理。授权模型把事件的处理委托给外部的处理实体进行处理,实现了将事件源和监听器分开的机制。

事件处理者(监听器)通常是一个类,该类如果能够处理某种类型的事件,就必须实现与该事件类型相对的接口。例如,一个 ButtonHandler 类之所以能够处理 ActionEvent 事件,原因在于它实现了与 ActionEvent 事件对应的接口 ActionListener。每个事件类都有一个与之相对应的接口。

搬运原产地

动作事件监听器

动作事件监听器是 Swing 中比较常用的事件监听器,很多组件的动作都会使用它监听,像按钮被里击、列表框中选择一项等。与动作事件监听器有关的信息如下。
事件名称:ActionEvent。
事件监听接口: ActionListener。
事件相关方法:addActionListener() 添加监听,removeActionListener() 删除监听。
涉及事件源:JButton、JList、JTextField 等。

演示效果
在这里插入图片描述

import java.awt.BorderLayout;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;
public class ActionListenerDemo extends JFrame{
 
    JLabel label;
    JButton button1;int clicks=0;
    publicActionListenerDemo(){setTitle("动作事件监听器示例");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100,100,400,200);
        JPanel contentPane=newJPanel();
        contentPane.setBorder(newEmptyBorder(5,5,5,5));
        contentPane.setLayout(newBorderLayout(0,0));setContentPane(contentPane);
        label=newJLabel(" ");
        label.setFont(newFont("楷体",Font.BOLD,16));//修改字体样式
        contentPane.add(label, BorderLayout.SOUTH);
        button1=newJButton("我是普通按钮");//创建JButton对象
        button1.setFont(newFont("黑体",Font.BOLD,16));//修改字体样式
        button1.addActionListener(newActionListener(){
            public voidactionPerformed(ActionEvent e){
                label.setText("按钮被单击了 "+(clicks++)+" 次");}});
        contentPane.add(button1);}//处理按钮单击事件的匿名内部类
    class button1ActionListener implements ActionListener{
        @Override
        public voidactionPerformed(ActionEvent e){
            label.setText("按钮被单击了 "+(clicks++)+" 次");}}
    public static voidmain(String[] args){
        ActionListenerDemo frame=newActionListenerDemo();
        frame.setVisible(true);}}

焦点事件监听器

(待)

监听列表项选择事件

(待)

ActionListener

是Java中关于事件处理的一个接口,继承自EventListener。
用于接收操作事件的侦听器接口。对处理操作事件感兴趣的类可以实现此接口,而使用该类创建的对象可使用组件的 addActionListener 方法向该组件注册。在发生操作事件时,调用该对象的 actionPerformed 方法。

addActionListener
public void addActionListener(ActionListener l)
添加一个 ActionListener按钮。

addActionListener的三种实现方法

1.匿名内部类

?.addActionListener(newActionListener(){
    public voidactionPerformed(ActionEvent e){//to do}});

?号用注册监听事件的对象代替.
注意:我们这是在addActionListener方法里传入了一个参数,这个参数为匿名内部类,并且重写了actionPerformed方法.
2.一般内部类

//先声明
SimpleListener ourListener=newSimpleListener();
private class SimpleListener implements ActionListener{
    	public voidactionPerformed(ActionEvent e){
    		String buttonName= e.getActionCommand();if(buttonName.equals("按钮1"))
    			JOptionPane.showMessageDialog(frame,"按钮1 被点击");elseif(buttonName.equals("按钮2"))
    			JOptionPane.showMessageDialog(frame,"按钮2 被点击");else
    			JOptionPane.showMessageDialog(frame,"Unknown event");}}
然后在main方法中运行?.addActionListener(ourListener);

或者

private class SimpleListener implements ActionListener{
    	public voidactionPerformed(ActionEvent e){
    		String buttonName= e.getActionCommand();if(buttonName.equals("按钮1"))
    			JOptionPane.showMessageDialog(frame,"按钮1 被点击");elseif(buttonName.equals("按钮2"))
    			JOptionPane.showMessageDialog(frame,"按钮2 被点击");else
    			JOptionPane.showMessageDialog(frame,"Unknown event");}}

然后在main方法中运行?.addActionListener(new SimpleListener());

参考程序

package learn;import java.awt.BorderLayout;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;
public class Simple1{

	private static JFrame frame;// 定义为静态变量以便main使用
    private static JPanel myPanel;// 该面板用来放置按钮组件
    private JButton button1;// 这里定义按钮组件
    private JButton button2;// 以便让ActionListener使用
	publicSimple1()// 构造器, 建立图形界面{
		   myPanel=newJPanel();
		   button1=newJButton("按钮1");// 新建按钮1
		   button2=newJButton("按钮2");
		
		   SimpleListener ourListener=newSimpleListener();// 建立一个actionlistener让两个按钮共享
		   button1.addActionListener(newSimpleListener());
		   button2.addActionListener(newSimpleListener());
		   myPanel.add(button1);// 添加按钮到面板
		   myPanel.add(button2);}
    private class SimpleListener implements ActionListener{
    	public voidactionPerformed(ActionEvent e){
    		String buttonName= e.getActionCommand();if(buttonName.equals("按钮1"))
    			JOptionPane.showMessageDialog(frame,"按钮1 被点击");elseif(buttonName.equals("按钮2"))
    			JOptionPane.showMessageDialog(frame,"按钮2 被点击");else
    			JOptionPane.showMessageDialog(frame,"Unknown event");}}
    public static voidmain(String[] args){
    	 Simple1 gui=newSimple1();// 新建Simple1组件
    	 
      frame=newJFrame("Simple1");// 新建JFrame// 处理关闭事件的通常方法
      frame.addWindowListener(newWindowAdapter(){
      public voidwindowClosing(WindowEvent e){System.exit(0);}});
    
      frame.getContentPane().add(myPanel);
      frame.pack(); 
      frame.setVisible(true);}}

参考代码来源

JFrame常用方法

pack();使窗口适应组件的大小.

  • 作者:悭吝韶华
  • 原文链接:https://blog.csdn.net/weixin_43353639/article/details/108412952
    更新时间:2022-07-15 08:09:53