TITLE SHOULD ACTUALLY BE: how to get mouselistener to work on method in an class in java

If I click a circle it should change the color of the circle. But, I am having difficult getting it to work.
Help appreciated.

Main just calls this class and calls the init function.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hopfieldnet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;



public class hop2d extends JFrame{
    static final int MAXPATTERNS = 4;
    static final int ROWS = 8;                       // Dimensions of the images
    static final int COLS = 8;
    static final int MAINSCREEN = 0;        // Constants for drawing the screens
    static final int TRAINPATTS = 1;

    JButton viewTrainPattern;   // Click on this button to view the training patterns
    JButton singleStep;
    MyPanel patPanel ;// Click on this button to run a test one (more) step
    int trainPatterns[][][] = new int [MAXPATTERNS][COLS][ROWS];
    int testPattern[][] = new int [COLS][ROWS];
    int t[][][][] = new int [COLS][ROWS][COLS][ROWS];   // connection weights
    int screenMode = MAINSCREEN;

    public void init()
    {
        JFrame frame = new JFrame("Hopfield Net");
        JPanel panel = new JPanel();
        patPanel = new MyPanel(200, 300);
        JLabel panel1 = new JLabel();
        ItemHandler itemHandler = new ItemHandler();
        singleStep = new JButton("Single Step");
        viewTrainPattern = new JButton("View Train Pattern");
        singleStep.setSize(30, 15);
        viewTrainPattern.setSize(30,15);
        frame.setSize(600, 600);
        panel.setBounds(150, 100, 180 , 120);
        singleStep.addActionListener(itemHandler);
        viewTrainPattern.addActionListener(itemHandler);
        panel.add(singleStep);
        panel.add(viewTrainPattern);
        frame.getContentPane().add(panel, BorderLayout.NORTH);
        setupTrainingPatterns();
        // Initialise test pattern to blank
        for (int i = 0; i < COLS; i++)
            for (int j = 0; j < ROWS; j++)
                testPattern[i][j] = -1;
        panel1.setText(testPattern.toString());
        frame.getContentPane().add(patPanel, BorderLayout.CENTER);
        frame.setVisible(true);
    }
    


    public void setupTrainingPatterns ()
    {

        initialisePattern(0,"00000000","01111110","01000010","01000010","01000010","01000010","01111110","00000000");
        initialisePattern(1,"00000000","00010000","00010000","00010000","11111110","00010000","00010000","00010000");
        initialisePattern(2,"10011110","10010010","10010010","10010010","10010010","10010010","10010010","11110011");
        initialisePattern(3,"00000000","00010000","00011000","00100100","00100100","01000010","01000010","11111111");
        //retrain();
    }

    public void initialisePattern (int patNum, String line0, String line1, String line2, String line3,String line4, String line5, String line6, String line7)
    {
        initialiseline(patNum,0,line0);
        initialiseline(patNum,1,line1);
        initialiseline(patNum,2,line2);
        initialiseline(patNum,3,line3);
        initialiseline(patNum,4,line4);
        initialiseline(patNum,5,line5);
        initialiseline(patNum,6,line6);
        initialiseline(patNum,7,line7);
    }

    public void initialiseline (int patNum, int lineNum, String line)
    {
        for (int i = 0; i < line.length(); i++)
            if (line.charAt(i) == '1')
                trainPatterns[patNum][i][lineNum] = +1;
            else
                trainPatterns[patNum][i][lineNum] = -1;
    }

//    @Override
//    public void paint (Graphics g)
//    {
//        switch (screenMode)
//        {
//            case MAINSCREEN : drawMainScreen(g);  break;
//            case TRAINPATTS : drawTrainingPatterns(g); break;
//        }
//    }

//    public void drawMainScreen (Graphics g)
//    {
//        g.drawString("Test pattern",50,40);
//        for (int j = 0; j < ROWS; j++)
//            for (int i = 0; i < COLS; i++)
//                drawCell(g,testPattern[i][j],50 + 12 * i, 50 + 12 * j);
//    }

//    public void drawTrainingPatterns (Graphics g)
//    {
//        for (int pattern = 0; pattern < MAXPATTERNS; pattern++)
//        {
//            g.drawString("Pattern " + pattern, 5 + 110 * pattern, 45);
//            for (int i = 0; i < COLS; i++)
//                for (int j = 0; j < ROWS; j++)
//                drawCell(g, trainPatterns[pattern][i][j],5 + 110 * pattern + 12 * i, 50 + 12 * j);
//        }
//    }

