-1

I need to use a JButton with a icon and text. I tried using

JButton btnLogout = new JButton();
ImageIcon icon = new ImageIcon(getClass().getResource("icon.png"));
btnLogout.setIcon(icon);
btnLogout.setText("Logout");

but this gives me a button like

+---------+
|icon|text|
+---------+

but i need the button like

+--------+
|  icon  |
|  Text  |
+--------+

How can i do this in java ?

new question
  • 29
  • 1
  • 9

1 Answers1

-1

You should google this first. You can find many similar solutions

Anyways, You could do this using html.

String text= "<html>"
                + "<center>"
                + "<img src=\"file:" + getClass().getResource("icon.png").getFile().toString() + "\" >"
                + "<br>Logout"
                + "</center></html>";

btnLogout.setText(text);

If you want to style more, you can use this library made by me.

Malinda
  • 358
  • 5
  • 18
  • You can use single quotes instead of escaping double quotes. – Salem Jan 15 '17 at 11:01
  • The URL won't work if the resource is embedded within the a Jar file – MadProgrammer Jan 15 '17 at 11:09
  • @MadProgrammer Yes. That's true. he is loading image from resources. So this will work for his issue. – Malinda Jan 15 '17 at 11:31
  • Thank you @Malinda. It's worked – new question Jan 15 '17 at 11:32
  • 1) This can be achieved using existing methods, as detailed in the duplicate. 2) `getResource(..)` returns an URL, which will already be prefixed with `file:` 3) Using HTML rendering, a disabled button does not render as it would for a normal button. 4) Using HTML rendering to load an icon, we lose the default ability to set different icons for unfocused, focused, pressed, hovered.. 5) @MadProgrammer *"The URL won't work if the resource is embedded within the a Jar file"* Sure it's possible, see [this answer](http://stackoverflow.com/a/18443485/418556). Are you referring the `file:` prefix? – Andrew Thompson Jan 15 '17 at 13:33