How can i style a JButton? [duplicate]

260
January 15, 2017, at 8:33 PM

This question already has an answer here:

  • Positioning JLabel in JPanel below the image 1 answer

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 ?

Answer 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.

READ ALSO
How do I reduce latency caused by resource cache eviction in Tomcat?

How do I reduce latency caused by resource cache eviction in Tomcat?

Contrary to Jetty, I found that an embedded Tomcat server does not extract resources (JSP, CSS, JS, images, etc) from WAR/JAR files on startup

298
Whats wrong with this my timer?

Whats wrong with this my timer?

Ok so i am halfway done with this timer script but i noticed when it runs the functions the second time it does not take in inputs anymore any idea why? It does take in all and waits for inputs on start

191
Initializing a string in java error

Initializing a string in java error

While running this code on netbeans it always run the if statement block but on compiling it on HackerRank code editor it always go into the else statementHelp me with the error

356
grid is not showing in javaFX

grid is not showing in javaFX

I am using javafx and I want to have a grid with colors like http://wwwlestard

403