I would like to set up a JButton so that it\'s icon is aligned to the left of it, while the text is centered.
I have found how to have one of them left, the other right
You can add a layout manager to your JButton
, for example a Border Layout would help:
You create a JLabel
with an Icon
and one with the text "Click me":
JLabel iconLabel = new JLabel(new ImageIcon(this.getClass().getResource("king.png")));
JLabel clickMe = new JLabel("Click me", SwingConstants.CENTER); //We give it the center alignment so it stays on the center of the label.
Then you create your JButton
, give it the Border Layout and add your components to it on the positions where you want it.
button.setLayout(new BorderLayout());
button.add(iconLabel, BorderLayout.WEST);
button.add(clickMe, BorderLayout.CENTER);
I gave each label a border so you could see how each label looks like, since the clickMe
label won't be right in the center of the JButton
but on the center of its JLabel
:
I think it's not a big deal as it's almost imperceptible w/o the borders