Align JButton icon to the left and keep text centered

跟風遠走 提交于 2019-12-31 04:00:29

问题


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, or both at the same setting, but I couldn't find what I am looking for.

Of course I can always redefine the paint methods, but I am looking for a leaner way to do it.


回答1:


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



来源:https://stackoverflow.com/questions/42169261/align-jbutton-icon-to-the-left-and-keep-text-centered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!