JAVA-GUI graphical user interface [Swing]

GUI - Knowledge of Graphical User Interfaces

Table of contents

GUI - Knowledge of Graphical User Interfaces

1. Introduction to GUI

1.1 Getting to know Swing for the first time 

2. Swing's top-level container

2.1 JFrame

2.2 JDialog

3. Layout Manager

3.1 BorderLayout (border layout manager)

3.2 FlowLayout (flow layout manager)

3.3 GridLayout (grid layout manager)

3.4 CardLayout (card layout manager)

4. Event processing

 4.1 Form events

 4.2 Mouse Events

 4.3 Keyboard events

 5. Swing common components

5.1 Panel Assembly

5.2 Text components

5.3 Label components

5.4 Button component

5.4.1 JCheckBox check box

5.4.2 JRadioButton radio button

5.5 JComboBox (drop-down box component)

5.6 Menu components 

5.6.1 Pull-down menu

5.6.2 JPopupMenu (popup menu) 


1. Introduction to GUI

         GUI Graphical User Interface (Graphical User Interface, referred to as GUI, also known as graphical user interface) is the graphical interface provided by the application program to the user for operation, including windows, menus, buttons, toolbars, and various other graphical interface elements.

        GUI design provides a rich class library, these classes are located in java.awt and javax.swing packages, referred to as AWT and Swing.

        Swing not only realizes all the functions in AWT, but also provides richer components and functions.

This article mainly focuses on learning Swing, and the reference material "Introduction to Java Basics"

1.1 Getting to know Swing for the first time 

        Swing is a lightweight component, which is developed by the java language, and the underlying layer is based on AWT, so that cross-platform applications can use any pluggable appearance style, and Swing can use more concise code, flexible functions and Modular components to create elegant user interfaces. It should be noted that Swing is not a substitute for AWT, but a supplement to the original AWT.

        All classes of Swing components are inherited from the Container class, and then two main branches are extended according to the functions of GUI development: container branch (including Window window and Panel panel) and component branch.

        Container branch: designed to implement graphical user interface windows.

        Component branch: It is to realize functions such as filling data, elements and human-computer interaction components into the container.

Swing component inheritance diagram

2. Swing's top-level container

        Swing provides three main top-level container classes: JFrame, JDialog, and JApplet.

2.1 JFrame

        Like Frame, JFrame is an independent top-level window and cannot be placed in other containers. JFrame supports all basic functions of general windows, such as window minimization, setting window size, and so on. The following is a small case to show the effect of using JFrame.

JFrame demo code:

package javaSE.GUI;

import javax.swing.JFrame;

/*
JFrame的常量解释
 DO_NOTHING_ON_CLOSE:当窗口关闭时,不做任何处理
 HIDE_ON_CLOSE:当窗口关闭时,隐藏这个窗口
 DISPOSE_ON_CLOSE:当窗口关闭时,隐藏并处理这个窗口(只有当它是最后一个窗口,才会退出JVM)
 EXIT_ON_CLOSE:当窗口关闭时,退出程序。(直接退出jvm)
*/

public class MyJFrame {
 public static void main(String[] args) {
	//JFrame指一个窗口,构造方法参数为窗口标题
	 JFrame frame = new JFrame("我的第一个窗口");

	 //frame.setTitle("修改窗口标题");
	 
     //设置关闭窗口时的默认操作。设置当窗口关闭时,退出程序
	 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	 //设置窗口大小
	 frame.setSize(400,300);
	 
	 //窗口弹出的初始位置
	 frame.setLocation(400,400);
	 
	 //显示窗口(这条语句 没写/填写false 窗口不会显示)
	 frame.setVisible(true);
 }
}

Show results:

2.2 JDialog

        JDialog is another top-level window of Swing, which, like Dialog, represents a dialog

        JDialog dialog boxes can be divided into two types: modal dialog boxes and non-modal dialog boxes. Among them, modal dialog boxes mean that the user needs to wait until the dialog box is processed before continuing to interact with other windows. Modeless dialogs allow the user to interact with other windows while processing the dialog.

         The dialog box is modal or non-modal, which can be set by passing parameters to the constructor when creating the Dialog object, or by calling its setModal() method after creating the JDialog object

  Common construction methods of JDialog 

JDialog(Frame owner) Construction method, used to create a non-modal dialog box, owner is the owner of the dialog box (top-level window JFrame)
JDialog(Frame owner,String title) Constructor, create a non-modal dialog box with the specified title
JDialog(Frame owner,boolean    modal) Creates an untitled dialog with the specified mode

JDialog demo code:

package javaSE.GUI;

import javax.swing.JDialog;
import javax.swing.JFrame;

/*
 * JDialog对话框
 *  模式对话框:用户需要等到处理完对话框后才能继续与其它窗口交互。
 *  非模式对话框:允许用户在处理对话框的同时与其它窗口交互。
 *  
 *  JDialog(Frame owner, String title, boolean modal)
 *  	owner:对话框所依赖的窗口
 *		title:窗口标题
 *		modal:true模式,false非模式
 *	
 */
public class MyJDialog {
	public static void main(String[] args) {
		
		//创建JFrame容器窗口,窗口名称JFrameTest
		JFrame frame = new JFrame("JFrameTest");
		//设置关闭窗口时的默认操作。EXIT_ON_CLOSE:当窗口关闭时,退出程序。
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400,300);//设置窗口大小
		frame.setVisible(true);//显示窗口
		
		//创建JDialog(对话框所有者,标题,true模式/false非模式)
		JDialog dialog = new JDialog(frame,"JDialog对话框",true);
		//设置关闭窗口时的默认操作。HIDE_ON_CLOSE:当窗口关闭时,隐藏这个窗口
		dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
		dialog.setSize(300,200);//窗口大小
		dialog.setVisible(true);//显示窗口
		
		
	}

}

Show results:

JDialog dialog = new JDialog(frame,"JDialog dialog",true);

When true, it means a modal dialog window. Before the JDialog dialog box is processed, no operation can be performed on the JFrameTest window. When changing true to false, it becomes a non-modal dialog window.

 JDialog dialog = new JDialog(frame,"JDialog dialog box",false);//Non-modal dialog window

After being modified to a non-modal dialog window, the JFrameTest window can also be operated while processing the JDialog dialog box.

Modified effect display:

3. Layout Manager

        Swing components cannot exist alone, they must be placed in a container, and the position and size of components in the container are determined by the layout manager. The Swing tool provides 8 layout managers based on AWT, namely: BorderLayout (border layout manager)
                BoxLayout (box layout manager)
                CardLayout (card layout manager)
                FlowLayout (flow layout manager)
                GridLayout ( Grid Layout Manager)
                GridBagLayout (Grid Bag Layout Manager)
                GroupLayout (Group Layout Manager)
                SpringLayout (Flexible Layout Manager)