    // Draw a particular value of 1 or -1
    public void drawCell (Graphics g, int value, int x, int y)
    {
        if (value == 1)
            g.setColor(Color.black);
        else
            g.setColor(Color.white);
            g.fillOval(x,y,12,12);         // Draws a white circle or a black one
            g.setColor(Color.black);
            g.drawOval(x,y,12,12);
    }

    public void runSingleStep ()
    {
        int new_mu[][] = new int[COLS][ROWS];   // Holds new values of mu before copying back
        int i,j,k,l;                                                           // FOR loop counters
        for (k = 0; k < COLS; k++)
            for (l = 0; l < ROWS; l++)
            {
                int sum = 0;
                for (i = 0; i < COLS; i++)
                    for (j = 0; j < ROWS; j++)
                        sum += t[i][j][k][l] * testPattern[i][j];
                        if (sum > 0)    // Pass through hard-limiting non-linearity
                            new_mu[k][l] = 1;
                        else
                            new_mu[k][l] = -1;
            }
            // Now copy the values present in new_mu back into the test pattern ready to be displayed
            for (i = 0; i < COLS; i++)
                for (j = 0; j < ROWS; j++)
                    testPattern[i][j] = new_mu[i][j];
           repaint();
    }

    public void retrain ()
    {
        for (int i = 0; i < COLS; i++)
            for (int j = 0; j < ROWS; j++)
                for (int k = 0; k < COLS; k++)
                    for (int l = 0; l < ROWS; l++)
                        if (i == k && j == l)
                            t[i][j][k][l] = 0;
                        else
                        {
                            int sum = 0;
                            for (int pattern = 0; pattern < MAXPATTERNS; pattern++)
                                sum += trainPatterns[pattern][i][j] * trainPatterns[pattern][k][l];
                                t[i][j][k][l] = sum;
                        }
    }
    
    

class ItemHandler implements ActionListener{
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == viewTrainPattern)
        {
            if (viewTrainPattern.getLabel() == "View Training Patterns")
            {
                viewTrainPattern.setLabel("View Main Screen");
                patPanel.setBackground(Color.red);
                screenMode = TRAINPATTS;
                patPanel.setScreenMode(screenMode);
                repaint();
            }
            else
            {
                viewTrainPattern.setLabel("View Training Patterns");
                patPanel.setBackground(Color.GREEN);
                screenMode = MAINSCREEN;
                patPanel.setScreenMode(screenMode);
                repaint();
            }
        }
        if (e.getSource() == singleStep)
        {
             runSingleStep();
             patPanel.setBackground(Color.BLUE);
             repaint();
        }
    }
}

    class MyPanel extends JPanel
    {
        private int width=100, height=100;
        public MyPanel(int w, int h)
        {
            width=(w>=0?w:100);
            height=(h>=0?h:100);
        }
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            switch (screenMode)
            {
                case MAINSCREEN: drawMainScreen(g); break;
                case TRAINPATTS: drawTrainingPatterns(g); break;
            }
        }
        
        public void setScreenMode(int c){
            screenMode=c;
        }
        public void drawMainScreen (Graphics g){
            g.drawString("Test pattern",50,40);
            for (int j = 0; j < ROWS; j++)
                for (int i = 0; i < COLS; i++)
                    drawCell(g,testPattern[i][j],50 + 12 * i, 50 + 12 * j);
        }

        public void drawTrainingPatterns (Graphics g)    {
            for (int pattern = 0; pattern < MAXPATTERNS; pattern++)
            {
                g.drawString("Pattern " + pattern, 5 + 110 * pattern, 45);
                for (int i = 0; i < COLS; i++)
                    for (int j = 0; j < ROWS; j++)
                    drawCell(g, trainPatterns[pattern][i][j],5 + 110 * pattern + 12 * i, 50 + 12 * j);
            }
        }
    }
}

