gpt4 book ai didi

java - 如何从自定义JButton拦截paintComponent

转载 作者:行者123 更新时间:2023-11-30 03:35:10 28 4
gpt4 key购买 nike

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

一开始是这样的

enter image description here

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

enter image description here

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

}

除了带有 super() 的构造函数之外,我的按钮类中没有任何其他方法。该类继承自 JButton 类,我在测试程序中将前景属性设置为 Color.white 并通过添加按钮

frame.getContentPane().add(button);

因为我的声誉不够高,所以我无法将屏幕截图插入到我正在使用 imgur 链接的问题中。如果我不被允许发布问题中的链接,我会立即删除它们

最佳答案

你已经破坏了绘制链,你必须调用super.paintComponent

public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);

本质上,Graphics是一个共享资源,绘制的每个组件都将使用相同的Graphics上下文,这意味着除非您先清除它,否则您可能仍然拥有以前的内容画到它还在那里。 paintComponent 的工作之一是使用组件的背景颜色清除 Graphics 上下文...

参见Painting in AWT and SwingPerforming Custom Painting了解更多详情

确保您使用 setOpaque(false) 使组件透明,否则可能会出现其他问题。您可能还想使用 setBorderPaintsetFocusPaintedsetContentAreaFilled 来更改默认外观委托(delegate)绘制按钮的方式

关于java - 如何从自定义JButton拦截paintComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162747/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com