How can a MouseListener on one panel use values of an object on a different panel?

26 views Asked by At

I'm an experienced developer, just not in JAVA or OOP. I am stuck on a basic java fundamental.

I am building a small app that has a drawing area (JPanel) that when clicked will draw a colored shape on the panel where the user clicks. The shape and color of the object to be drawn is determined by radio and combo buttons on another panel.

What would be a very basic fundamental way to do this?

I start with a JFrame, add a left and right JPanel. The left panel has a mouselistener, the right has the attributes needed for the shape to be drawn.

I was able to get the drawing part to work but only with a hard coded shape built into it.

1

There are 1 answers

0
AudioBubble On

I would suggest adding reference to the said object by using as argument in action listener constructor method.

The Complete Running Example:

package com.jms.app;

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

import javax.swing.*;

public class MainApp extends JFrame {

    JPanel mainPanel = new JPanel(new BorderLayout());
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    SomeListener listener = new SomeListener(panel2); //YOU WANT RIGHT PANEL TO DRAW

    public MainApp() {
        panel1.setBorder(BorderFactory.createLineBorder(Color.black));
        panel1.setPreferredSize(new Dimension(150, 150));
        panel1.addMouseListener(listener); //YOU WANT LEFT PANEL TO CAPTURE MOUSE EVENT
        panel2.setBorder(BorderFactory.createLineBorder(Color.black));
        panel2.setPreferredSize(new Dimension(150, 150));

        mainPanel.add(panel1, BorderLayout.WEST);
        mainPanel.add(panel2, BorderLayout.EAST);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(mainPanel);
        setSize(300, 150);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args){
        MainApp app = new MainApp();
        app.setVisible(true);
    }

    class SomeListener extends MouseAdapter {
        private JPanel panel = null;

        public SomeListener(JPanel panel) {
            this.panel = panel;
        }

        public void mouseClicked(MouseEvent e) {
            System.out.println("Here is your referenced object." + panel.toString());
            //I'm lazy to draw for you.
        }
    } 
}