【问题标题】:Components on the JMenuBarJMenuBar 上的组件
【发布时间】:2015-11-21 10:04:35
【问题描述】:

我正在寻找一种方法来更改 JMenuBar 上的组件图形

我有以下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);
    }
}

这会创建一个看起来像这样的JMenuBar(对于放大的屏幕截图表示歉意)

如您所见,JMenuBar 上有一个JLabel 和一个JCheckBox。如何更改JCheckBox 的背景,使其周围没有与JMenuBar 的标准外观不同的正方形。

我已经尝试了以下代码,但到目前为止都没有成功

chkbtnSmartSize.setBackground(this.getBackground());

(在不同的尝试中)

chkbtnSmartSize.setBackground(lblSmartSize.getBackground());

如有任何帮助,将不胜感激

谢谢,

【问题讨论】:

    标签: java graphics jmenuitem jmenubar


    【解决方案1】:

    事实证明有几种方法可以做到这一点。

    最简单的方法是移除组件的边框和背景。例如,我应该使用此复选框

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

    另一种方法是更改​​ JMenuBar 的背景,然后对复选框执行相同操作。

    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);
    

    如果删除复选框的背景并更改JMenuBar的颜色,则不需要chkbtnSmartSize.setBackground(color);这行代码

    最后,如果您将JComponent 的背景设置为与JMenuBar 的背景颜色相同的颜色,它将具有与第一种方法相同的效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多