Align JButton icon to the left and keep text centered

前端 未结 1 466
无人及你
无人及你 2021-01-21 15:51

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

1条回答
  •  迷失自我
    2021-01-21 16:42

    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

    0 讨论(0)
提交回复
热议问题