'Change color of dots drawn on JLabel depending on what RadioButton (JRadioButton) is chosen

My app allows the user to draw dots on the image (JLabel) with a mouseclick. I have a bunch of RadioButtons on the panel. When one of them is selected AND the mouse is clicked on the image, the color of the dot should match the color specified in the RadioButton class. RadioButton is simply a class that contains JRadioButton and Color.

        facialFeaturePanel = new JPanel();
        facialFeaturePanel.setBorder(BorderFactory.createTitledBorder(
                 BorderFactory.createEtchedBorder(), "Facial Features"));
        
        ArrayList <String> face = new ArrayList<>(Arrays.asList("L Eye", "R Eye", "L Ear", "R Ear", "Nose", "Mouth", "Chin"));
        ArrayList <Color> clist = new ArrayList<>(Arrays.asList(Color.red, Color.pink, Color.blue, Color.cyan, Color.green, Color.black,
                 new Color(102,0,153)));
        
        LinkedList <RadioButton> facialFeatures = createRadioButtons(face,clist);
                
        for (RadioButton rb : facialFeatures) {
            rb.getButton().addActionListener(this);
            facialFeaturePanel.add(rb.getButton());
        }

Here's the code for the mouseclick on the image. Forgive me for bad coding I'm pretty new to Java. Is there a better way of making this work?


    public void actionPerformed(ActionEvent e) {
        for(int i=0; i < facialFeatures.size(); i++) {
            if(e.getSource() == facialFeatures.get(i).getButton()) {
                if (WindowFrame.imagePanel.imgLabel!=null) {
                    @SuppressWarnings("removal")
                    final Integer innerI = new Integer(i);
                    WindowFrame.imagePanel.imgLabel.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mousePressed(MouseEvent e) {
                            Graphics g = WindowFrame.imagePanel.imgLabel.getGraphics();
                            Point p = e.getPoint();
                            g.setColor(facialFeatures.get(innerI).getColor());
                            g.fillRect(p.x-2, p.y-2, 4, 4);
                            System.out.println("Point: " + p.getLocation());
                        }
                    });
                    
                } else {
                    System.out.println("ImgLabel is null");
                }
            }
        }
    }

The problem is when I add more LinkedLists of RadioButtons to the actionPerformed, it doesn't work. I basically copied and pasted the code from for(int i=0; i < facialFeatures.size(); i++) { a couple times with different LinkedLists



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source