The following will explain the commonly used layout managers.

3.1 BorderLayout (border layout manager)

        BorderLayout (Border Layout Manager) is a more complex layout method. It divides the container into five areas, namely East (EAST), South (SOUTH), West (WEST), North (NORTH), and Center (CENTER). ). Components can be placed in any of these five areas.

        When adding components to the container of the BorderLayout layout manager, you need to use the add(Component comp, Object constraints) method, where the parameter constraints is Object type, and you can use the 5 constants provided by the BorderLayout class when passing parameters, which are EAST (East), SOUTH (South), WEST (West), NORTH (North) and CENTER (Middle).

 BorderLayout code display:

package javaSE.GUI;

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

/*
 * BorderLayout(边界布局管理器)
 */
public class BorderLayoutTest1 {
	public static void main(String[] args) {
		//创建一个名为BorderLayout的顶级容器窗口
		JFrame frame = new JFrame("BorderLayout");
		
		//设置窗体的布局管理器为BorderLayout
		frame.setLayout(new BorderLayout());
		frame.setSize(300,300); 	//设置窗体大小
		frame.setLocation(300,200);	//设置窗体显示位置
		
		//下面的代码是创建五个按钮主键
		JButton but1 = new JButton("NORTH(北)");
		JButton but2 = new JButton("SOUTH(南)");
		JButton but3 = new JButton("WEST(西)");
		JButton but4 = new JButton("EAST(东)");
		JButton but5 = new JButton("CENTER(中)");
		
		//将创建好的按钮组件添加到窗体中,并设置按钮所在的区域
		frame.add(but1, BorderLayout.NORTH);//北
		frame.add(but2, BorderLayout.SOUTH);//南
		frame.add(but3, BorderLayout.WEST);	//西
		frame.add(but4, BorderLayout.EAST);	//东
		frame.add(but5, BorderLayout.CENTER);//中
		
		//窗体可见
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		
	}
}

Show results:

What if you add a button with one less position? Let's try without adding the button with the position of North

//不添加位置为北的按钮(先注释掉下面这行代码)
//frame.add(but1, BorderLayout.NORTH);//北

 Comment out the effect of the button whose position is north:

3.2 FlowLayout (flow layout manager)

        FlowLayout is a flow layout manager, it is the simplest layout manager. When using the FlowLayout layout manager, the container will place components from left to right in the order they were added. When the bounds of the container are reached, the component is automatically placed at the beginning of the next line. These components can be aligned left, center (the default), or right

   FlowLayout constructor

FlowLayout() Components are centered by default, and the horizontal and vertical spacing defaults to 5 units
FlowLayout(int align) Specifies the alignment of the component relative to the container. The horizontal and vertical spacing defaults to 5 units
FlowLayout(int align,int hgap,int vgap) Specifies the alignment and horizontal and vertical spacing of components

The construction method of FlowLayout:

Among them, align determines the alignment of components relative to the border of the container in each row, respectively:

  FlowLayout.LEFT (left alignment)
  FlowLayout.RIGHT (right alignment)
  FlowLayout.CENTER (center alignment)

The parameters hgap and vgap respectively set the horizontal and vertical spacing between components, and any value can be filled in.

FlowLayout code display:

package javaSE.GUI;


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

/*
 * FlowLayout(流式布局管理器)
 * 
 *FlowLayout.LEFT   (左对齐)
 *FlowLayout.RIGHT  (右对齐)
 *FlowLayout.CENTER (居中对齐)
 */
public class FlowLayoutTest {
	public static void main(String[] args) {
		//创建一个名为FlowLayout的窗体
		JFrame f = new JFrame("FlowLayout");
		
		//设置窗体中的布局管理器为FlowLayout
		//所有组件左对齐,水平间距为20,垂直间距为24
		f.setLayout(new FlowLayout(FlowLayout.LEFT,20,24));
		f.setSize(400,200);		//设置窗体大小
		f.setLocation(300,200); //设置窗体显示位置
		
		//向容器添加组件
		f.add(new JButton("老大"));
		f.add(new JButton("老二"));
		f.add(new JButton("老三"));
		f.add(new JButton("老四"));
		f.add(new JButton("老五"));
		f.add(new JButton("老六"));
		
		//窗体可见
		f.setVisible(true);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
	}
}

Show results:

3.3 GridLayout (grid layout manager)

        GridLayout (grid layout manager) uses vertical and horizontal lines to divide the container into grids of equal size with n rows and m columns, and place a component in each grid.

         The components added to the container are first placed in the grid of row 1, column 1 (upper left corner), and then other components are placed in the grid of row 1 from left to right. When the row is full, continue to the next row Place components from left to right

GridLayout construction method

GridLayout() There is only one row by default, and each component occupies a column
GridLayout(int rows,int cols) Specify the number of rows and columns for the container
GridLayout(int rows,int cols,int hgap,int vgap) Specify the number of rows and columns of the container and the horizontal and vertical distance between components

GridLayout code display:

package javaSE.GUI;

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

/*
 * GridLayout(网格布局管理器)
 */
public class GridLayoutTest {
	public static void main(String[] args) {
		//创建一个名为GridLayout的窗体
		JFrame f = new JFrame("GridLayout");
		

		//设置窗体中的布局管理器GridLayout
		//设置该窗体为3*3的网格
		f.setLayout(new GridLayout(3,3));
		f.setSize(300,300);		//设置窗体大小
		f.setLocation(400,400); //设置窗体显示位置
		
		//使用循环添加8个按钮到GridLayout容器中
		for(int i = 1; i <= 8; i++) {
			Button btn = new Button(i + "号键");
			f.add(btn);
		}
		
		//窗体可见
		f.setVisible(true);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		
	}

}

Show results:

3.4 CardLayout (card layout manager)

        CardLayout (card layout manager) regards the interface as a series of cards, only one of which is visible at any time, and this card occupies the entire area of ​​​​the container

CardLayout constructor

void first(Container parent)

Show the first card of the parent container

void last(Container parent)

Display the last card of the parent container

void previous(Container parent)

Show the previous card of the parent container

void next(Container parent)

Show the next card of the parent container

void show(Container parent,

String name)

Display the component named name in the parent container, if it does not exist, nothing will happen.

CardLayout code display:

package javaSE.GUI;

import java.awt.*;
import java.awt.event.*;

/*
1、CardlayoutTest类继承Frame类,实现ActionListener接口
2、在该类中定义Panel面板放置卡片,再定义一个Panel面板放置按钮
3、定义卡片布局对象,在卡片面板中添加2个文本标签分别为“传智播客”和“黑马程序员”
4、定义一个方法实现按钮的监听触发,并对触发事件做出相应的处理
*/
class CardlayoutTest extends Frame implements ActionListener {
	Panel cardPanel = new Panel();              // 创建Panel面板放置卡片
	Panel controlpaPanel = new Panel();         // 创建Panel面板放置按钮
    Button nextbutton, preButton;	//创建按钮
	CardLayout cardLayout = new CardLayout();//定义卡片布局对象
	
	public CardlayoutTest() { //定义构造方法,设置卡片布局管理器的属性
		
		cardPanel.setLayout(cardLayout); // 设置cardPanel面板对象为卡片布局
		// 在cardPanel面板对象中添加3个文本标签
		cardPanel.add(new Label("蛋炒饭", Label.CENTER));
		cardPanel.add(new Label("回锅肉", Label.CENTER));
		cardPanel.add(new Label("大头鱼", Label.CENTER));
		
		// 创建两个按钮对象
		nextbutton = new Button("下一张卡片");
		preButton = new Button("上一张卡片");
		
		// 为按钮对象注册监听器
		nextbutton.addActionListener(this);
		preButton.addActionListener(this);
		
		// 将按钮添加到controlpaPanel【控制面板】中
		controlpaPanel.add(preButton);
		controlpaPanel.add(nextbutton);
		
		// 将cardPanel面板放置在窗口边界布局的中间,窗口默认为边界布局
		this.add(cardPanel, BorderLayout.CENTER);
		// 将controlpaPanel面板放置在窗口边界布局的南区,
		this.add(controlpaPanel, BorderLayout.SOUTH);
		
		setSize(300, 200); //设置窗口大小	
		setVisible(true);  //显示窗口
		// 为窗口添加关闭事件监听器
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				CardlayoutTest.this.dispose();
			}
		});
		
		
	}
	
	// 下面的代码实现了按钮的监听触发,并对触发事件做出相应的处理
	public void actionPerformed(ActionEvent e) {
		// 如果用户单击nextbutton,执行的语句
		if (e.getSource() == nextbutton) {
		// 切换cardPanel面板中当前组件之后的一个组件,若当前组件为最后一个组件,则显示第一个组件。
			cardLayout.next(cardPanel);
		}
		if (e.getSource() == preButton) {
		// 切换cardPanel面板中当前组件之前的一个组件,若当前组件为第一个组件,则显示最后一个组件。
			cardLayout.previous(cardPanel);
		}
	}
	

}
public class Test {
	public static void main(String[] args) {
		new CardlayoutTest();//创建CardlayoutTest实例
	}
}

Show results:

4. Event processing

        Event handling in Swing components is designed to respond to user actions. In the process of Swing event processing, three types of objects are mainly involved:

1. Event source (component): the place where the event occurs, usually the component that generates the event, such as window, button, menu, etc. 

2. Event object (Event): encapsulates a specific event that occurs on the GUI component (usually an operation by the user)

3. Listener (Listener): An object responsible for listening to events occurring on the event source and responding to various events (the object includes an event handler). Event handler: the method for the listener object to process the received event object accordingly

Rich events are provided in AWT, roughly including form events, mouse events, keyboard events, action events, etc.

 Event processing flow chart

         In the program, if you want to implement the event monitoring mechanism, you must first define a class that implements the interface of the event listener. For example, a window of type Window needs to implement WindowListener. Then register the event listener object for the event source through the addWindowListener() method. When an event occurs on the event source, the event listener object will be triggered, and the event listener will call the corresponding method to process the corresponding event.

Let's write a small example to feel it

 Code display:

package javaSE.GUI;

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


/*
 * 实现步骤
 *  在JFrame窗口中添加一个JButton按钮组件
 *  同时通过addActionListener()方法为按钮组件添加一个自定义事件监听器
 *  当单击按钮组件时就会触发事件监听器,进行事件处理
 */

//自定义事件监听器类
class MyListener implements ActionListener{
	//实现监听器方法,对监听器事件进行处理
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("您点击了JButton按钮组件");
	}
}


public class Test01 {
	public static void main(String[] args) {
		
		//创建一个名为事件测试的窗体
		JFrame f = new JFrame("事件测试");
		f.setSize(400, 200); //设置窗口大小
		
		//创建一个按钮组件,作为事件源
		JButton btn = new JButton("按钮");
		
		//为按钮组件(事件源)添加自定义监听器
		btn.addActionListener(new MyListener());
		
		f.add(btn);//向容器中添加按钮组件
		f.setVisible(true);//窗体可见
	    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
	}
	

}

Show results

After clicking the button, the relevant information is printed in the background

 4.1 Form events

         WindowEvent, in an application, when processing a window event, you first need to define a class that implements the WindowListener interface as a window listener, and then use the addWindowListener() method to connect the window object with the window listener bound.

        Most GUI applications need to use the Windows Form object as the outermost container. It can be said that the form object is the basis of all GUI applications. Applications usually add other components to the form directly or indirectly. Form opening, closing, activation, deactivation, etc., these actions are all form events.

Form event code display:

package javaSE.GUI;


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

public class WindowsEventTest {
	public static void main(String[] args) {
		JFrame f = new JFrame("窗体事件");	//创建一个名为窗体事件的窗体
		f.setSize(400,300);		//设置窗体大小
		f.setLocation(300,200);	//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
        //f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//测试windowClosed
        //窗口关闭时,隐藏并处理这个窗口(只有当它是最后一个窗口,才会退出JVM)
        
		// 使用内部类创建WindowListener实例对象,监听窗体事件
		f.addWindowListener(new WindowListener() {
			
			public void windowOpened(WindowEvent e) {
				System.out.println("窗体打开事件");
			}
			
			public void windowIconified(WindowEvent e) {
				System.out.println("窗体图标化事件");//最小化
			}
			
			public void windowActivated(WindowEvent e) {
				System.out.println("窗体激活事件");//获得焦点状态
			}
			
			public void windowDeiconified(WindowEvent e) {
				System.out.println("窗体取消图标化事件");//最小化恢复正常
			}
			
			public void windowDeactivated(WindowEvent e) {
				System.out.println("窗体停用事件");//失去焦点状态
			}
			
			public void windowClosing(WindowEvent e) {
				System.out.println("窗体正在关闭事件");
                //关闭,点击右上角X,优先于windowClosed
			}
			
			public void windowClosed(WindowEvent e) {
				System.out.println("窗体关闭事件");
                //关闭,设置为 DISPOSE_ON_CLOSE时才会被调用
			}
		});
	}
}

Window event effect display:

Note that windowClosed (window close event) will only be displayed when it is set to DISPOSE_ON_CLOSE

DISPOSE_ON_CLOSE: [When the window is closed, hide and process this window (only when it is the last window, it will exit the JVM)]

Window operation : minimize, click the icon (minimize to return to normal), click the close button in the upper right corner .

 4.2 Mouse Events

        Mouse events (MouseEvent), almost all components can generate mouse events, mouse events include mouse down, mouse release, mouse click, etc.

        The mouse event can be processed by implementing the MouseListener interface or inheriting the adapter MouseAdapter class, and then calling the addMouseListener() method to bind the listener to the event source object.

Mouse event code display:

package javaSE.GUI;

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

/*
 * 鼠标事件(MouseEvent)
 */
public class MouseEventTest {
	public static void main(String[] args) {
		
        创建一个名为鼠标事件的窗体
		JFrame f = new JFrame("鼠标事件");

		//窗口设置流式布局管理器
        //[FlowLayout() : 组件默认居中对齐,水平、垂直间距默认为5个单位]
		f.setLayout(new FlowLayout());

		f.setSize(300, 200); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		Button but = new Button("按钮"); // 创建按钮对象
		f.add(but); // 在窗口添加按钮组件
		
		//为按钮添加鼠标事件监听器
		but.addMouseListener(new MouseListener() {
			public void mouseReleased(MouseEvent e) {
				System.out.println("鼠标放开");
			}
			public void mousePressed(MouseEvent e) {
				System.out.println("鼠标按下");
			}
			public void mouseExited(MouseEvent e) {
				System.out.println("鼠标移出按钮区域");
			}
			public void mouseEntered(MouseEvent e) {
				System.out.println("鼠标进入按钮区域");
			}
			public void mouseClicked(MouseEvent e) {
				System.out.println("鼠标完成点击");
			}
		});
	}
}


Mouse event effect display:

 4.3 Keyboard events

        Keyboard operations are also the most commonly used user interaction methods, such as keyboard presses, releases, etc. These operations are defined as keyboard events.

        Keyboard event (KeyEvent), the listener object that handles the KeyEvent event needs to implement the KeyListener interface or inherit the KeyAdapter class, and then call the addKeyListener() method to bind the listener to the event source object.

The keyboard event code shows:

package javaSE.GUI;

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

/*
 * 键盘事件(KeyEvent)
 */
public class KeyEventTest {
	public static void main(String[] args) {
		//创建一个名为键盘事件的窗体
		JFrame f = new JFrame("键盘事件");
		
		//窗口设置流式布局管理器
		//[FlowLayout() : 组件默认居中对齐,水平、垂直间距默认为5个单位]
		f.setLayout(new FlowLayout());
		
		f.setSize(400, 300);	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		TextField tf = new TextField(30); //创建文本框对象
		f.add(tf); 			//在窗口中添加文本框组件
		f.setVisible(true);	//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
         // 为文本框添加键盘事件监听器
		tf.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				// 获取所按键对应的字符代码(键码)
			 	int keyCode = e.getKeyCode(); 
			 	// 获取所按键的键盘字符
				String keyChar = KeyEvent.getKeyText(keyCode);
				//char keyChar = e.getKeyChar(); 
				//方法二 单字符可以,但是像Shift,Ctrl等键就显示不出来,打印为?
			 	
				System.out.print("输入的内容为:" + keyChar + " , ");
				System.out.println("KeyCode(键码)为:" + keyCode);
			}
		});
	}
}

Keyboard event effect display:

 

 5. Swing common components

5.1 Panel Assembly

        Swing components not only have top-level containers such as JFrame and JDialog, but also provide some panel components, also known as intermediate containers. This means that panel components cannot exist alone and can only be placed in top-level containers. There are two common panel components: Jpanel and JScrollPane.

        Jpanel: It is a borderless panel that cannot be moved, enlarged, reduced or closed. Its default layout manager is FlowLayout. Of course, you can also use the constructor JPanel(LayoutManager layout) or its setLayout() method to make a layout manager for it.

        JScrollPane : A panel container with a scroll bar, and this panel can only add one component. If you want to add multiple components to the JScrollPane panel, you should first add these multiple components to a component (such as JPane), and then add This component (eg JPanel) is added to the JScrollPane.

Common construction methods of JScrollPane

JScrollPane() Create an empty JScrollPane panel
JScrollPane (Component view) Creates a JScrollPane that displays the specified component, and displays horizontal and vertical scroll bars as long as the content of the component exceeds the view size
JScrollPane (Component view,int vsbPolicy,int hsbPolicy)

Creates a JScrollPane that displays the specified container and has the specified scrolling policy. Parameters vsbPolicy and hsbPolicy represent vertical scrolling policy and horizontal scrolling policy respectively.

    JScrollPane set panel scroll strategy method

void setHorizontalBarPolicy(int policy) Specifies the horizontal scroll bar policy, that is, when the horizontal scroll bar is displayed on the scroll panel
void setVerticalBarPonlicy(int policy) Specifies the vertical scroll bar policy, that is, when the vertical scroll bar is displayed on the scroll panel
void setViewportView(Component view)

Set the components displayed in the scroll panel

         JScrollPane panel scrolling strategy

HORIZONTAL_SCROLLBAR_AS_NEEDED Showing horizontal scrollbars only when needed is the default policy. (The horizontal scroll axis appears when the content of the horizontal area is larger than the display area)
HORIZONTAL_SCROLLBAR_NEVER Horizontal scrollbar never shows
HORIZONTAL_SCROLLBAR_ALAWAYS The horizontal scroll bar is always displayed
VERTICAL_SCROLLBAR_AS_NEEDED  The vertical scroll axis appears when the content of the vertical area is larger than the display area
VERTICAL_SCROLLBAR_NEVER The vertical scroll axis never shows up
VERTICAL_SCROLLBAR_ALWAYS The vertical scroll axis is always displayed

Code display:

package javaSE.GUI;

/*
 * JScrollPane是一个带有滚动条的面板容器,而且这个面板只能添加一个组件,
 * 如果想往JScrollPane面板中添加多个组件,应该先将组件添加到JPanel中,
 * 然后将JPanel添加到JScrollPane中.
 */
import java.awt.*;
import javax.swing.*;

