Inheriting from adapter class saves ours time as we need not implement all the functions of the interface we want to use.The adapter class
implement that interface and overrides the functions with empty
body and then we gonna easily inherit the adapter class and use only the required functions.
For example in the following code i just used onMouseClicked() ,
see this for handling Mouse events with adapter class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI extends JFrame {
private String details;
private JLabel statusBar;
public GUI() {
super("title");
statusBar = new JLabel("default stage");
add(statusBar, BorderLayout.SOUTH);
addMouseListener(new MouseClass());
}
// An abstract adapter class for receiving mouse events.
// The methods in this class are empty.
// This class exists as convenience for creating listener objects.
private class MouseClass extends MouseAdapter {
//MouseEvent is an event which indicates that a mouse
//action occurred in a component
public void mouseClicked(MouseEvent e) {
details = "";
details += String.format("I clicked %d ", e.getClickCount());
if(e.isMetaDown())
details += " with right mouse button" ;
else if(e.isAltDown())
details += " with centeer mouse button " ;
else
details += " with left mouse button ";
statusBar.setText(details);
}
}
}
implement that interface and overrides the functions with empty
body and then we gonna easily inherit the adapter class and use only the required functions.
For example in the following code i just used onMouseClicked() ,
see this for handling Mouse events with adapter class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI extends JFrame {
private String details;
private JLabel statusBar;
public GUI() {
super("title");
statusBar = new JLabel("default stage");
add(statusBar, BorderLayout.SOUTH);
addMouseListener(new MouseClass());
}
// An abstract adapter class for receiving mouse events.
// The methods in this class are empty.
// This class exists as convenience for creating listener objects.
private class MouseClass extends MouseAdapter {
//MouseEvent is an event which indicates that a mouse
//action occurred in a component
public void mouseClicked(MouseEvent e) {
details = "";
details += String.format("I clicked %d ", e.getClickCount());
if(e.isMetaDown())
details += " with right mouse button" ;
else if(e.isAltDown())
details += " with centeer mouse button " ;
else
details += " with left mouse button ";
statusBar.setText(details);
}
}
}