Search code examples
javaswingiconsjbuttonjcomponent

Setting JButton Icon


I want a JButton to have an icon on it. So far I have this.

ImageIcon ii = new ImageIcon("Button.png");
width = ii.getIconWidth();
height = ii.getIconHeight();
Toolkit tk = Toolkit.getDefaultToolkit();
windowW = (int) tk.getScreenSize().getWidth();
windowH = (int) tk.getScreenSize().getHeight();
play = new JButton("Play");
play.setSize(width, height);
play.setLocation(windowW / 2 - 165,windowH / 2 - 165);
play.setIcon(ii);
play.addActionListener(this);

It get the icon's width and height and then set the JButton to the icon's width and height but for some reason the icon will be a little to the left so that you still can see some of the JButton's default texture. This is an image of how it looks like:

example output

How would I make it so that the image covers the whole JButton like it's supposed to?


Solution

  • This is because you add Play text to the button like that new JButton("Play");

    if you delete Play you will see

    image covers the whole JButton