1

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.

Attempt to create button.

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!

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Julian
  • 325
  • 1
  • 3
  • 10
  • 1
    This [answer](http://stackoverflow.com/a/6736108/480417) contains some useful code. Also, you should set the horizontal text position to centered, so that it is drawn over the icon. – lhballoti Jul 15 '12 at 20:33
  • 3
    JButton.setContentAreaFilled(false); – MadProgrammer Jul 15 '12 at 22:55
  • 2
    Why not paint "Plant!" directly to the scaled image (and not use a button text)? BTW - please upload the 'plank' image, and for better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Jul 16 '12 at 05:40

1 Answers1

0

set HorizontalTextPosition for Button

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