Dani AI

Generated

The MouseListener is already firing (the "This is working" print), so the remaining piece is hit‑detection: map the mouse Point back to the 8×8 grid cell, then test whether that Point actually lies inside the circular dot drawn in that cell. was right to suggest e.getPoint() and Rectangle.contains(); the next step is to convert that Point into array indexes and then test a circle hit (distance from circle center <= radius) rather than only relying on the bounding rectangle.

Mapping recipe (use the same offsets used by drawCell): compute i = (mouseX - baseX) / cellSize and j = (mouseY - baseY) / cellSize, check 0 <= i < COLS and 0 <= j < ROWS, then compute the cell's center (cellX + cellSize/2, cellY + cellSize/2) and test (dxdx + dydy <= radiusradius). For TRAINPATTS, compute which pattern column was clicked first (pattern = (mouseX - patternBaseX) / patternSpacing), then use baseX = patternBaseX + patternpatternSpacing for that pattern. On hit, toggle the backing array (testPattern or trainPatterns[pattern]) and call repaint().

Example (put inside MyPanel.mousePressed; inner class can access outer fields):

Point p = e.getPoint();
final int cell = 12, radius = cell/2;
if (screenMode == MAINSCREEN) {
    int baseX = 50, baseY = 50;
    int i = (p.x - baseX) / cell;
    int j = (p.y - baseY) / cell;
    if (i >= 0 && i < COLS && j >= 0 && j < ROWS) {
        int cx = baseX + i*cell + radius, cy = baseY + j*cell + radius;
        int dx = p.x - cx, dy = p.y - cy;
        if (dx*dx + dy*dy <= radius*radius) {
            testPattern[i][j] = (testPattern[i][j] == 1) ? -1 : 1;
            repaint();
        }
    }
}

Troubleshooting notes: ensure the listener is attached to the drawing panel (patPanel), not a covering container; account for panel insets if present; call repaint after changing model; keep GUI creation on the EDT (SwingUtilities.invokeLater). Add braces in drawCell for clarity to avoid logic surprises. This approach builds on 's Rectangle idea but gives exact circle hits and lets each circle be toggled reliably.

Recommended Answers

All 4 Replies

i have 2 panels because i have two windows...
The draw cell method creates a graphic object and i want to change color depending on if the graphic object is selected or not. I can't even create a handle to it.

Added mouse listener it works whenever I click anywhere not only when I click on the circles

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hopfieldnet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;



public class hop2d extends JFrame{
    static final int MAXPATTERNS = 4;
    static final int ROWS = 8;                       // Dimensions of the images
    static final int COLS = 8;
    static final int MAINSCREEN = 0;        // Constants for drawing the screens
    static final int TRAINPATTS = 1;

    JButton viewTrainPattern;   // Click on this button to view the training patterns
    JButton singleStep;
    MyPanel patPanel ;// Click on this button to run a test one (more) step
    int trainPatterns[][][] = new int [MAXPATTERNS][COLS][ROWS];
    int testPattern[][] = new int [COLS][ROWS];
    int t[][][][] = new int [COLS][ROWS][COLS][ROWS];   // connection weights
    int screenMode = MAINSCREEN;

