import javax.swing.*;
class First{
public static void main(String args[]){
Second gui = new Second();
gui.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
gui.setSize(300, 200);
gui.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Second extends JFrame {
private JPanel mousePanel;
private JLabel statusBar;
public Second(){
super("title");
mousePanel = new JPanel();
mousePanel.setBackground(Color.RED);
// Settomg the layout to be centered
add(mousePanel, BorderLayout.CENTER);
// Setting the statusBar default text to "Default" & setting the layout to NORTH (up)
statusBar = new JLabel("Default");
add(statusBar, BorderLayout.NORTH);
// Creating an object to pass in the event listener
HandlerClass handler = new HandlerClass();
// Assigning an event listener to the mousePanel and passing in the handler object
mousePanel.addMouseListener(handler);
mousePanel.addMouseMotionListener(handler);
}
// Creating the HandlerClass and implementing MouseListener & MouseMotionListener for all to be overriden
private class HandlerClass implements MouseListener, MouseMotionListener{
// Overriding the methods from the libraries and setting the designated event for each one
public void mouseClicked(MouseEvent event){
statusBar.setText(String.format("Clicked at X:%d Y:%d", event.getX(), event.getY()));
}
public void mousePressed(MouseEvent event){
statusBar.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent event){
statusBar.setText("Mouse Released");
}
public void mouseEntered(MouseEvent event){
statusBar.setText("Mouse Entered MousePanel");
}
public void mouseExited(MouseEvent event){
statusBar.setText("Mouse Exited MousePanel");
}
// Mouse Motion Events:
public void mouseDragged(MouseEvent event){
statusBar.setText("Mouse Dragged");
}
public void mouseMoved(MouseEvent event){
statusBar.setText("Mouse Moved");
}
}
}