반응형

onabort
이미지의 다운로드를 중지할  (브라우저의 중지버튼)
onactivate
개체가 활성활   발생
(
태그의 기능이 작용할  발생하는 이벤트로 예를 들어 링크를 누를 경우 링크가 옮겨질때 발생하는 것을 감지하는 이벤트 핸들러)
onafterprint
문서가 출력되거나 혹은 출력하기 위해 출력 미리보기를 한후에 발생
onafterupdate
데이터영역 개체에서 발생하는 이벤트로 데이터 소스 오브젝트내의 데이터가  업데이트 되었을  발생(데이터 개체부분 참조)
onbeforeactivate
개체가 활성화 상태로 되기 바로 직전에 발생 (onactivate 참고)
onbeforecopy
선택 영역이 시스템의 클립보드로 복사되기 바로 직전에 발생
onbeforecut
선택 영역이 지워지기 바로 직전에 발생
onbeforedeactivate
 문서에서 현재 개체에서 다른 개체로 activeElement 바뀔 때 발생 (activeElement 개체를 지칭하는 예약어로도 쓰임)
onbeforeeditfocus
편집가능한 개체 내부에 포함된 개체가 편집활성화  상태가 되거나 혹은 편집가능한 개체가 제어를 위해 선택될때 
onbeforepaste
시스템의 클립보드에서 문서로 붙여넣기 될때 대상 개체에서 발생
onbeforeprint
문서가 출력되거나 혹은 출력하기 위해 출력미리보기 직전에 발생
onbeforeunload
페이지가 언로드되기 직전에 발생
onbeforeupdate
데이터영역 개체에서 발생하는 이벤트로 데이터 소스 오브젝트내의 데이터가  업데이트 되기전에 발생(데이터 개체부분 참조)
onblur
개체가 포커스를 잃었을 
onbounce
마퀴태그에서 alernate상태에서 스크롤이  사이드에서 바운드 될때 발생
oncellchange
데이터제공 개체에서 데이터가 변화할때 발생
onchange
개체 혹은 선택영역의 내용이 바뀔  발생
onclick
개체위에서 마우스의 왼쪽 버튼을 누를때 발생
oncontextmenu 
클라이언트 영역에서 사용자가 마우스 오른쪽 버튼을 눌러 콘텍스트 메뉴를 열 때 발생
oncontrolselect
사용자가 개체의 제어 영역을 만들때 발생
oncopy

시스템의 클립보드에 선택영역 혹은 개체를 복사할  소스 개체로부터 발생
oncut
시스템의 클립보드에 선택영역 혹은 개체를 잘라낼때 소스 개체로부터 발생
ondataavailable
비정기적으로 데이터를 전달하는 데이터 소스 개체로부터 데이터가 도착할  마다 정기적으로 발생
ondatasetchanged
데이터 소스개체의 변화에 의해 데이터가 노출된 상태로 될때 발생
ondatasetcomplete
데이터 소스 개체로부터 모든 데이터가 유용한 상태로 표시될때 발생
ondblclick
사용자가 개체에 더블클릭 할때 발생
ondeactivate
 문서에서 현재 개체에서 다른 개체로 activeElement 변할 때 발생
