在JPanel中填充JButton

时间:2018-11-15 12:42:47

标签: java swing awt

我有一个JPanel充当应用程序的顶部栏,我现在正在尝试设计顶部栏按钮,但是我面临一个问题。

enter image description here

如您所见,当我将鼠标悬停在其上方时,红色没有填充面板,我希望红色为完整的正方形。并保持顶部栏和图标大小相同。我期望的结果是

enter image description here

如您所见,颜色填充在整个条形图中。我想重新创建这个。

下面是自定义JButtonClass的代码,以创建悬停效果。

public class LynxButton extends JButton {
    public LynxButton(){
        super.setContentAreaFilled(false);
    }

    public LynxButton(String text) {
        super(text);
        super.setContentAreaFilled(false);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Color pressedColor = ThemeManager.red_LYNX.darker();
        if (getModel().isPressed()) {
            g.setColor(pressedColor);
        } else if (getModel().isRollover()) {
            g.setColor(pressedColor);
        } else {
            g.setColor(getBackground());
        }
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(g);
    }


    @Override
    public void setContentAreaFilled(boolean b) {
    }
}

然后我们使用

定义代码
    LynxButton exitButton = new LynxButton();
    exitButton.setIcon(...);
    exitButton.setBorder(null);

我试图设置页边空白,以查看是否可以解决问题,但还是没有运气。

exitButton.setMargin(new Insets(0, 0, 0, 0));

编辑:忘记显示JPanel Defination

JPanel buttonContainer = new JPanel(new FlowLayout(FlowLayout.RIGHT));

buttonContainer填充了整个顶部栏,通过取消对setBackgroundColor的调用来确认它。

enter image description here

1 个答案:

答案 0 :(得分:0)

您没有从hgap来计算vgapFlowLayout。它们的作用就像一个自然的边界。

您需要做的就是将JPanel的初始化更改为new JPanel(new FlowLayout(FlowLayout.RIGHT), 0, 0)

示例代码:

public static void main(String[] args) {
    JFrame f = new JFrame();
    TestA b = new TestA("X");
    JPanel buttonContainer = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
    buttonContainer.setBackground(Color.GREEN);
    buttonContainer.add(b);
    f.add(buttonContainer);
    f.pack();
    f.setVisible(true);
}

TestA是您的LynxButton

class TestA extends JButton {
    public TestA() {
        super.setContentAreaFilled(false);
    }

    public TestA(String text) {
        super(text);
        super.setContentAreaFilled(false);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Color pressedColor = Color.RED;
        if (getModel().isPressed()) {
            g.setColor(pressedColor);
        } else if (getModel().isRollover()) {
            g.setColor(pressedColor);
        } else {
            g.setColor(getBackground());
        }
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(g);
    }

    @Override
    public void setContentAreaFilled(boolean b) {
    }
}