国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase Detailed explanation of events in java with pictures and texts

Detailed explanation of events in java with pictures and texts

Nov 28, 2019 pm 05:35 PM
java

Detailed explanation of events in java with pictures and texts

Before learning java events, you must have a certain understanding of java internal classes, common java components, containers, layout managers, and java abstract window toolkit. Combined with the following knowledge points, You can do some simple window programs. (Recommended: java video tutorial)

The Java language uses the authorization event model to process events. Under this model, each component has corresponding events, such as a click event for a button, a content change event for a text field, etc.

When an event is triggered, the component will send the event to each event listener registered by the component. The event listener defines the processing of events corresponding to different events. At this time, the event listener The processor will call different event handlers based on different event information to complete the processing of this event. The event information will be received only after the event listener is triggered.

The salient feature of this model is that when the component is triggered, it does not process it itself, but leaves the processing operation to a third party to complete. For example, when a button is clicked in the GUI, the button is an event source object. The button itself has no right to react to this click. What it does is send information to its registered listener (event processing (or, in essence, it is also a class) to handle.

To understand Java's event processing, you must understand the following three important summaries.

(1), Event - event generated by user operation

(2), Event source Event source - component that generates event

(3), Event handling method Event handle - method of handling events

1. Basic principles of event processing

When an event is triggered on a button, the virtual machine generates a click The event object is then searched for the registered related processing method on the button, that is, the event source, and the event object is passed to this method, and this method is executed.

Sample program:

In the following program, JButton jb is the event source, ClickAction is the event handler, jb.addActionListener(a); associates the event source with the event handler. When a click event occurs on the event source, the code defined in ClickAction is executed.

The source code is as follows:

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

import javax.swing.JButton;
import javax.swing.JFrame;

public class EventTest {

    public static void main(String[] args) {

        JFrame j = new JFrame("示例程序1");
        //1、事件源jb按鈕就是事件源,因?yàn)橐c(diǎn)擊它
        JButton jb = new JButton("click");
        //2、事件處理程序ClickAction表示事件處理程序
        ClickAction a = new ClickAction();
        //3、關(guān)聯(lián),將事件源和事件處理程序a關(guān)聯(lián)起來,意思是發(fā)生點(diǎn)擊執(zhí)行a
        jb.addActionListener(a);
        //將jb源事件添加到窗口中。
        j.getContentPane().add(jb);
        j.pack();
        j.setVisible(true);
    }
}

//事件處理程序,點(diǎn)擊就是一個(gè)Action事件
class ClickAction implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        System.out.println("hello");
    }
}

2. Event object

In your example above, ActionEvent is an event object. This event is generated by JButton when the JButton is pressed. The event is passed to the ActionListener object registered by registering the listener, through which the most common information such as the time when the event occurs and the event source when the event occurs can be obtained.

Common methods of ActionEvent are as follows:

(1)String getActionCommand(): Returns the command string related to this type of action. The default component is title.

(2)int getModifiers(): Returns the keyboard button pressed simultaneously when this action occurs

(3)long getWhen(): Returns the long form of the event when this event occurs.

Sample program:
The source code is as follows:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class EventTest2 {

    public static void main(String[] args) {

        JFrame j = new JFrame("示例程序2");
        JPanel jp = new JPanel();
        JLabel j1 = new JLabel("請點(diǎn)擊");
        JButton jb = new JButton("click");
        JButton jb1 = new JButton("click");
        ClickAction2 a = new ClickAction2();
        jb1.addActionListener(a);//如果jb1上發(fā)生了Action事件就執(zhí)行a里面的代碼
        jb.addActionListener(a);
        jp.add(j1);
        jp.add(jb);
        jp.add(jb1);
        j.add(jp);
        j.setSize(400, 200);
        j.setVisible(true);

    }

}

class ClickAction2 implements ActionListener{

    //事件發(fā)生時(shí),actionPerformed方法會(huì)被虛擬機(jī)調(diào)用,事件對象回傳給該方法
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
         long d = e.getWhen();//事件發(fā)生的事件
         Date date = new Date(d);//轉(zhuǎn)化為相應(yīng)的時(shí)間
         System.out.println(date);
         JButton sou = (JButton)e.getSource();//發(fā)生的事件源
         sou.setText("點(diǎn)不著");//將點(diǎn)擊發(fā)生的按鈕的按鈕設(shè)為點(diǎn)不著
         //如果沒有設(shè)置過ActionCommand,默認(rèn)得到的是按鈕的標(biāo)題
         String com = e.getActionCommand();
         System.out.println("command is: " +com);
    }

}

3. Event type

There are many events in graphical interface development. These events With EventObject as the top level and class, a tree structure is formed according to the type of event.

See the figure below for details:

Detailed explanation of events in java with pictures and texts

EventObject is the parent class of all event classes, and it contains two methods:

(1), Object getSource(): The object where the Event originally occurred

(2), String toString(): Returns the String representation of this EventObject.

Through getSource(): You can know which object the event occurred on.

Regarding the meaning of other event classes, source code explanations and simple drills for several classes will be given below.

MouseEvent Class

When a component is pressed, released, clicked, moved or dragged, a mouse event is triggered.

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class MouseListenerTest {
    public static void main(String[] args) {
        JFrame j = new JFrame("我的窗口");
        MouL w = new MouL();
        j.addMouseListener(w);
        j.setSize(100, 100);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class MouL implements MouseListener{

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("鼠標(biāo)的位置: " + e.getX() + "," + e.getY());
        System.out.println("點(diǎn)擊發(fā)生了");
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("按下");
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("松開");
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("鼠標(biāo)進(jìn)入了窗口");
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("鼠標(biāo)離開了窗口");
    }
}

WindowEvent Class

Window events will be triggered when the window is opened, closed, maximized, or minimized

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class WindowsListenerTest {

    public static void main(String[] args) {

        JFrame j = new JFrame("我的窗口");
        WindowL w = new WindowL();
        j.addWindowListener(w);
        j.setSize(100, 100);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class WindowL implements WindowListener{

    @Override
    public void windowOpened(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口打開時(shí)我執(zhí)行windowOpened");
    }

    @Override
    public void windowClosing(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("windowClosing");
    }

    @Override
    public void windowClosed(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口關(guān)閉時(shí)我執(zhí)行windowClosed");
    }

    @Override
    public void windowIconified(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口最小化時(shí)我執(zhí)行windowIconified");
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口回復(fù)時(shí)我執(zhí)行windowDeiconified");
    }

    @Override
    public void windowActivated(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口變成活動(dòng)狀態(tài)時(shí)我執(zhí)行mouseClicked");
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口變成不活動(dòng)狀態(tài)時(shí)我執(zhí)行windowDeactivated");
    }

}

ContainerEvent Class

When Events are triggered when a component is added to a container or when a component is removed from a container.

import java.awt.event.ContainerListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ContainerEvent {

    public static void main(String[] args) {

        JFrame j = new JFrame("我的窗口");
        ContL w = new ContL();
        JPanel jp = new JPanel();

        jp.addContainerListener(w);

        JButton del = new JButton("刪除");
        JButton add = new JButton("add");

        jp.add(add);
        jp.add(del);//觸發(fā)組件添加了

        jp.remove(del);//觸發(fā)組件刪除了

        j.getContentPane().add(jp);
        j.setSize(100, 100);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

class ContL implements ContainerListener{

    @Override
    public void componentAdded(java.awt.event.ContainerEvent e) {
        // TODO Auto-generated method stub
        System.out.println("組件添加了");
    }

    @Override
    public void componentRemoved(java.awt.event.ContainerEvent e) {
        // TODO Auto-generated method stub
        System.out.println("組件刪除了");
    }

}

FocusEvent

Mouse clicks and other operations will cause a component to gain or lose focus. When a component gets focus, or loses focus, the focus event will be triggered

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FocusTest {

    public static void main(String[] args) {

        JFrame j = new JFrame("key test");
        JPanel jp = new JPanel();
        JButton j1 = new JButton("1");
        JButton j2 = new JButton("2");
        j1.addFocusListener(new FocusL());
        j2.addFocusListener(new FocusL());
        jp.add(j1);
        jp.add(j2);
        j.add(jp);
        j.setSize(600, 500);
        j.setVisible(true);
    }

}

class FocusL implements FocusListener{

    @Override
    public void focusGained(FocusEvent e) {
        //得到FocusEvent發(fā)生時(shí)的對象,轉(zhuǎn)化為按鈕
        // TODO Auto-generated method stub
        JButton j = (JButton)e.getSource();
        //得到按鈕的標(biāo)題
        String title = j.getText();
        System.out.println("focusGained:按鈕" + title + "獲得焦點(diǎn)");
    }

    @Override
    public void focusLost(FocusEvent e) {
        // TODO Auto-generated method stub
        JButton j = (JButton)e.getSource();
        String title = j.getText();
        System.out.println("focusLost:按鈕" + title + "失去焦點(diǎn)");
    }

}

4. Multiple listeners

Generally, the event source can Many different types of events are generated, so many different types of listeners can be registered (triggered).

Multiple listeners can be registered on an event source component, and a listener can be registered on multiple different event sources.

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class MultiListenerTest {

    public static void main(String[] args) {

        JFrame a = new JFrame("事件處理");
        JTextField jf = new JTextField();
        a.add(jf, "South");
        MouseM m = new MouseM();

        //同一事件源上注冊兩個(gè)事件監(jiān)聽程序
        //鼠標(biāo)的監(jiān)聽程序如點(diǎn)擊等
        a.addMouseListener(m);

        //鼠標(biāo)移動(dòng)的監(jiān)聽程序
        a.addMouseMotionListener(m);

        a.setSize(200, 200);
        a.setVisible(true);
    }

}

class MouseM implements MouseMotionListener, MouseListener{

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("clicked" + "x:" + e.getX() + ",y:" + e.getY());
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mousePressed");
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mouseRelsased");
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mouseEntered");
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mouseExited");
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("拖動(dòng):" + e.getPoint());
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("移動(dòng):" + e.getPoint());
    }

}

5. Event Adapter

To simplify programming, JDK defines corresponding implementation classes for most event listener interfaces - event adapter classes , in the adapter, implements all the methods in the corresponding listener interface, but does nothing.

So the defined listener class can inherit the event adapter class and only override the required methods.

There are the following adapters:

- ComponentAdapter (component adapter)

- ContainerAdapter (容器適配器)

- FocusAdapter (焦點(diǎn)適配器)

- KeyAdapter (鍵盤適配器)

- MouseAdapter (鼠標(biāo)適配器)

- MouseMotionAdapter (鼠標(biāo)運(yùn)動(dòng)適配器)

- WindowAdapter (窗口適配器)

鼠標(biāo)適配器示例程序:MouseListener中由多個(gè)方法,但在這里只實(shí)現(xiàn)了mouseClicked()

package 圖形界面設(shè)計(jì);

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;

public class AdapterTest {

    public static void main(String[] args) {

        JFrame z = new JFrame("事件適配器測試");
        z.setSize(500, 400);

        MouseLS a = new MouseLS();

        //注冊z上的鼠標(biāo)事件處理程序,發(fā)生點(diǎn)擊等事件執(zhí)行a里的代碼
        z.addMouseListener(a);
        z.setVisible(true);
        z.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class MouseLS extends MouseAdapter{

    public void mouseClicked(MouseEvent e){

        // 打印出鼠標(biāo)點(diǎn)擊時(shí)的x點(diǎn)和y點(diǎn)的坐標(biāo)
        System.out.println("鼠標(biāo)點(diǎn)擊了:" + e.getX() + "," + e.getY());
    }

}

更多java知識(shí)請關(guān)注java基礎(chǔ)教程欄目。

The above is the detailed content of Detailed explanation of events in java with pictures and texts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles