0

Working on a homework assignment and I'm having issues with figuring out how to print a line of text when a mouse cursor enters and exits a certain colored area (a JPanel called panel in this case) while using the MouseListener interface.

I choose a color from the bottom panel (either Red, blue, or yellow) and then when I move to the upper panel it should be able to print which color the mouse has entered in while the mouse is in the panel and which color I exited from when my mouse finds itself outside of said panel...

Hopefully that makes sense. Here's a code snippet of what I have so far. This is for the color RED:

class RedButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            panel.setBackground(Color.RED); 
            class RedMouseListener implements MouseListener
            {

                public void mouseEntered(MouseEvent event) 
                { 

                }

                public void mouseExited(MouseEvent event) 
                { 

                }

                public void mousePressed(MouseEvent event) { }

                public void mouseReleased(MouseEvent event) { }

                public void mouseClicked(MouseEvent event) { }
            }
        }
    }
    ActionListener redListener = new RedButtonListener();
    bRed.addActionListener(redListener);
Matthieu
  • 2,736
  • 4
  • 57
  • 87
Hunter
  • 1
  • 1
  • 1
  • 1

2 Answers2

0

Here's a relevant question from Stack Overflow Mouse moved event within JPanel

I'd recommend once you ensure that triggers are being correctly listened to (try printing "Hello World") From there you need to get the communication of the color state within the mouse event. If everything is within the same instance you can just access the variables needed within the event listener.

Here are the docs on MouseEvent http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseEvent.html

Make sure you added the mouse listener try the following

panel.addMouseListener(new RedMouseListener());

start simple making the following work

public void mouseEntered(MouseEvent event) 
{ 
    System.out.println("Hello World!");
}

if you need to access the color of the panel within the event listener try the following snippet

panel.getBackground();

This returns a Color object.

Its worth mentioning the extra class declaration can be avoided by using an anonymous inner class. see How are Anonymous (inner) classes used in Java? These overridden methods are essentially a sub class of MouseListener but we don't need to call it by name.

panel.addMouseListener(new MouseListener(){ 
    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseClicked(MouseEvent e) {}
});
Community
  • 1
  • 1
t3dodson
  • 3,949
  • 2
  • 29
  • 40
  • That compiles without problems, but nothing shows up. No matter where I put addMouseListener it gives me an error and doesn't compile. I do need that, right? – Hunter Jun 11 '14 at 02:59
  • @Hunter I'm making an example of an anonymous class that will help. Are you tied to writing your own RedMouseListener? – t3dodson Jun 11 '14 at 03:01
  • Ah, okay so the addMouseListener has finally decided to compile after that, but still no text shows up when I hover my mouse over the RED area. I'm not sure what you mean, but I have to make a MouseListener for each of the three colors. So for example, I'll click on the RED button and the JPanel will turn red. When I hover my mouse over the area, it will print "Mouse has entered the RED area." When it moves outside of the JPanel it will say "Mouse has exited the RED area." It's going to be for all three colors. – Hunter Jun 11 '14 at 03:05
  • @Hunter could you do a switch within one of the listeners or a bunch of if's – t3dodson Jun 11 '14 at 03:07
  • I'm sorry, I'm not sure exactly how I'd do that. I'm fairly new to Java. – Hunter Jun 11 '14 at 03:14
  • @Hunter Define "RED" area? Until you can provide more context, everything we do is guess work... – MadProgrammer Jun 11 '14 at 03:28
  • Just the color red. A red colored box, essentially. Thanks for the help, regardless. – Hunter Jun 11 '14 at 03:44
  • @Hunter How is it rendered? Are you painting, is it a component? If it is a component, how many other components are on the screen or is there only one? – MadProgrammer Jun 11 '14 at 03:54
0

Introduction

Since this is such an old question, I thought I'd put together a simple Swing GUI to illustrate how a MouseListener works.

Here's the GUI before I do anything.

enter image description here

The main panel in the center will take on the selector color when the mouse is moved into the selection area. The main panel will return to it's original color when the mouse is moved out of the selection area.

Here's the GUI when my mouse is in the blue selection area.

enter image description here

Explanation

If you're not familiar with Java Swing, Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Concurrency in Swing and the Laying Out Components Within a Container sections.

When I create a Swing GUI, I use the model/view/controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.

The MVC pattern implies that you create the model first, then the view, then the controller. This is more of an iterative process than a waterfall.

In Java Swing, the MVC pattern means:

  1. The view reads information from the model.
  2. The view may not update the model.
  3. The controller updates the model and repaints / revalidates the view.

The model consists of one or more plain Java getter/setter classes.

The view consists of a JFrame and however many JPanels it takes to create the GUI.

There's usually not one controller "to rule them all". Each listener acts as an independent controller to manage its part of the model and view.

