Home  >  Article  >  Java  >  What is the JavaGUI event listening mechanism?

What is the JavaGUI event listening mechanism?

王林
王林forward
2023-05-10 20:10:141386browse

1. There are objects in an event model: event source, event and listener

2. Event listening mechanism:

  • Event source Where the event occurs

  • Event What is going to happen

  • Event processing The solution for what happened

  • Event monitoring Associate the event source with the event

What is the JavaGUI event listening mechanism?

##Usage steps:

  • Create a new component (such as JButton)

  • Add the component to the corresponding panel (such as JFrame)

  • Register a listener to listen for events generated by the event source (For example, using ActionListener to respond to the user clicking a button)

  • Define the method for handling events (such as defining the corresponding method in actionPerformed in ActionListener)

Example 1:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class AddActionListener {
    public static void main(String[] args) {
        JFrame jf = new JFrame("AddActionListener");
        jf.setLayout(new FlowLayout(FlowLayout.LEFT));
        jf.setBounds(400, 300, 400, 300);
        JTextArea area=new JTextArea(20,10);
        area.setLineWrap(true);
        JButton jb=new JButton("秃头");
        jb.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                area.setText("不要熬夜!");
            }
        });
        jf.add(area);
        jf.add(jb);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

What is the JavaGUI event listening mechanism?##Example 2:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class AddActionListener {
    public static void main(String[] args) {
        JFrame jf = new JFrame("AddActionListener");
        jf.setLayout(new FlowLayout(FlowLayout.LEFT));
        jf.setBounds(400, 300, 400, 300);
        JTextArea area=new JTextArea(20,10);
        area.setLineWrap(true);
        JButton jb=new JButton("秃头");
        jb.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                area.append("不要熬夜!");
            }
        });
        jf.add(area);
        jf.add(jb);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

What is the JavaGUI event listening mechanism?

tips: ActionEvent

is a Class, e is an instance of that class. You can replace e with whatever you like, for example. eventor object

The above is the detailed content of What is the JavaGUI event listening mechanism?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete