Search code examples
javaimageswingimageiconjradiobutton

Adding figure to JRadioButtonMenuItem


I have to create a simple Text Editor which has menu bar with specific options.

One of them is to change font colors by selecting it on JRadioButtonMenuItem which has to look exactly as professor described in the picture.

My problem is that I don't know how to create and add those little circles between text and radio button.

Screenshot


Solution

  • Somehow I've managed to solve my problem by using Icon interface. Here's a little part of my code with final result. I'm still open for any kind of tips and improvements to my code to make it better and learn by coding properly.

    Here's my Circle class:

    public class Circle implements Icon {
        Color color;
    
        public Circle(Color color){
            this.color = color;
        }
    
        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            g.setColor(color);
            g.drawOval(x, y, getIconWidth(), getIconHeight());
            g.fillOval(x, y, getIconWidth(), getIconHeight());
        }
    
        @Override
        public int getIconWidth() {
            return 7;
        }
    
        @Override
        public int getIconHeight() {
            return 7;
        }
    }
    

    and my GUI method of showing menu bar:

    private void myMenuBar(
            ...
            JMenu optionsForeground,
            JRadioButtonMenuItem optionsForeBlue
    ) {
    
        ...
        optionsForegroundBlue.setForeground(color);
        optionsForegroundBlue.setIcon(new Circle(color));
    
        optionsForeground.add(optionsForeBlue);
        options.add(optionsForeground);
    
        options.add(optionsBackground);
        options.add(optionsFontSize);
    
        menuBar.add(file);
        menuBar.add(edit);
        menuBar.add(options);
    }
    

    result