简体   繁体   中英

JButton showing behind icon

I am trying to create a custom button which extends 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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