gpt4 book ai didi

java - JButton 显示在图标后面

转载 作者:行者123 更新时间:2023-12-01 05:14:27 25 4
gpt4 key购买 nike

我正在尝试创建一个扩展 JButton 的自定义按钮。它接收文本以及按钮所需的宽度和高度。构造函数根据输入的宽度和高度缩放图像按钮。但是,正如您在附图中看到的那样,出现了问题。

Attempt to create button.

这是我的类(class):

class GameButton extends JButton {
public GameButton(String text, int width, int height) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("Images/Other/buttonImage.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Create new (blank) image of required (scaled) size
BufferedImage scaledImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);

// Paint scaled version of image to new image
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, width, height, null);
// clean up
graphics2D.dispose();

ImageIcon icon = new ImageIcon(scaledImage);

setIcon(icon);
setMargin(new Insets(0, 0, 0, 0));
setIconTextGap(0);
setBorderPainted(false);
setOpaque(false);
setBorder(null);
setText(text);
setSize(width, height);
}
}

原始按钮图像仍在绘制,看起来图像可能无法正确缩放。有什么想法吗?

谢谢!

最佳答案

设置按钮的水平文本位置

jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

关于java - JButton 显示在图标后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11495276/

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