简体   繁体   English

JButton在图标后面显示

[英]JButton showing behind icon

I am trying to create a custom button which extends JButton. 我试图创建一个扩展JButton的自定义按钮。 It takes in the text and the desired width and height of the button. 它接受文本以及按钮的所需宽度和高度。 The constructor scales the image button based on the input width and height. 构造函数根据输入的宽度和高度缩放图像按钮。 However, something is going wrong as you can see in the attached image. 但是,出了问题,如您在所附图像中看到的那样。

尝试创建按钮。

Here is my 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);
    }
}

The original button image is still drawing and it looks as though the image may not be scaled correctly. 原始按钮图像仍在绘制中,看起来图像可能无法正确缩放。 Any ideas? 有任何想法吗?

Thanks! 谢谢!

为Button设置Horizo​​ntalTextPosition

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM