Explanation of GUI programming in Java (Part 2)
1. Event listening mechanism
-- Event source: those graphical interface components in the awt or swing package, that is, the component where the event occurs
-- Event :Event An operation performed by the user on the component
--Listener:Listener The method responsible for processing the event
2. Classes under the java.awt.event package
WindowEvent //Window events, such as the user clicking on a half-closed window, the window gaining or losing focus, maximizing or minimizing, etc.
MouseEvent //Mouse events, mouse pressed, mouse released, click ( Press and then release) etc.
ActionEvent //Action event, it does not represent a specific action, but a semantics, such as a button or menu being clicked, pressing Enter in the text box Wait, it can be understood like this: a certain action of the user causes the basic function of a certain component to occur, which is the ActionEvent event
Different event types correspond to different event listener interfaces, and the name of the interface Corresponds to the name of the event.
WindowEvent - >WindowListener
MouseEvent ->MouseListener
ActionEvent ->ActionListener
Code example:
import java.awt.Frame;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;public class Test20 {public static void main(String[] args) { Frame f = new Frame(); f.setSize(400, 400); f.setVisible(true); f.addWindowListener(new WindowListener() { @Overridepublic void windowOpened(WindowEvent e) { // 窗口被打开// TODO Auto-generated method stub} @Overridepublic void windowClosing(WindowEvent e) { // 设置关闭事件// TODO Auto-generated method stubSystem.exit(0); } @Overridepublic void windowClosed(WindowEvent e) { // 用户已经关闭窗口// TODO Auto-generated method stub} @Overridepublic void windowIconified(WindowEvent e) { // 被最小化的时候// TODO Auto-generated method stub} @Overridepublic void windowDeiconified(WindowEvent e) { // 最小化被还原的时候// TODO Auto-generated method stub} @Overridepublic void windowActivated(WindowEvent e) { // 窗体被激活// TODO Auto-generated method stub} @Overridepublic void windowDeactivated(WindowEvent e) { // 失去焦点的时候// TODO Auto-generated method stub} }); } }
Have you noticed that when using the WindowListener interface, a lot of uncommon code will be introduced (here we just want to set it off). The methods in the excuse can only be overwritten and cannot be deleted. That's it. The whole project seems very long-winded. In order to solve this problem, there is an event adapter.
3. Event Adapter
JDK defines corresponding implementation classes for most event listener interface classes (there are many empty implementation methods in it to facilitate us to create listeners listener object), which we call the event adapter class. Here I used WindowAdapter.
import java.awt.Frame;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class Test21 {public static void main(String[] args) { Frame f = new Frame("事件适配器的栗子"); f.setSize(400, 400); f.setVisible(true); f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
You can look at the source code of the WindowAdapter class and get a feel for it.
public abstract class WindowAdapterimplements WindowListener, WindowStateListener, WindowFocusListener {/** * Invoked when a window has been opened. */public void windowOpened(WindowEvent e) {}/** * Invoked when a window is in the process of being closed. * The close operation can be overridden at this point. */public void windowClosing(WindowEvent e) {}/** * Invoked when a window has been closed. */public void windowClosed(WindowEvent e) {}/** * Invoked when a window is iconified. */public void windowIconified(WindowEvent e) {}/** * Invoked when a window is de-iconified. */public void windowDeiconified(WindowEvent e) {}/** * Invoked when a window is activated. */public void windowActivated(WindowEvent e) {}/** * Invoked when a window is de-activated. */public void windowDeactivated(WindowEvent e) {}/** * Invoked when a window state is changed. * @since 1.4 */public void windowStateChanged(WindowEvent e) {}/** * Invoked when the Window is set to be the focused Window, which means * that the Window, or one of its subcomponents, will receive keyboard * events. * * @since 1.4 */public void windowGainedFocus(WindowEvent e) {}/** * Invoked when the Window is no longer the focused Window, which means * that keyboard events will no longer be delivered to the Window or any of * its subcomponents. * * @since 1.4 */public void windowLostFocus(WindowEvent e) {} }
Let’s practice some examples of event handlers.
Example 1:
import java.awt.Button;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;//例一:在窗体中放置一个按纽,点击后让程序退出class TestFrame implements ActionListener { // ActionListener接口里面只有一个方法,下面会重写private Frame f;public TestFrame() { f = new Frame("窗口"); init(); }private void init() { f.setSize(300, 300); f.setLayout(new FlowLayout());// 布局模式Button b = new Button("退出程序"); b.addActionListener(this); f.add(b); f.setVisible(true); } @Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubf.setVisible(false); f.dispose();// 在关闭的时候,可以用它来销毁窗体资源System.exit(0);// 退出 } }public class Test22 {public static void main(String[] args) {new TestFrame(); } }
As above, click the exit program button to exit. Click the X in the upper right corner, is that correct? You can exit. Because there is no WindowListener set.
This example uses the ActionListener interface. You can take a look at its source code, as follows:
public interface ActionListener extends EventListener {/** * Invoked when an action occurs. */public void actionPerformed(ActionEvent e); }
Example 2:
TextField txtNo;= Frame("请输入密码"f.setBounds(50, 50, 400, 400);f.setLayout( FlowLayout());= TextField(10); code = (!(code >= KeyEvent.VK_0 && code <= KeyEvent.VK_9)) {System.out.println(KeyEvent.getKeyText(code) + "输入有误" 0
Test class:
public class Test23 {public static void main(String[] args) {new TestFrame(); } }
Example 3:
List the contents of the specified directory:
import java.awt.Button;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.File;public class Test24 {public static void main(String[] args) {new MyWindow(); } }class MyWindow { MyWindow() { init(); }private Frame f;private Button b;private TextField txtDir;// 用来输入目录名称private TextArea txtFileList;// 用来显示文件列表private void init() { f = new Frame("窗口"); f.setBounds(44, 44, 500, 500); f.setLayout(new FlowLayout()); txtDir = new TextField(8); b = new Button("显示"); txtFileList = new TextArea(20, 30);// 用来显示文件列表的区域f.add(txtDir); f.add(b); f.add(txtFileList); initEvent(); f.setVisible(true); }private void initEvent() {// TODO Auto-generated method stubf.addWindowListener(new WindowAdapter() {/** * Invoked when a window is in the process of being closed. The * close operation can be overridden at this point. */public void windowClosing(WindowEvent e) { System.exit(0); } }); b.addActionListener(new ActionListener() {/** * Invoked when an action occurs. */public void actionPerformed(ActionEvent e) { txtFileList.setText(""); String dirStr = txtDir.getText();// 取出用户输入的路径File file = new File(dirStr);if (file.isDirectory() && file.exists()) { String[] fileNameList = file.list();for (String s : fileNameList) { txtFileList.append(s + "\r\n");// 别忘了换行符 } } else { txtFileList.append("输入有误,请重新输入"); } } }); } }
Result: (I asked it to display the directory of my D drive)
The above is the detailed content of Explanation of GUI programming in Java (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