This is a simple application, so it consists of two model classes, one view class, and one controller class. The model is not updated at all in this example.

I did not code this entire application at one time. I wrote a few lines of code and ran tests. I made lots of changes to the code before I was satisfied with how it worked.

Model

The ColorSelection class is a plain Java getter/setter class that holds the color name, background color, and foreground color.

The MouseMovementModel class is a plain Java getter/setter class that holds the ColorSelection instances. The GUI builds the selection JPanel based on this information. If you want to add another selection color, you would add it here.

View

The view consists of a JFrame, a selection JPanel, and the main JPanel.

The JFrame has a default BorderLayout. The selection JPanel goes into the NORTH section and the main JPanel goes into the CENTER section. Only one component can be placed in a section. That component is usually a JPanel.

The selection JPanel uses a FlowLayout to hold the color selection JPanels. The color selection JPanels are created based on the number of ColorSelection instances in the application model.

A color selection JPanel is a simple JPanel created to use the information from a ColorSelection instance.

The main JPanel is a simple JPanel that will show a background color. The controller will be responsible for changing the background color.

Controller

The ColorListener class extends a MouseAdapter. The MouseAdapter class implements the MouseListener, MouseMotionListener, and MouseWheelListener interfaces. Using the MouseAdapter class allows me to implement just the mouse listener methods I'm writing code for.

The mouseEntered method sets the main JPanel to the ColorSelection color. The code is really simple. It updates the view with the ColorSelection background color.

The mouseExited method sets the main JPanel back to its original color.

Code

Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

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

public class MouseMovementExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MouseMovementExample());
    }
    
    private final JPanel mainPanel;
    private final JPanel[] colorPanel;
    
    private final MouseMovementModel model;
    
    public MouseMovementExample() {
        this.model = new MouseMovementModel();
        this.mainPanel = createMainPanel();
        this.colorPanel = new JPanel[model.getSelections().length];
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Mouse Movement Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createSelectionPanel(), BorderLayout.NORTH);
        frame.add(mainPanel, BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createSelectionPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        ColorSelection[] selections = model.getSelections();
        
        for (int index = 0; index < selections.length; index++) {
            ColorSelection selection = selections[index];
            ColorListener listener = new ColorListener(this, selection);
            colorPanel[index] = createColorPanel(selection, listener);
            panel.add(colorPanel[index]);
        }
        
        return panel;
    }
    
    private JPanel createColorPanel(ColorSelection selection, ColorListener listener) {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(selection.getBackgroundColor());
        panel.addMouseListener(listener);
        panel.setPreferredSize(new Dimension(200, 100));
        
        JLabel label = new JLabel(selection.getColorName());
        label.setFont(panel.getFont().deriveFont(Font.BOLD, 36f));
        label.setForeground(selection.getForegroundColor());
        label.setHorizontalAlignment(JLabel.CENTER);
        panel.add(label, BorderLayout.CENTER);
        
        return panel;
    }
    
    private JPanel createMainPanel() {
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(200, 200));
        
        return panel;
    }
    
    public Color getMainPanelBackground() {
        return this.mainPanel.getBackground();
    }
    
    public void setMainPanelBackground(Color color) {
        this.mainPanel.setBackground(color);
    }
    
    public class ColorListener extends MouseAdapter {
        
        private final Color originalBackgroundColor;
        
        private final ColorSelection selection;
        
        private final MouseMovementExample view;

        public ColorListener(MouseMovementExample view, ColorSelection selection) {
            this.view = view;
            this.selection = selection;
            this.originalBackgroundColor = view.getMainPanelBackground();
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            view.setMainPanelBackground(selection.getBackgroundColor());
        }

        @Override
        public void mouseExited(MouseEvent e) {
            view.setMainPanelBackground(originalBackgroundColor);
        }
        
    }
    
    public class MouseMovementModel {
        
        private final ColorSelection[] selections;
        
        public MouseMovementModel() {
            this.selections = new ColorSelection[3];
            
            this.selections[0] = new ColorSelection("Red", Color.RED, Color.WHITE);
            this.selections[1] = new ColorSelection("Green", Color.GREEN, Color.BLACK);
            this.selections[2] = new ColorSelection("Blue", Color.BLUE, Color.WHITE);
        }

        public ColorSelection[] getSelections() {
            return selections;
        }
        
    }
    
    public class ColorSelection {
        
        private final Color backgroundColor, foregroundColor;
        
        private final String colorName;

        public ColorSelection(String colorName, Color backgroundColor, Color foregroundColor) {
            this.colorName = colorName;
            this.backgroundColor = backgroundColor;
            this.foregroundColor = foregroundColor;
        }

        public Color getBackgroundColor() {
            return backgroundColor;
        }

        public Color getForegroundColor() {
            return foregroundColor;
        }

        public String getColorName() {
            return colorName;
        }
        
    }

}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111