    public void init()
    {
        JFrame frame = new JFrame("Hopfield Net");
        JPanel panel = new JPanel();
        patPanel = new MyPanel(200, 300);
        JLabel panel1 = new JLabel();
        ItemHandler itemHandler = new ItemHandler();
        singleStep = new JButton("Single Step");
        viewTrainPattern = new JButton("View Train Pattern");
        singleStep.setSize(30, 15);
        viewTrainPattern.setSize(30,15);
        frame.setSize(600, 600);
        panel.setBounds(150, 100, 180 , 120);
        singleStep.addActionListener(itemHandler);
        viewTrainPattern.addActionListener(itemHandler);
        panel.add(singleStep);
        panel.add(viewTrainPattern);
        frame.getContentPane().add(panel, BorderLayout.NORTH);
        
        setupTrainingPatterns();
        // Initialise test pattern to blank
        for (int i = 0; i < COLS; i++)
            for (int j = 0; j < ROWS; j++)
                testPattern[i][j] = -1;
        panel1.setText(testPattern.toString());
        frame.getContentPane().add(patPanel, BorderLayout.CENTER);
        frame.setVisible(true);
    }



    public void setupTrainingPatterns ()
    {

        initialisePattern(0,"00000000","01111110","01000010","01000010","01000010","01000010","01111110","00000000");
        initialisePattern(1,"00000000","00010000","00010000","00010000","11111110","00010000","00010000","00010000");
        initialisePattern(2,"10011110","10010010","10010010","10010010","10010010","10010010","10010010","11110011");
        initialisePattern(3,"00000000","00010000","00011000","00100100","00100100","01000010","01000010","11111111");
        //retrain();
    }

    public void initialisePattern (int patNum, String line0, String line1, String line2, String line3,String line4, String line5, String line6, String line7)
    {
        initialiseline(patNum,0,line0);
        initialiseline(patNum,1,line1);
        initialiseline(patNum,2,line2);
        initialiseline(patNum,3,line3);
        initialiseline(patNum,4,line4);
        initialiseline(patNum,5,line5);
        initialiseline(patNum,6,line6);
        initialiseline(patNum,7,line7);
    }

    public void initialiseline (int patNum, int lineNum, String line)
    {
        for (int i = 0; i < line.length(); i++)
            if (line.charAt(i) == '1')
                trainPatterns[patNum][i][lineNum] = +1;
            else
                trainPatterns[patNum][i][lineNum] = -1;
    }

//    @Override
//    public void paint (Graphics g)
//    {
//        switch (screenMode)
//        {
//            case MAINSCREEN : drawMainScreen(g);  break;
//            case TRAINPATTS : drawTrainingPatterns(g); break;
//        }
//    }

//    public void drawMainScreen (Graphics g)
//    {
//        g.drawString("Test pattern",50,40);
//        for (int j = 0; j < ROWS; j++)
//            for (int i = 0; i < COLS; i++)
//                drawCell(g,testPattern[i][j],50 + 12 * i, 50 + 12 * j);
//    }

//    public void drawTrainingPatterns (Graphics g)
//    {
//        for (int pattern = 0; pattern < MAXPATTERNS; pattern++)
//        {
//            g.drawString("Pattern " + pattern, 5 + 110 * pattern, 45);
//            for (int i = 0; i < COLS; i++)
//                for (int j = 0; j < ROWS; j++)
//                drawCell(g, trainPatterns[pattern][i][j],5 + 110 * pattern + 12 * i, 50 + 12 * j);
//        }
//    }

    // Draw a particular value of 1 or -1
    public void drawCell (Graphics g, int value, int x, int y)
    {
        if (value == 1)
            g.setColor(Color.black);
        else
            g.setColor(Color.white);
            g.fillOval(x,y,12,12);         // Draws a white circle or a black one
            g.setColor(Color.black);
            g.drawOval(x,y,12,12);
    }


    public void runSingleStep ()
    {
        int new_mu[][] = new int[COLS][ROWS];   // Holds new values of mu before copying back
        int i,j,k,l;                                                           // FOR loop counters
        for (k = 0; k < COLS; k++)
            for (l = 0; l < ROWS; l++)
            {
                int sum = 0;
                for (i = 0; i < COLS; i++)
                    for (j = 0; j < ROWS; j++)
                        sum += t[i][j][k][l] * testPattern[i][j];
                        if (sum > 0)    // Pass through hard-limiting non-linearity
                            new_mu[k][l] = 1;
                        else
                            new_mu[k][l] = -1;
            }
            // Now copy the values present in new_mu back into the test pattern ready to be displayed
            for (i = 0; i < COLS; i++)
                for (j = 0; j < ROWS; j++)
                    testPattern[i][j] = new_mu[i][j];
           repaint();
    }

