将JButton图标向左对齐并保持文本居中 [英] Align JButton icon to the left and keep text centered

查看:105
本文介绍了将JButton图标向左对齐并保持文本居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个JButton,以使其图标在其左侧对齐,而文本居中.

我已经找到了如何在相同的设置下将其中一个左,另一个或两个都保留,但是我找不到我想要的东西.

当然,我总是可以重新定义 paint 方法,但是我正在寻找一种更精简的方法.

解决方案

您可以添加JButton的noreferrer>布局管理器,例如边框布局会有所帮助:

您创建一个带有IconJLabel和一个带有文本"Click me"的JLabel:

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.

然后创建JButton,为其提供边框布局,然后将组件添加到所需的位置.

button.setLayout(new BorderLayout());
button.add(iconLabel, BorderLayout.WEST);
button.add(clickMe, BorderLayout.CENTER);

我给每个标签加了一个边框,这样您就可以看到每个标签的样子,因为clickMe标签不会正好位于JButton的中心,而是位于其JLabel的中心:

我认为这没什么大不了的,因为它几乎不受边界的影响

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.

解决方案

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

这篇关于将JButton图标向左对齐并保持文本居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