Search code examples
javagraphicsjmenuitemjmenubar

Components on the JMenuBar


I am looking for a way to change the graphics of a component on a JMenuBar

I have the following JMenuBar.

package GUIMain;

import javax.swing.*;
import java.awt.*;

public class MyMenuBar extends JMenuBar
{
    int fontMetrics;
    FontMetrics fM;
    
    JLabel lblSmartSize = new JLabel("", SwingConstants.CENTER);
    JCheckBox chkbtnSmartSize = new JCheckBox();
    
    SortsGui sG;
    
    public MyMenuBar(SortsGui sG)
    {
        this.sG = sG;
        setBorderPainted(true);
        makePopUpMenu();
    }
    
    void makePopUpMenu()
    {
        add(Box.createHorizontalGlue());
        
        fM = lblSmartSize.getFontMetrics(lblSmartSize.getFont());
        fontMetrics = fM.stringWidth("Enable Smart Resizing?");
        lblSmartSize.setMinimumSize(new Dimension(fontMetrics+10,25));
        lblSmartSize.setPreferredSize(new Dimension(fontMetrics+10,25));
        lblSmartSize.setMaximumSize(new Dimension(fontMetrics+10,25));
        add(lblSmartSize);
        
        chkbtnSmartSize.setBackground(lblSmartSize.getBackground());
        add(chkbtnSmartSize);
    }
}

This creates a JMenuBar which looks like this (apologies for blown up screenshot) Shows picture of the menu bar

As you can see the JMenuBar has a JLabel and a JCheckBox on it. How would I change the background of the JCheckBox so that it does not have a square around it which is different to the standard look of the JMenuBar.

I have tried the following code and have so far been unsuccessful

chkbtnSmartSize.setBackground(this.getBackground());

(On a different attempt)

chkbtnSmartSize.setBackground(lblSmartSize.getBackground());

Any help in accomplishing this would be grateful

Thanks,

Dan


Solution

  • It turns out there are a few ways to do this.

    The simplest way to do this would to be to remove the border and the background of the component. For example with this check box I should do

    chkbtnSmartSize.setOpaque(false);
    chkbtnSmartSize.setContentAreaFilled(false);
    chkbtnSmartSize.setBorder(null);
    chkbtnSmartSize.setFocusable(false);
    

    Another way would be to change the background of the JMenuBar and then do the same for the check box.

    Color color = Color.red; 
    @Override //This Method changes the background colour of the JMenuBar
    protected void paintComponent(Graphics g) {
    
        super.paintComponent(g);
    
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(color);
        g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
    
    }
    ...
    chkbtnSmartSize.setBackground(color);
    

    If you remove the background of the check box and change the color of the JMenuBar you do not need the line of code chkbtnSmartSize.setBackground(color);

    Finally if you set the background of the JComponent to the same color of the background of the JMenuBar it will have the same affect as the first method did.