ondrag
드래그 상태가 지속되는 동안 소스 객체로 부터 발생
ondragend
드래그 상태가 끝날때 소스 객체로 부터 발생
ondragenter
사용자가 개체를 드래그 하여 드롭가능 위치로 지정된 영역으로 이동할때 타겟 개체에서 발생
ondragleave
사용자가 개체를 드래그 하여 드롭가능 위치로 지정된 영역을 떠날때 타겟 개체에서 발생
ondragover
사용자가 개체를 드래그 하여 드롭가능 위치로 지정된 영역내에서 드래그할  계속적으로 타겟 개체에서 발생
ondragstart
선택된 개체 혹은 텍스트 영역에서 사용자가 드래그를 시작할  발생
ondrop
드래그앤드롭 작용에서 상태가 진행되는 동안 개체가 타겟 개체에 드롭되었을  타겟 개체에서 발생
onerror
개체가 로드되는 동안 발생하는 이벤트
onerrorupdate
데이터 소스 개체 내에 데이터가 없데이트 되는 동안 에러가 발생할  데이터 영역 개체에서 발생 
onfilterchange
비주얼 필터의 상태가 바뀌거나 트랜지션이 완료되었을  발생
onfinish
마퀴개체의 loop 완료되었을  발생
onfocus
개체가 포커스를 받았을  발생
onfocusin
개체에 포커스가 셋팅되기 바로 직전 개체에 대해 발생
onfocusout
포커스가 다른 개체로 이동한 후에 포커스를 가고 있는 현재 개체에서 발생
onhelp
브라우저가 활성화 되어 있는 동안 F1키를 눌렀을  
onkeydown
사용자가 키를 눌렀을  
onkeypress
기능키를 제외한 키를 눌렀을  발생
onkeyup
사용자가 키를 놓았을  발생
onlayoutcomplete
소스 문서로 부터 콘텐드를 가지는 객체가 미리보기나 출력을 할때 현재 LayoutRect개체를 모두 채우는 것이 끝났을  발생
onload
브라우저가 개체를 로드한 후에 발생
onlosecapture
개체가 마우스 캡쳐를 잃었을  발생
onmousedown
개체 위에 마우스 버튼을 누를 때 발생(좌우 어느 버튼이든)
onmouseenter
개체 안으로 마우스 포인터가 들어올 때 발생
onmouseleave
개체의 경계 밖으로 마우스 포인터가 이동할  발생
onmousemove
개체 위에서 마우스가 움직일 때 발생
onmouseout
개체 밖으로 마우스 포인터가 빠져나갈  발생
onmouseover
개체위로 마우스 포인터가 들어올 때 발생
onmouseup
마우스가 개체 위에 있는 동안 마우스를 누른상태에서 해제될때 발생
onmousewheel
마우스 휠이 돌아갈 때 발생
onmove
개체가 움직일  발생
onmoveend
개체가 움직임이 끝날  발생
onmovestart
개체가 움직이기 시작할  발생
onpaste
문서에 클립보드로 부터 데이터가 전송될때 타겟 개체에서 발생
onpropertychange
개체의 속성이 바뀔 때 발생
onreadystatechange
개체의 상태가 변화할 때 발생
onreset
폼을 사용자가 리셋할 경우 발생
onresize
개체의 크기가 바뀔 때 발생
onresizeend
제어영역에서 개체의 크기가 사용자에 의해 변화가 끝날 때 발생
onresizestart
제어영역에서 개체의 크기가 사용자에 의해 변화되기 시작할 때 발생
onrowenter
데이터 소스 내에서 현재 열이 변화되거나 개체에 새로운 유용한 데이터가 입력될 때 발생
onrowexit
데이터 소스 콘트르롤이 개체내의 현재 열을  변화시킬  발생 
onrowsdelete
레코드셋에서 열이 삭제될 때 발생
onrowsinserted
현재 레코드셋에 새로운 열이 추가된 후에 발생(데이터 개체에서)
onscroll
사용자가 개체내이 스크롤 바를 스크롤 할 때 발생
onselect
현재 선택된 영역이 바뀔 때 발생
onselectionchange
문서의 선택 영역의 상태가 바뀔 때 발생
onselectstart
개체가 선택되기 시작할 때 발생
onstart
마퀴 개체에서  루프가 시작될 때 발생
onstop
사용자가 stop버튼을 눌렀을 경우 혹은 페이지를 떠날 때 발생
onsubmit
폼이 전송되기 바로 전에 발생
onunload
 

반응형

Java Swing Events

