Java 如何从自定义JButton截取paintComponent

Java 如何从自定义JButton截取paintComponent,java,swing,awt,jbutton,paintcomponent,Java,Swing,Awt,Jbutton,Paintcomponent,我创建了一个自定义JButton,背景透明,并从graphics.drawRoundRect()中绘制了一条线,但当我启动程序进行测试时,我的JCheckbox一直显示在按钮顶部 一开始是这样的 这是在我用鼠标悬停在按钮上之后 以下是来自paintComponent方法的代码 @Override public void paintComponent(Graphics graphics) { graphics.setColor(this.getForeground());

我创建了一个自定义JButton,背景透明,并从graphics.drawRoundRect()中绘制了一条线,但当我启动程序进行测试时,我的JCheckbox一直显示在按钮顶部

一开始是这样的

这是在我用鼠标悬停在按钮上之后

以下是来自paintComponent方法的代码

    @Override
public void paintComponent(Graphics graphics) {
    graphics.setColor(this.getForeground());
    graphics.drawRoundRect(2, 2, this.getWidth() - 4, this.getHeight() - 4, 30, 30);
    graphics.setFont(this.getFont());

    int centerX = getWidth() / 2;
    int centerY = getHeight() / 2;

    FontMetrics fontMetrics = graphics.getFontMetrics();
    Rectangle stringBounds = fontMetrics.getStringBounds(this.getText(), graphics).getBounds();

    int textX = centerX - stringBounds.width / 2;
    int textY = centerY + fontMetrics.getAscent() / 2;

    graphics.setColor(this.getForeground());
    graphics.drawString(this.getText(), textX, textY);

}
我的button类中没有任何其他方法,除了包含super()的构造函数。 该类继承自JButton类,我在测试程序中将前台属性设置为Color.white,并通过

frame.getContentPane().add(button);
因为我的声誉不够高,所以我无法在问题中插入截图,而是使用imgur链接。
如果不允许我发布问题中的链接,我将立即删除它们

如果您已断开绘制链,则必须调用
super.paintComponent

public void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);
本质上,
Graphics
是一个共享资源,绘制的每个组件都将使用相同的
Graphics
上下文,这意味着除非先清除它,否则可能仍然存在以前绘制的内容。
paintComponent
的工作之一是用组件的背景色清除
Graphics
上下文

有关详细信息,请参阅和


确保使用
setOpaque(false)
使组件透明,否则可能会导致其他问题。您可能还想使用
setBorderPaint
setFocusPainted
setContentAreaFilled
来更改默认外观和感觉代理绘制按钮的方式谢谢,这没有问题,现在只有一件事困扰着我,当我单击按钮时,它会以正常的JButton颜色高亮显示,我没有找到任何属性来更改该颜色。选择颜色可能直接来自
UIManager
。如果我设置contentAreaFilled(false),则它不会在单击时更改颜色,我还添加了setO乳(false)。但现在我的字体相当粗体和模糊,即使我检查它是普通的。我使用的是Tahoma Plain,11px,很可能文本被绘制了两次,一次是由UI代表绘制,一次是由您绘制
JButton
是一个复杂的小组件,最好使用自己的UI委托