Java Graphical User Interface(GUI): Adapter Class Using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept of Adapter Class
  • The user will learn how to use Adapter Class to override only methods the user wants to use.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

In the previous tutorial, we looked at MouseListener and MouseMotionListener. We also looked at the five methods in MouseListener and the two methods in MouseMotionlistener; seven methods in total.

A programmer might want to write a program using these two classes, and only wants to use two methods in his program; it is necessary to implement all the methods contained in the class, however, implementing the seven methods from these two classes could be quite tedious and time consuming.

Java comes up with a construct that enables the programmer override only methods that concerns his program. Using this construct, the programmer can only implement the methods he wants saving time and making the program less bulky.

This tutorial follows through from the previous tutorial, creating a panel and status bar that displays messages but instead of implementing five methods, the program uses MouseAdapter to implement only two methods that suits the program, mouseEntered and mouseClicked methods.

Adapter Class

An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events relevant to you.

1.png

2.png

CODE BLOCK

adapter Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class adapter extends JFrame {
    private JPanel panel;
    private JLabel messageBar;
    public adapter() {
        super("Adapter Class Demo");
        messageBar = new JLabel("Default");
        add(messageBar, BorderLayout.SOUTH);
        panel = new JPanel();
        panel.setBackground(Color.YELLOW);
        add(panel, BorderLayout.CENTER);
        panel.addMouseListener(new handlerClass());
    }
    private class handlerClass extends MouseAdapter {
        public void mouseEntered (MouseEvent event) {
            panel.setBackground(Color.BLUE);
        }
        public void mouseClicked (MouseEvent event) {
            messageBar.setText(String.format("You clicked %d times", event.getClickCount()));
            if (event.isMetaDown())
                messageBar.setText(String.format("You clicked %d times " + "with right mouse button", event.getClickCount()));
            else if (event.isAltDown())
                messageBar.setText(String.format("You clicked %d times " + "with center mouse button", event.getClickCount()));
            else
                messageBar.setText(String.format("You clicked %d times " + "with left mouse button", event.getClickCount()));
        }
    }
}
adapterMain Class
import javax.swing.JFrame;
public class adapterMain {
    public static void main (String args []) {
        adapter event = new adapter();
        event.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        event.setSize(500, 300);
        event.setVisible(true);
    }
}

adapter Class

panel = new JPanel();
panel.setBackground(Color.YELLOW);
add(panel, BorderLayout.CENTER);
panel.addMouseListener(new handlerClass());

A JPanel object is created and background color is set to Yellow.
The panel is added to the screen, the

BorderLayout.CENTER

Method is used to place the panel in the center of the screen.

A new handlerClass is created to hold the listener instructions and is passed to the MouseListener class.

private class handlerClass extends MouseAdapter {
        public void mouseEntered (MouseEvent event) {
            panel.setBackground(Color.BLUE);
        }
        public void mouseClicked (MouseEvent event) {
            messageBar.setText(String.format("You clicked %d times", event.getClickCount()));
            if (event.isMetaDown())
                messageBar.setText(String.format("You clicked %d times " + "with right mouse button", event.getClickCount()));
            else if (event.isAltDown())
                messageBar.setText(String.format("You clicked %d times " + "with center mouse button", event.getClickCount()));
            else
                messageBar.setText(String.format("You clicked %d times " + "with left mouse button", event.getClickCount()));
        }
    }
}

The newly created handlerClass extends MouseAdapter. This allows the programmer to implement only the methods he requires.

The mouseEntered method is implemented and instructions given.

The mouseClicked method is also implemented and instructions given to return number of clicks.

if (event.isMetaDown())
messageBar.setText(String.format("You clicked %d times " + "with right mouse button", event.getClickCount()));

If statement to determine if a button is clicked with the right mouse button. The .isMetaDown() method is used to pass instructions if user clicks with right mouse button.
A message is displayed if this is true.

else if (event.isAltDown())
messageBar.setText(String.format("You clicked %d times " + "with center mouse button", event.getClickCount()));

else if statement to determine if a button is clicked with the centre mouse button. The .isAltDown() method is used to pass instructions if user clicks with the centre mouse button.
A message is displayed if this is true.

else
messageBar.setText(String.format("You clicked %d times " + "with left mouse button", event.getClickCount()));

else statement to display a message if the above statements is false.

mouseMain CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class adapterMain {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main (String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

adapter event = new adapter();

An Object of the adapter class is created. This enables the user to call in built GUI methods that will help to properly display the JPanel and JLabel components to the screen.

event.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

event.setSize(500, 300);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (500, 300).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

event.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

0.png

3.png

The program is run and color of the panel changes when mouse enters the panel area.

4.png

When the user clicks using the left mouse button, a message is displayed in the status bar below.

5.png

When the user clicks using the center mouse button, a message is displayed in the status bar below.

6.png

When the user clicks using the right mouse button, a message is displayed in the status bar below.

7.png

8.png

9.png

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by will-ugo from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x