>  기사  >  Java  >  Java의 이벤트 처리

Java의 이벤트 처리

PHPz
PHPz원래의
2024-08-30 16:15:191126검색

기존 객체 상태의 모든 변경은 이벤트로 호출되고, 이벤트 핸들러는 특정 이벤트를 수신하고 이에 따라 일부 논리적 작업을 수행하도록 설계되며, AWT 구성 요소는 사용자 이벤트를 수신하는 필수 리스너에 등록될 수 있으며 그런 다음 그에 따라 이벤트를 처리합니다. 이번 주제에서는 Java의 이벤트 핸들링에 대해 알아보겠습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

다음은 AWT 이벤트 핸들러가 사용되는 방식에 대한 구문입니다.

// importing awt package
import java.awt.*;
// create a class extending Frame component
class <className> extends Frame implements <ListenerInterface>{
// override methods of implemented interface
@Override
public void <methodName>(){
// do required actions on event happened
}
<className>(){
component.addActionListerner(listenerClassobject);  // register component with listener
}}

위 구문은 Java awt에서 리스너를 사용하는 방법을 보여줍니다.

위 구문에서 Java 클래스의 이름을 나타냅니다. <리스너 인터페이스> 사용할 리스너의 이름일 수 있습니다. 이벤트에 컴포넌트를 등록하려면 위에 표시된 메소드를 사용하여 리스너에 컴포넌트를 등록해야 합니다.

Java의 이벤트 처리

다음은 Java awt에서 사용할 수 있는 다양한 유형의 리스너입니다.

Event ListenerInterface Description
ActionEvent ActionListener Produced on click of a button, selection of an item from menu or other.
MouseEvent MouseListener Produced when mouse event takes place like moved, pressed, click, double-click or enter/exit of mouse pointer into a specified area.
KeyEvent KeyListener Produced on the press of the key.
ItemEvent ItemListener Produced when the checkbox is checked or unchecked or item present in a list is clicked.
WindowEvent WindowListener Produced on different operations performed on a window.
ComponentEvent ComponnetEventListener Produced when a component is made visible, hidden, moved or changes are made in component size.
ContainerEvent ContainerListener Produced when a component is inserted or deleted from a container.
FocusEvent FocusListener Produced when a component attains or loses keyboard focus.
AdjustmentEvent AdjustmentListener Produced when changes are made to using the scrollbar.
MouseWheelEvent MouseWheelListener Produced when the mouse wheel is rotated.
TextEvent TextListener Produced whenever there is a change in the value of textarea or textfield.

다음은 Java awt에서 이벤트 처리와 관련된 주요 단계입니다.

  • 필요한 인터페이스를 구현하고 해당 메서드를 재정의합니다.
  • 리스너에 구성요소를 등록합니다.

Java에서의 이벤트 처리 예

다음 예에서는 Java awt에서 이벤트 핸들러를 사용하는 방법을 보여줍니다.

코드:

package com.edubca.awtdemo;
// importing important packages
import java.awt.*;
import java.awt.event.*;
public class EventHandlerDemo {
private Frame parentFrame;
private Label headerTitle;
private Label status;
private Panel panel;
public EventHandlerDemo(){
prepareInterface();
}
public static void main(String[] args){
EventHandlerDemo  awtdemo = new EventHandlerDemo();
awtdemo.showEventHandlingDemo();
}
private void prepareInterface(){
parentFrame = new Frame("Java Event Handling Example");
parentFrame.setSize(400,400);
parentFrame.setLayout(new GridLayout(3, 1));
parentFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerTitle = new Label();
headerTitle.setAlignment(Label.CENTER);
status = new Label();
status.setAlignment(Label.CENTER);
status.setSize(350,100);
panel = new Panel();
panel.setLayout(new FlowLayout());
parentFrame.add(headerTitle);
parentFrame.add(panel);
parentFrame.add(status);
parentFrame.setVisible(true);
}
private void showEventHandlingDemo(){
headerTitle.setText("Handling Button Click Event");
Button firstButton = new Button("First Button");
Button secondButton = new Button("Second Button");
Button thirdButton = new Button("Third Button");
firstButton.setActionCommand("First Button Clicked");
secondButton.setActionCommand("Second Button Clicked");
thirdButton.setActionCommand("Third Button Clicked");
//registering button with listener
firstButton.addActionListener(new ButtonClickEventListener());
//registering button with listener
secondButton.addActionListener(new ButtonClickEventListener());
//registering button with listener
thirdButton.addActionListener(new ButtonClickEventListener());
panel.add(firstButton);
panel.add(secondButton);
panel.add(thirdButton);
parentFrame.setVisible(true);
}
// inner class implementing Action Listener
private class ButtonClickEventListener implements ActionListener{
// overriding method
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
// do different actions according to different commands
if( command.equals( "First Button Clicked" ))  {
status.setText ("First Button Clicked.");
}
else if( command.equals( "Second Button Clicked" ) )  {
status.setText ("Second Button Clicked.");
}
else  {
status.setText ("Third Button Clicked.");
}
}
}
}

위 프로그램은 Java에서 awt 이벤트 핸들러를 사용하는 방법을 보여줍니다. 여기에는 필요한 리스너 인터페이스를 구현하고 해당 메소드를 구현한 후 지정된 리스너에 구성 요소를 등록하는 작업이 포함됩니다.

위의 예에는 3개의 버튼이 있고 버튼을 한 번 클릭하면 바닥글의 라벨이 변경됩니다. 위 프로그램이 실행되면 다음 창이 나타납니다.

Java의 이벤트 처리

첫 번째 버튼을 클릭하면 아래 텍스트가 생성됩니다.

Java의 이벤트 처리

두 번째 버튼을 클릭하면 다음과 같은 출력이 생성됩니다.

Java의 이벤트 처리

세 번째 버튼을 클릭하면 다음과 같은 출력이 생성됩니다.

Java의 이벤트 처리

따라서 다양한 버튼의 클릭 이벤트가 리스너에 의해 감지되고 그에 따라 다양한 기능이 수행되는 것을 볼 수 있습니다.

결론

위 기사는 Java awt의 이벤트 핸들러에 대한 명확한 이해를 제공합니다.

위 내용은 Java의 이벤트 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.