Events are an important part in any GUI program. All GUI applications are event-driven. An application reacts to different event types which are generated during it's life. Events are generated mainly by the user of an application. But they can be generated by other means as well. e.g. internet connection, window manager, timer. In the event model, there are three participants:

  • event source
  • event object
  • event listener

The Event source is the object whose state changes. It generates Events. The Event object (Event) encapsulates the state changes in the event source. The Event listener is the object that wants to be notified. Event source object delegates the task of handling an event to the event listener.

Event handling in Java Swing toolkit is very powerful and flexible. Java uses Event Delegation Model. We specify the objects that are to be notified when a specific event occurs.

An event object

When something happens in the application, an event object is created. For example, when we click on the button or select an item from list. There are several types of events. An ActionEvent, TextEvent, FocusEvent, ComponentEvent etc. Each of them is created under specific conditions.

Event object has information about an event, that has happened. In the next example, we will analyze an ActionEvent in more detail.

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

import java.text.DateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

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


public class EventObject extends JFrame {


    private JList list;
    private DefaultListModel model;

    public EventObject() {

        setTitle("Event Object");

        JPanel panel = new JPanel();
        panel.setLayout(null);

        model = new DefaultListModel();
        list = new JList(model);
        list.setBounds(150, 30, 220, 150);

        JButton ok = new JButton("Ok");
        ok.setBounds(30, 35, 80, 25);

        ok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(event.getWhen());
                Locale locale = Locale.getDefault();
                Date date = new Date();
                String s = DateFormat.getTimeInstance(DateFormat.SHORT,
                    locale).format(date);

                if ( !model.isEmpty() )
                    model.clear();

                if (event.getID() == ActionEvent.ACTION_PERFORMED)
                    model.addElement(" Event Id: ACTION_PERFORMED");

                model.addElement(" Time: " + s);

                String source = event.getSource().getClass().getName();
                model.addElement(" Source: " + source);

                int mod = event.getModifiers();

                StringBuffer buffer = new StringBuffer(" Modifiers: ");

                if ((mod & ActionEvent.ALT_MASK) > 0)
                    buffer.append("Alt ");

                if ((mod & ActionEvent.SHIFT_MASK) > 0)
                    buffer.append("Shift ");

                if ((mod & ActionEvent.META_MASK) > 0)
                    buffer.append("Meta ");

                if ((mod & ActionEvent.CTRL_MASK) > 0)
                    buffer.append("Ctrl ");

                model.addElement(buffer);
            }
        });

        panel.add(ok);
        panel.add(list);
        add(panel);

        setSize(420, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new EventObject();
    }
}

The code example shows a button and a list. If we click on the button, information about the event is displayed in the list. In our case, we are talking about an ActionEvent class. The data will be the time, when the event occured, the id of the event, the event source and the modifier keys.

 public void actionPerformed(ActionEvent event) {

Inside the action listener, we have an event parameter. It is the instance of the event, that has occured. In our case it is an ActionEvent.

 cal.setTimeInMillis(event.getWhen());

Here we get the time, when the event occured. The method returns time value in milliseconds. So we must format it appropriately.

 String source = event.getSource().getClass().getName();
 model.addElement(" Source: " + source);

Here we add the name of the source of the event to the list. In our case the source is a JButton.

 int mod = event.getModifiers();

We get the modifier keys. It is a bitwise-or of the modifier constants.

 if ((mod & ActionEvent.SHIFT_MASK) > 0)
     buffer.append("Shift ");

Here we determine, whether we have pressed a Shift key.


Event Object
Figure: Event Object

Implementation

There are several ways, how we can implement event handling in Java Swing toolkit.

  • Anonymous inner class
  • Inner class
  • Derived class

Anonymous inner class

We will illustrate these concepts on a simple event example.

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

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


public class SimpleEvent extends JFrame {


    public SimpleEvent() {

        setTitle("Simle Event");

        JPanel panel = new JPanel();
        panel.setLayout(null);

        JButton close = new JButton("Close");
        close.setBounds(40, 50, 80, 25);

        close.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }

        });

        panel.add(close);
        add(panel);

        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new SimpleEvent();
    }
}

In this example, we have a button that closes the window upon clicking.

 JButton close = new JButton("Close");

The button is the event source. It will generate events.

 close.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
         System.exit(0);
     }
 });

Here we register an action listener with the button. This way, the events are sent to the event target. The event target in our case is ActionListener class. In this code, we use an anonymous inner class.

Inner class

Here we implement the example using an inner ActionListener class.

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

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


public class InnerClass extends JFrame {

    public InnerClass() {

        setTitle("Using inner class");

        JPanel panel = new JPanel();
        panel.setLayout(null);

        JButton close = new JButton("Close");
        close.setBounds(40, 50, 80, 25);

        ButtonListener listener = new ButtonListener();
        close.addActionListener(listener); 

        panel.add(close);
        add(panel);

        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
      }

    public static void main(String[] args) {
        new InnerClass();
    }
}
 ButtonListener listener = new ButtonListener();
 close.addActionListener(listener); 

Here we have a non anonymous inner class.

 class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
 }

The button listener is defined here.

A derived class implementing the listener

The following example will derive a class from a component and implement an action listener inside the class.

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

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


public class UsingInterface extends JFrame {


    public UsingInterface() {

        setTitle("Using inner class");

        JPanel panel = new JPanel();
        panel.setLayout(null);

        MyButton close = new MyButton("Close");
        close.setBounds(40, 50, 80, 25);

        panel.add(close);
        add(panel);

        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    class MyButton extends JButton implements ActionListener {

        public MyButton(String text) {
            super.setText(text);
            addActionListener(this);
        }

        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }

    }

    public static void main(String[] args) {
        new UsingInterface();
    }
}

In this example, we create a MyButton class, which will implement the action listener.

 MyButton close = new MyButton("Close");

Here we create the MyButton custom class.

 class MyButton extends JButton implements ActionListener {

The MyButton class is extended from the JButton class. It implements the ActionListener interface. This way, the event handling is managed within the MyButton class.

 addActionListener(this);

Here we add the action listener to the MyButton class.

Multiple sources

A listener can be plugged into several sources. This will be explained in the next example.

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

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;


public class MultipleSources extends JFrame {

    JLabel statusbar;

    public MultipleSources() {

        setTitle("Multiple Sources");
        JPanel panel = new JPanel();
        statusbar = new JLabel(" ZetCode");

        statusbar.setBorder(BorderFactory.createEtchedBorder(
                EtchedBorder.RAISED));

        panel.setLayout(null);

        JButton close = new JButton("Close");
        close.setBounds(40, 30, 80, 25);
        close.addActionListener(new ButtonListener());

        JButton open = new JButton("Open");
        open.setBounds(40, 80, 80, 25);
        open.addActionListener(new ButtonListener());

        JButton find = new JButton("Find");
        find.setBounds(40, 130, 80, 25);
        find.addActionListener(new ButtonListener());

        JButton save = new JButton("Save");
        save.setBounds(40, 180, 80, 25);
        save.addActionListener(new ButtonListener());

        panel.add(close);
        panel.add(open);
        panel.add(find);
        panel.add(save);

        add(panel);
        add(statusbar, BorderLayout.SOUTH);

        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e)
        {
            JButton o = (JButton) e.getSource();
            String label = o.getText();
            statusbar.setText(" " + label + " button clicked");
        }
      }


    public static void main(String[] args) {
        new MultipleSources();
    }
}

We create four buttons and a statusbar. The statusbar will display an informative message upon clicking on the button.

 close.addActionListener(new ButtonListener());
 ...
 open.addActionListener(new ButtonListener());
 ...

Each button will be registered against a ButtonListener class.

 JButton o = (JButton) e.getSource();
 String label = o.getText();

Here we determine, which button was pressed.

 statusbar.setText(" " + label + " button clicked")

We update the statusbar.


Multiple Sources
Figure: Multiple Sources

Multiple listeners

We can register several listeners for one event.

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

import java.util.Calendar;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EtchedBorder;


public class MultipleListeners extends JFrame {

    private JLabel statusbar;
    private JSpinner spinner;
    private static int count = 0;

    public MultipleListeners() {

        setTitle("Multiple Listeners");
        JPanel panel = new JPanel();
        statusbar = new JLabel("0");

        statusbar.setBorder(BorderFactory.createEtchedBorder(
                EtchedBorder.RAISED));

        panel.setLayout(null);

        JButton add = new JButton("+");
        add.setBounds(40, 30, 80, 25);
        add.addActionListener(new ButtonListener1());
        add.addActionListener(new ButtonListener2());

        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);

        SpinnerModel yearModel = new SpinnerNumberModel(currentYear,
                                       currentYear - 100,
                                       currentYear + 100,
                                       1);

        spinner = new JSpinner(yearModel);
        spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));

        spinner.setBounds(190, 30, 80, 25);

        panel.add(add);
        panel.add(spinner);

        add(panel);
        add(statusbar, BorderLayout.SOUTH);

        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    class ButtonListener1 implements ActionListener {
        public void actionPerformed(ActionEvent e)
        {
            Integer val = (Integer) spinner.getValue();
            spinner.setValue(++val);
        }
      }

    class ButtonListener2 implements ActionListener {
        public void actionPerformed(ActionEvent e)
        {
            statusbar.setText(Integer.toString(++count));
        }
      }


    public static void main(String[] args) {
        new MultipleListeners();
    }
}

In this example, we have a button, spinner and a statusbar. We use two button listeners for one event. One click of a button will add one year to the spinner component and update the statusbar. The statusbar will show, how many times we have clicked on the button.

 add.addActionListener(new ButtonListener1());
 add.addActionListener(new ButtonListener2());

We register two button listeners.

 SpinnerModel yearModel = new SpinnerNumberModel(currentYear,
                              currentYear - 100,
                              currentYear + 100,
                              1);
 spinner = new JSpinner(yearModel);

Here we create the spinner component. We use a year model for the spinner. The SpinnerNumberModel arguments are initial value, min, max values and the step.

 spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));

We remove the thousands separator.

 Integer val = (Integer) spinner.getValue();
 spinner.setValue(++val);

Here we increase the year number.


Multiple Listeners
Figure: Multiple Listeners

Removing listeners

The Java Swing toolkit enables us to remove the registered listeners.

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

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


public class RemoveListener extends JFrame {

    private JLabel text;
    private JButton add;
    private JCheckBox active;
    private ButtonListener buttonlistener;
    private static int count = 0;

    public RemoveListener() {

        setTitle("Remove listener");
        JPanel panel = new JPanel();

        panel.setLayout(null);

        add = new JButton("+");
        add.setBounds(40, 30, 80, 25);
        buttonlistener = new ButtonListener();

        active = new JCheckBox("Active listener");
        active.setBounds(160, 30, 140, 25);

        active.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (active.isSelected()) {
                  add.addActionListener(buttonlistener);}
                else {
                  add.removeActionListener(buttonlistener);
                }
            }
        });

        text = new JLabel("0");
        text.setBounds(40, 80, 80, 25);

        panel.add(add);
        panel.add(active);
        panel.add(text);

        add(panel);

        setSize(310, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e)
        {
            text.setText(Integer.toString(++count));
        }
      }

    public static void main(String[] args) {
        new RemoveListener();
    }
}

We have three components on the panel. A button, check box and a label. By toggling the check box, we add or remove the listener for a button.

 buttonlistener = new ButtonListener();

We have to create a non anonymous listener, if we want to later remove it. We need a reference to it.

 if (active.isSelected()) {
     add.addActionListener(buttonlistener);}
 else {
     add.removeActionListener(buttonlistener);
 }

We determine, whether the check box is selected. Then we add or remove the listener.


Remove listener
Figure: Remove listener

Moving a window

The following example will look for a position of a window on the screen.

import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

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


public class MovingWindow extends JFrame implements ComponentListener {

    private JLabel labelx;
    private JLabel labely;

    public MovingWindow() {

        setTitle("Moving window");

        JPanel panel = new JPanel();
        panel.setLayout(null);

        labelx = new JLabel("x: ");
        labelx.setFont(new Font("Serif", Font.BOLD, 14));
        labelx.setBounds(20, 20, 60, 25);

        labely = new JLabel("y: ");
        labely.setFont(new Font("Serif", Font.BOLD, 14));
        labely.setBounds(20, 45, 60, 25);

        panel.add(labelx);
        panel.add(labely);

        add(panel);

        addComponentListener(this);

        setSize(310, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void componentResized(ComponentEvent e) {
    }

    public void componentMoved(ComponentEvent e) {
        int x = e.getComponent().getX();
        int y = e.getComponent().getY();
        labelx.setText("x: " + x);
        labely.setText("y: " + y);
    }

    public void componentShown(ComponentEvent e) {
    }

    public void componentHidden(ComponentEvent e) {
    }


    public static void main(String[] args) {
        new MovingWindow();
    }
}

The example shows the current window coordinates on the panel. To get the window position, we use the ComponentListener

 labelx.setFont(new Font("Serif", Font.BOLD, 14));

We make the font bigger, the default one is a bit small.

 int x = e.getComponent().getX();
 int y = e.getComponent().getY();

Here we get the x and the y positions.

Notice, that we have to implement all four methods, that are available in the ComponentListener. Even, if we do not use them.


Moving a window
Figure: Moving a window

Adapters

Adapters are convenient classes. In the previous code example, we had to implement all four methods of a ComponentListener class. Even if we did not use them. To avoid unnecessary coding, we can use adapters. Adapter is a class that implements all necessary methods. They are empty. We then use only those methods, that we actually need. There is no adapter for a button click event. Because there we have only one method to implement. The actionPerformed() method. We can use adapters in situations, where we have more than one method to implement.

The following example is a rewrite of the previous one, using a ComponentAdapter.

import java.awt.Font;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

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


public class Adapter extends JFrame {

    private JLabel labelx;
    private JLabel labely;

    public Adapter() {

        setTitle("Adapter");

        JPanel panel = new JPanel();
        panel.setLayout(null);

        labelx = new JLabel("x: ");
        labelx.setFont(new Font("Serif", Font.BOLD, 14));
        labelx.setBounds(20, 20, 60, 25);

        labely = new JLabel("y: ");
        labely.setFont(new Font("Serif", Font.BOLD, 14));
        labely.setBounds(20, 45, 60, 25);


        panel.add(labelx);
        panel.add(labely);

        add(panel);
        addComponentListener(new MoveAdapter());

        setSize(310, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }


    class MoveAdapter extends ComponentAdapter {
      public void componentMoved(ComponentEvent e) {
          int x = e.getComponent().getX();
          int y = e.getComponent().getY();
          labelx.setText("x: " + x);
          labely.setText("y: " + y);
      }
     }

    public static void main(String[] args) {
        new Adapter();
    }
}

This example is a rewrite of the previous one. Here we use the ComponentAdapter.

 addComponentListener(new MoveAdapter());

Here we register the component listener.

 class MoveAdapter extends ComponentAdapter {
     public void componentMoved(ComponentEvent e) {
         int x = e.getComponent().getX();
	 int y = e.getComponent().getY();
	 labelx.setText("x: " + x);
         labely.setText("y: " + y);
     }
 }

Inside the MoveAdapter inner class, we define the componentMoved() method. All the other methods are left empty.

+ Recent posts