public class JScrollPaneTest {
	public static void main(String[] args) {
		//1、创建一个名为PanelDemo的窗体
		JFrame f = new JFrame("PanelDemo");
			
		/*
		 * BorderLayout 窗口设置边界布局管理器
		 * 边界布局管理器 将容器划分为五个区域:
		 *   分别是东(EAST)、南(SOUTH)、西(WEST)、北(NORTH)、中(CENTER)
		 */
		f.setLayout(new BorderLayout());
				
		f.setSize(350, 200);	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);	//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		//2、创建JScrollPane滚动面板组件
		JScrollPane scrollPane = new JScrollPane();
		// 设置水平滚动条策略-滚动条需要时显示
		scrollPane.setHorizontalScrollBarPolicy
			(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		// 设置垂直滚动条策略-滚动条一直显示
		scrollPane.setVerticalScrollBarPolicy
			(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		
		//3、定义一个JPanel面板
		JPanel panel = new JPanel();
		//在Panel面板中添加五个按钮
		panel.add(new JButton("金"));
		panel.add(new JButton("木"));
		panel.add(new JButton("水"));
		panel.add(new JButton("火"));
		panel.add(new JButton("土"));
		
		//设置JPanel面板在滚动面板JScrollPane中显示
		scrollPane.setViewportView(panel);
		//4、向JFrame容器窗口中添加JScrollPane滚动面板
		f.add(scrollPane,BorderLayout.CENTER);//BorderLayout.CENTER 设置为中
		
		
	}
}

Show results:

 The horizontal scroll bar strategy is HORIZONTAL_SCROLLBAR_AS_NEEDED. The horizontal scroll bar will only be displayed when the full content cannot be displayed in the horizontal direction, so we need to pull the window horizontally and zoom out to see the effect.

5.2 Text components

The JTextComponent class has two subclasses, namely JTextField (text box) and JTextArea (text field)

Common methods of JTextComponent

String String getText() Returns all text content in the text component
String  String getSelectedText() Returns the selected text content in the text component
void selectAll() Select everything in the text component
void setEditable(boolean b) Set the text component as editable or non-editable
void setText(String text) Set the content of the text component
void replaceSelection(String content) Replace the currently selected content with the given content

Common construction methods of JTextField

JTextField() Creates an empty textbox with an initial string of null
JTextField(int columns) Creates a textbox with the specified number of columns, with an initial string of null
JTextField(String text) Creates a text box that displays the specified initial string
JTextField(String text, int columns) Create a text box with the specified number of columns and display the specified initial string

Common construction methods of JTextArea

JTextArea() Constructor, create an empty text field
JTextArea(String text) Constructor method to create a text field that displays the specified initial string
JTextArea(int rows,int columns) Constructor that creates an empty text field with the specified number of rows and columns
JTextArea(String text,int rows,int columns) Construction method, create a text field that displays the specified initial text and specifies the row and column

Write a chat window below to demonstrate the basic use of text components JTextField (text box) and JTextArea (text field) components

Code display:

package javaSE.GUI;

import java.awt.BorderLayout;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*
	编写一个简单的聊天窗口:
		使用JFrame顶级容器创建并设置了一个聊天窗口
		BorderLayout边界布局管理器分为:上下两个区域
			中:
				JScrollPane滚动面板,
				该面板中封装了JTextArea文本域(显示聊天记录)
			南:
				JPanel面板中放置了三个组件
				JLabel标签(用于信息说明)
				JTextField文本框(输入聊天信息)
				JButton按钮(发送消息)
				
 */
public class TextTest {
	public static void main(String[] args) {
		//1、创建一个名为聊天窗口的窗体
		JFrame f = new JFrame("聊天窗口");	
		/*
		 * BorderLayout 窗口设置边界布局管理器
		 * 边界布局管理器 将容器划分为五个区域:
		 *   分别是东(EAST)、南(SOUTH)、西(WEST)、北(NORTH)、中(CENTER)
		 */
		f.setLayout(new BorderLayout());
		
		//2、创建一个JTextArea文本域,用来显示多行聊天信息
		JTextArea showArea = new JTextArea(12,34);
		//创建一个JScrollPane滚动面板组件,将JTextArea文本域作为其显示组件
		/*
		 * JScrollPane (Component view)	
		 * 创建一个显示指定组件的JScrollPane面板,
		 * 只要组件的内容超过视图大小,就会显示水平和垂直滚动条
		 */
		JScrollPane scorllPane = new JScrollPane(showArea);
		showArea.setEditable(false); //设置文本域不可编辑
		
		//3、创建一个JTextField文本框,用来输入单行聊天信息
		JTextField inputField = new JTextField(20);
		JButton btn = new JButton("发送");  // 创建一个发送按钮
		
		// 为按钮添加事件
		btn.addActionListener(new ActionListener() { // 为按钮添加一个监听事件
			public void actionPerformed(ActionEvent e) {// 重写actionPerformed方法
				String content = inputField.getText();  // 获取输入的文本信息
              // 判断输入的信息是否为空
				if (content != null && !content.trim().equals("")) {
                    // 如果不为空,将输入的文本追加到到聊天窗口(放入文本域中)
					showArea.append("路人甲:"+content + "\n"); 
				    } else {
                    // 如果为空,提示短信内容不能为空
				    showArea.append("消息内容不能为空!" + "\n");
				}
				inputField.setText(""); //最后将输入的文本域内容置为空
			}
		});
		
		//4、创建一个JPanel面板组件
		JPanel panel = new JPanel();
		JLabel label = new JLabel("聊天信息");	//创建一个标签
		panel.add(label);		//将标签组件添加到JPanel面板
		panel.add(inputField);	//将文本框添加到JPanel面板
		panel.add(btn);			//将按钮添加到JPanel面板
		
		//5、向JFream聊天窗口的中部和南部分别加入面板组件JScrollPane和JPanel
		f.add(scorllPane,BorderLayout.CENTER);//中(CENTER)
		f.add(panel,BorderLayout.SOUTH);	  //南(SOUTH)
		
		f.setSize(400, 350); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		
	}

}

Show results:

5.3 Label components

        The label component in Swing mainly uses JLabel.

        JLabel组件可以显示文本,图像,还可以设置标签内容的垂直和水平对齐方式。

JLabel构造方法

JLabel() 创建无图像并且标题为中字符串的JLabel
JLabel(Icon image) 创建有指定图像的JLabel
JLabel(Icon image,int horizontalAlignment) 创建有指定图像和水平对齐方式的JLabel
JLabel(String text) 创建有指定文本的JLabel
JLabel(String text,Icon icon,int horizontalAlignment) 创建有指定文本、图像和水平对齐方式的JLabel
JLabel(String text,int horizontalAlignment) 创建有指定文本和水平对齐方式的JLabel

代码展示:

package javaSE.GUI;

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

/*
	使用JFrame顶级容器
	BorderLayout边界布局管理器分为:上下两个区域
		中:
			JLabel标签(加入图标【ImageIcon图标组件】)
		南:
			JLabel标签(加入文字)
			

	SCALE_DEFAULT 		   使用默认的图像缩放算法。
	SCALE_AREA_AVERAGING   使用 Area Averaging 图像缩放算法。
	SCALE_FAST     		   选择一种图像缩放算法,在这种缩放算法中,缩放速度比缩放平滑度具有更高的优先级。
	SCALE_REPLICATE        使用 ReplicateScaleFilter 类中包含的图像缩放算法。
	SCALE_SMOOTH           选择图像平滑度比缩放速度具有更高优先级的图像缩放算法
 */
public class JLabelTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1、创建一个名为JLabel测试的窗体
		JFrame f = new JFrame("JLabel测试");	
		/*
		 * BorderLayout 窗口设置边界布局管理器
		 * 边界布局管理器 将容器划分为五个区域:
		 *   分别是东(EAST)、南(SOUTH)、西(WEST)、北(NORTH)、中(CENTER)
		 */
		f.setLayout(new BorderLayout());
		
		//2、创建一个JLabel标签,用于展示图片
		JLabel label = new JLabel();
		/*
		     创建一个ImageIcon图标组件,从指定的文件中读取相关图象信息,它支持GIF和JPG、BMP等基本图象格式
		     我的test.jpg,就放在项目。如果图盘放在src目录下 "src/test.jpg"
		*/
		ImageIcon icon = new ImageIcon("test.jpg"); 
		Image img = icon.getImage();	//获取这个Icon的image
		//用于设置图片大小尺寸(宽度,高度,SCALE_DEFAULT使用默认的图像缩放算法)
		img = img.getScaledInstance(400, 200, Image.SCALE_DEFAULT);
		
		icon.setImage(img);	//将调好的image放到ImageIcon
		label.setIcon(icon);//将ImageIcon放入JLabel图标中
		
		//3、创建一个JPanel面板
		JPanel panel = new JPanel();
		//创建JLabel标签(指定文本,水平对齐方式)【CENTER居中】
		JLabel label2 = new JLabel("祝你 早安、午安、晚安",JLabel.CENTER);
		panel.add(label2);//将JLabel标签添加到JPanel面板
		
		//4、向JLabel测试窗口的中部部和南部分别加入面板组件JLabel和JPanel
		f.add(label,BorderLayout.CENTER);//中
		f.add(panel,BorderLayout.SOUTH); //南
		
		f.setSize(400, 300); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
	}

}

效果展示:

5.4 按钮组件

        常见的按钮组件有JButton、JCheckBox、JRadioButton等,它们都是抽象类AbstractButton类的直接或间接子类。

AbstractButton 常用方法

Icon getIcon 获取按钮组件
void setIcon(Icon icon) 设置按钮的图标
String getText() 获取按钮的文本
void setText(String text) 设置按钮的文本
void setEnable(boolean b) 设置按钮是否可用
boolean setSelected(boolean b) 设置按钮是否为选中状态
boolean isSelected() 返回按钮的状态(true为选中,反之则未选中)

5.4.1 JCheckBox 复选框

        JCheckBox组件(复选框),它有 选中/未选中 两种状态。如果复选框有多个,则用户可以选中其中一个或者多个。

JCheckBox 常用发方法

JCheckBox() 创建一个没有文本信息,初始状态未被选中的复选框
JCheckBox(String text) 创建一个带有文本信息,初始状态未被选中的复选框
JCheckBox(String text,boolean selected) 创建一个带有文本信息,并指定初始状态(选中/未选中)的复选框

代码展示:

package javaSE.GUI;

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

/*
	使用JFrame顶级容器
	使用BorderLayout边界布局管理器分为:上下两个区域
			JLabel标签(用来展示文字)
		南:
			JPanel面板中放置了两个JCheckBox复选框和JLabel标签(提示信息)
			(两个复选框分别对应不同的字体样式)

 */
public class JCheckBoxTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1、创建一个名为 JCheckBoxTest的窗体
		JFrame f = new JFrame(" JCheckBoxTest");	
		/*
		 * BorderLayout 窗口设置边界布局管理器
		 * 边界布局管理器 将容器划分为五个区域:
		 *   分别是东(EAST)、南(SOUTH)、西(WEST)、北(NORTH)、中(CENTER)
		 */
		f.setLayout(new BorderLayout());
			
		//2、创建一个JLabel标签组件 ,标签文本居中对齐
		JLabel label = new JLabel("骑马倚斜桥,满楼红袖招",JLabel.CENTER);
		// 设置标签文本的字体(Font是一个字体类,PLAIN(普通样式),BOLD(粗体样式),ITALIC(斜体样式))
		label.setFont(new Font("宋体", Font.PLAIN, 20));
		
		//3、创建一个JPanel面板组件
		JPanel panel = new JPanel();
		//创建两个JCheckBox复选框,并添加到JPanel组件中
		JCheckBox italic = new JCheckBox("斜体");
		JCheckBox bold = new JCheckBox("黑体");
		
		//为复选框定义ActionListener监听器
		ActionListener listener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int mode = 0; 
				if(bold.isSelected())	//如果bold黑体复选框被选中
					mode += Font.BOLD;	//字体添加黑体样式
				if(italic.isSelected()) //如果italic斜体复选框被选中
					mode += Font.ITALIC; //字体添加斜体样式
				label.setFont(new Font("宋体", mode , 20));
				
			}
			
		};
		
		//为两个复选框添加监听器
		italic.addActionListener(listener);
		bold.addActionListener(listener);
		
		JLabel label2 = new JLabel("请选择文字的样式:");//创建一个标签(提示信息)
		panel.add(label2);//将标签添加到JPanel面板
		//将复选框添加到JPanel面板
		panel.add(italic);
		panel.add(bold);
		
		//4、向JFrame窗口中加入居中的JLabel标签组件和JPanel面板组件
		f.add(label);
		f.add(panel,BorderLayout.SOUTH);//南
				
		f.setSize(400, 350); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		
	}

}

效果展示:

5.4.2 JRadioButton 单选按钮

        JRadioButton组件(单选按钮),与JCheckBox复选框不同的是,单选按钮只能选中一个。对于JRadioButton按钮来说,当一个按钮被选中时,先前被选中的按钮就会自动取消选中。

JRadioButton 常见构造方法

JRadioButton() 创建一个没有文本信息、初始状态未被选中的单选框
JRadioButton(String text) 创建一个带有文本信息、初始状态未被选中的单选框
JRadioButton(String text,boolean selected) 创建一个带有文本信息、并指定初始状态(选中/未选中)的单选框

代码展示:

package javaSE.GUI;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
	使用JFrame顶级容器
		在JPanel面板上放置三个JRadioButton按钮,代表“红”、“黄”、“蓝”
		按钮添加到panel面板和ButtonGroup按钮组中并添加监听器
		选择三个JRadioButton按钮可以改变面板的颜色

 */
public class JRadioButtonTest {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1、创建一个名为 JRadioButtonTest的窗体
		JFrame f = new JFrame(" JRadioButtonTest");	
		/*
		 * BorderLayout 窗口设置边界布局管理器
		 * 边界布局管理器 将容器划分为五个区域:
		 *   分别是东(EAST)、南(SOUTH)、西(WEST)、北(NORTH)、中(CENTER)
		 */
		f.setLayout(new BorderLayout());
			
		//2、创建一个 JPanel面板(放置三个JRadioButton按钮)
		JPanel panel = new JPanel();
		//创建ButtonGroup按钮组件
		ButtonGroup group = new ButtonGroup();
		//创建三个JRadioButton单选框
		JRadioButton red = new JRadioButton("红");
		JRadioButton yellow = new JRadioButton("黄");
		JRadioButton blue = new JRadioButton("蓝");
		//将单选框添加到同一个ButtonGroup按钮组件中
		group.add(red);
		group.add(yellow);
		group.add(blue);
		
		//3、创建一个JPanel面板作为调色板
		JPanel panel2 = new JPanel();
		
		//为单选按钮定义ActionListener监听器
		ActionListener listener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				Color color = null;
				if(red.isSelected()) {//red红单选框是否被选中
					color = Color.RED;	
				}else if(yellow.isSelected()) {//yellow黄单选框是否被选中
					color = Color.YELLOW; 
				}else{//BLUE蓝单选框被选中
					color = Color.BLUE;
				}
				panel2.setBackground(color);//设置背景颜色
				
			}
			
		};
		
		//为三个单选添加监听器
		red.addActionListener(listener);
		yellow.addActionListener(listener);
		blue.addActionListener(listener);
		
		//将复选框添加到JPanel面板
		panel.add(red);
		panel.add(yellow);
		panel.add(blue);
		
		//4、向JFrame窗口中加入JPanel面板组件和JPanel2面板组件
		f.add(panel,BorderLayout.NORTH);//北
		f.add(panel2,BorderLayout.CENTER);//中
				
		f.setSize(400, 350); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		
	}
}

效果展示:

 

5.5 JComboBox(下拉框组件)

         JComboBox组件被称为组合框或者下拉列表框,它将所有选项折叠收藏在一起,默认显示的是第一个添加的选项。当用户点击组合框时,会出现下拉式的选择列表,用户可以从中选择其中一项并显示。

JComboBox 对象的构造方法

JComboBox() 创建一个没有可选项的下拉框
JComboBox(Object[ ] items) 创建一个下拉框,将Object数组中的元素作为下拉框的下拉列表选项
JComboBox(Vector items) 创建一个下拉框,将Vector集合中的元素作为下拉框的下拉列表选项

JComboBox 常用方法

void addItem(Object anObject) 为下拉框添加选项
void insertItemAt(Object anObject,int index) 在指定索引处添加选项
Object getItemAt(int index) 返回指定索引处选项,第一个选项的索引为0
int getItemCount() 返回下拉框中选项的数目
Object getSelectedItem() 返回当前所选项
void removeAllItems() 删除下拉框中所有选项
void removeItem(Object object) 从下拉框中删除指定选项
void removeItemAt(int index) 移除指定索引的选项
void setEditable(boolean aFlag) 设置下拉框的选项是否可编辑,true可编辑,反之则不可编辑

代码展示:

package javaSE.GUI;

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

import javax.swing.*;
/*
使用JFrame顶级容器
	使用BorderLayout边界布局管理器分为:
		北:
			JComboBox下拉框(注册监听器)
			JTextField文本框
 */
public class JComboBoxText {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1、创建一个名为 JComboBoxText的窗体
		JFrame f = new JFrame(" JComboBoxText");	
		/*
		 * BorderLayout 窗口设置边界布局管理器
		 * 边界布局管理器 将容器划分为五个区域:
		 *   分别是东(EAST)、南(SOUTH)、西(WEST)、北(NORTH)、中(CENTER)
		 */
		f.setLayout(new BorderLayout());
			
		//2、创建一个 JPanel面板,用来封装JComboBox下拉框
		JPanel panel = new JPanel();
		//创建JComboBox下拉框
		JComboBox<String> comboBox = new JComboBox<>();
		//为下拉框添加选项
		comboBox.addItem("请选择角色");
		comboBox.addItem("天星");
		comboBox.addItem("暗影");
		comboBox.addItem("绿魔");
		comboBox.addItem("王霸");
		
		//创建JTextField文本框组件,展示用户的选择
		JTextField textField = new JTextField(20);
		
		//为JComboBox下拉框定义ActionListener监听器
		ActionListener listener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				//获取当前所选项
				String item = (String) comboBox.getSelectedItem();
				if("请选择角色".equals(item)) {
					textField.setText("");
				}else {
					textField.setText("您选择到角色是:" + item);
				}
				
			}
			
		};
		
		//为下拉框添加监听器
		comboBox.addActionListener(listener);

		//将JComboBox下拉框和JTextField文本框添加到JPanel面板
		panel.add(comboBox);
		panel.add(textField);
		
		//4、向JFrame窗口中加入JPanel面板组件和JPanel2面板组件
		f.add(panel,BorderLayout.NORTH);//北
				
		f.setSize(400, 200); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序
		
		
	}	

}

效果展示:

5.6 菜单组件 

        Swing提供了很多中样式的菜单,这次我们主要来学习下拉式菜单和弹出式菜单。

5.6.1 下拉式菜单

         下拉式菜单包括JMenuBar(菜单栏)、JMenu(菜单)和JMenuItem(菜单项)。用记事本为例,展示一下这三个组件所对应的位置。

JMenuBar:表示一个水平的菜单栏,它用来管理菜单,不参与同用户的交互式操作。 JMenu:表示一个菜单,它用来整合管理菜单项。菜单可以是单一层次的结构,也可以是多层次的结构。                                                                                                              JMenuItem:表示一个菜单项,它是菜单系统中最基本的组件。和JMenu菜单一样,在创建JMenuItem菜单项时,通常会使用JMenumItem(String text)这个构造方法为菜单项指定文本内容。JMenuItem继承自AbstractButton类,因此可以把它看成是一个数组,如果使用无参的构造方法创建一个菜单项,则可以调用从AbstractButton类中继承的setText()方法和setIcon()方法为其设置文本和图标

 JMenu 常用方法(菜单)

