Home  >  Article  >  Java  >  Explanation of GUI programming in Java (Part 2)

Explanation of GUI programming in Java (Part 2)

巴扎黑
巴扎黑Original
2017-07-23 13:47:332284browse

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!

Statement:
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