Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

mouselistener in java

package com.javapointers.javase;
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
 
public class MouseListenerTest implements MouseListener {
 
    JPanel leftPanel, rightPanel;
    JTextArea textArea;
    JFrame frame;
 
    public MouseListenerTest() {
        frame = new JFrame("MouseListener Test");
        textArea = new JTextArea();
        textArea.setLineWrap(true);
 
        leftPanel = new JPanel();
        rightPanel = new JPanel();
        leftPanel.setPreferredSize(new Dimension(200, 100));
        rightPanel.setPreferredSize(new Dimension(200, 100));
        leftPanel.setBackground(Color.GREEN);
        rightPanel.setBackground(Color.BLUE);
 
        leftPanel.addMouseListener(this);
        rightPanel.addMouseListener(this);
 
        frame.setLayout(new BorderLayout());
        frame.add(leftPanel, BorderLayout.WEST);
        frame.add(rightPanel, BorderLayout.EAST);
        frame.add(textArea, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == leftPanel) {
            textArea.setText("You have clicked the left panel");
        } else {
            textArea.setText("You have clicked the right panel");
        }
    }
 
    @Override
    public void mousePressed(MouseEvent e) {
        if (e.getSource() == leftPanel) {
            textArea.setText("You have pressed the left panel");
        } else {
            textArea.setText("You have pressed the right panel");
        }
    }
 
    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getSource() == leftPanel) {
            textArea.setText("You have released mouse on left panel");
        } else {
            textArea.setText("You have released mouse on right panel");
        }
    }
 
    @Override
    public void mouseEntered(MouseEvent e) {
        if (e.getSource() == leftPanel) {
            textArea.setText("You have entered mouse on left panel");
        } else {
            textArea.setText("You have entered mouse on right panel");
        }
    }
 
    @Override
    public void mouseExited(MouseEvent e) {
        if (e.getSource() == leftPanel) {
            textArea.setText("You have exited mouse on left panel");
        } else {
            textArea.setText("You have exited mouse on right panel");
        }
    }
 
    public static void main(String args[]) {
        MouseListenerTest test = new MouseListenerTest();
    }
}
 
PREVIOUS NEXT
Tagged: #mouselistener #java
ADD COMMENT
Topic
Name
4+6 =