JMenuItem add(JMenuItem menuItem)  将菜单项添加到菜单末尾,返回此菜单
void addSeparator() 将分隔符添加到菜单的末尾
JMenuItem getItem(int pos) 返回指定索引处的菜单项,第一个菜单项的索引为0
int getItemCount() 返回菜单上的项数,菜单项和分隔符都计算在内
JMenuItem insert(JmenuItem menuItem,int pos) 在指定索引处插入菜单项
void insertSeparator(int pos) 在指定索引处插入分隔符
void remove(int pos) 从菜单中移除指定索引处的菜单项
void remove(JMenuItem menuItem) 从菜单中移除指定的菜单项
void removeAll() 从菜单中移除所有的菜单项

代码展示:

package javaSE.GUI;

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

/*
 使用JFrame顶级容器
	创建JMenuBar菜单栏对象,将其放置在JFrame窗口的顶部
	创建JMenu菜单对象,将其添加到JMenuBar菜单栏中
	创建JMenuItem菜单项,为菜单项添加事件监听器
	当点击菜单项会弹出一个模态的JDialog窗口,将菜单项添加到JMenu菜单中。
 */

public class JMenuText {
	public static void main(String[] args) {
		//1、创建一个名为 JMenuText的窗体
		JFrame f = new JFrame("JMenuText");	
		
		//2、创建菜单栏组件JMenuBar 
		JMenuBar menuBar = new JMenuBar();
		//创建菜单组件JMenu
		JMenu menu = new JMenu("文件");      //创建文件菜单
		JMenu menu1 = new JMenu("编辑");      //创建编辑菜单
		JMenu menu2 = new JMenu("查看");      //创建查看菜单
	    // 将菜单添加到菜单栏上
		menuBar.add(menu);                    
		menuBar.add(menu1);                
		menuBar.add(menu2);                               
			
		//创建两个JMenuItem菜单项
		JMenuItem item1 = new JMenuItem("新建");
		JMenuItem item2 = new JMenuItem("退出");
		//JMenuItem菜单项添加到menu菜单组件
		menu.add(item1);
		menu.addSeparator();//设置分隔符
		menu.add(item2);
		

		//分别为两个JMenuItem菜单项创建监听器
		item1.addActionListener(new ActionListener() {//新建监听器
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				// 创建一个JDialog窗口 (true模式,false非模式)
				JDialog dialog = new JDialog(f,"新建文件",true);
				dialog.setSize(200, 200);  //设置窗体大小
				dialog.setLocation(50, 50);//设置窗体显示位置
				dialog.setVisible(true);//窗体可见
				//DISPOSE_ON_CLOSE:当窗口关闭时,隐藏并处理这个窗口(只有当它是最后一个窗口,才会退出JVM)
				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
				
			}
			
		});
		
		item2.addActionListener(new ActionListener() {//退出监听器
			public void actionPerformed(ActionEvent e) {
				System.exit(0);//正常退出程序(关闭当前正在运行的java虚拟机)
			}
		});

		//3、向JFrame窗口容器中加入JMenuBar组件
		f.setJMenuBar(menuBar);
				
		f.setSize(400, 350); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序	
	}
}

效果展示:

5.6.2 JPopupMenu(弹出式菜单) 

        弹出式菜单用JPopupMenu表示 JPopupMenu弹出式菜单和下拉式菜单一样都通过调用add()方法添加JMenuItem菜单项,但它默认是不可见的,如果想要显示出来,则必须调用它的show(Component invoker,int x,int y)方法,invoker表示JPopupMenu菜单显示位置的参考方式,x和y表示invoker组件坐标空间中的一个坐标,显示的是JPopupMenu菜单的左上角坐标。

代码展示:

package javaSE.GUI;

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

/*
 使用JFrame顶级容器
 	popupMenu设置弹出式菜单(这里注册监听,鼠标单击右键显示)
 	该菜单添加三个JMenuItem菜单项
	
 */
public class JPopupMenuTest {
	public static void main(String[] args) {
		//1、创建一个名为 JPopupMenuTest的窗体
		JFrame f = new JFrame("JPopupMenuTest");	
				
		//2、创建菜JPopupMenu弹出式菜单 
		JPopupMenu popupMenu = new JPopupMenu();                             
					
		// 创建三个JMenuItem菜单项
	 	JMenuItem refreshItem = new JMenuItem("查看");
	 	JMenuItem createItem = new JMenuItem("新建");
	 	JMenuItem exitItem = new JMenuItem("退出");
	 			
		//JMenuItem菜单项添加到menu菜单组件
	 	popupMenu.add(refreshItem);
	 	popupMenu.addSeparator();//设置分隔符
	 	popupMenu.add(createItem);
	 	popupMenu.addSeparator();//设置分隔符
	 	popupMenu.add(exitItem);

		//3、为JFrame窗口添加鼠标事件监听器
	 	f.addMouseListener(new MouseAdapter() {
	 		public void mouseClicked(MouseEvent e) {
	 			// 如果点击的是鼠标的右键,显示JPopupMenu菜单
	 			if (e.getButton() == MouseEvent.BUTTON3) {
	 				popupMenu.show(e.getComponent(), e.getX(), e.getY());
	 			}
	 		}
	 	});
	 			
	 	createItem.addActionListener(new ActionListener() {//新建监听器
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				// 创建一个JDialog窗口 (true模式,false非模式)
				JDialog dialog = new JDialog(f,"新建文件",true);
				dialog.setSize(200, 200);  //设置窗体大小
				dialog.setLocation(50, 50);//设置窗体显示位置
				dialog.setVisible(true);//窗体可见
				//DISPOSE_ON_CLOSE:当窗口关闭时,隐藏并处理这个窗口(只有当它是最后一个窗口,才会退出JVM)
				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
						
			}
					
		});
				
		exitItem.addActionListener(new ActionListener() {//退出监听器
			public void actionPerformed(ActionEvent e) {
				System.exit(0);//正常退出程序(关闭当前正在运行的java虚拟机)
			}
		});

						
		f.setSize(400, 250); 	//设置窗体大小
		f.setLocation(300, 200);//设置窗体显示位置
		f.setVisible(true);		//窗体可见
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,退出应用程序	
	}

}

效果展示:

                                点击右键弹出菜单项

结尾:

GUI - 图形用户接口相关知识远不止于此,如果您感兴趣的话,就继续向前探索吧!

文章还有许多不足之处,还请大家多多指正。

有则改之,无则加勉。

获取编程软件和资源 下载链接:

java初学者的装备(软件、学习路线、资源)_小白要努力变黑的博客-CSDN博客

Guess you like

Origin blog.csdn.net/m0_51315555/article/details/123761623