    public void retrain ()
    {
        for (int i = 0; i < COLS; i++)
            for (int j = 0; j < ROWS; j++)
                for (int k = 0; k < COLS; k++)
                    for (int l = 0; l < ROWS; l++)
                        if (i == k && j == l)
                            t[i][j][k][l] = 0;
                        else
                        {
                            int sum = 0;
                            for (int pattern = 0; pattern < MAXPATTERNS; pattern++)
                                sum += trainPatterns[pattern][i][j] * trainPatterns[pattern][k][l];
                                t[i][j][k][l] = sum;
                        }
    }



    class ItemHandler implements ActionListener{
        public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == viewTrainPattern)
            {
                if (viewTrainPattern.getLabel() == "View Training Patterns")
                {
                    viewTrainPattern.setLabel("View Main Screen");
                    patPanel.setBackground(Color.red);
                    screenMode = TRAINPATTS;
                    patPanel.setScreenMode(screenMode);
                    repaint();
                }
                else
                {
                    viewTrainPattern.setLabel("View Training Patterns");
                    patPanel.setBackground(Color.GREEN);
                    screenMode = MAINSCREEN;
                    patPanel.setScreenMode(screenMode);
                    repaint();
                }
            }
            if (e.getSource() == singleStep)
            {
                 runSingleStep();
                 patPanel.setBackground(Color.BLUE);
                 repaint();
            }
        }
    }

    class MyPanel extends JPanel
    {
        private int width=100, height=100;
        public MyPanel(int w, int h)
        {
            addMouseListener(new MouseAdapter() {
                @Override
            public void mousePressed(MouseEvent me) {
            System.out.println("This is working");
          }
        });

            width=(w>=0?w:100);
            height=(h>=0?h:100);
        }
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            switch (screenMode)
            {
                case MAINSCREEN: drawMainScreen(g); break;
                case TRAINPATTS: drawTrainingPatterns(g); break;
            }
        }

        public void setScreenMode(int c){
            screenMode=c;
        }
        public void drawMainScreen (Graphics g){
            g.drawString("Test pattern",50,40);
            for (int j = 0; j < ROWS; j++)
                for (int i = 0; i < COLS; i++)
                    drawCell(g,testPattern[i][j],50 + 12 * i, 50 + 12 * j);
        }

        public void drawTrainingPatterns (Graphics g)    {
            for (int pattern = 0; pattern < MAXPATTERNS; pattern++)
            {
                g.drawString("Pattern " + pattern, 5 + 110 * pattern, 45);
                for (int i = 0; i < COLS; i++)
                    for (int j = 0; j < ROWS; j++)
                    drawCell(g, trainPatterns[pattern][i][j],5 + 110 * pattern + 12 * i, 50 + 12 * j);
            }
        }
    }
}

In the line 125 (drawCell-method) write

System.out.println(new Rectangle(x,y,12,12));

Inside this rectangles circles are drawn on the panel
If you pressed mouse, you know position of mouse

// convert mousePosition to i,j array indexes
    public void mousePressed(MouseEvent e) {

        Point p = e.getPoint();//mouse position
        System.out.println(p);
        Rectangle lastCircle = new Rectangle(134, 134, 12, 12); //test example

        boolean b = lastCircle.contains(p); //check, is point p inside rectangle?
        if (b) {
            System.out.println("Mouse is inside a last circle, table indexes i,j are ...");
        }
        // useing drawCell(g, testPattern[i][j], 50 + 12 * i, 50 + 12 * j); parameters
        // and g.drawOval(x, y, 12, 12); parameters
        // you can reverse calculate indexes i and j !
        // store i,j outside, and use them in other parts of program
       
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.