我想设置一个JButton,以使其图标在其左侧对齐,而文本居中.
我已经找到了如何在相同的设置下让其中一个左,另一个右或两者都处于同一位置,但是我找不到我想要的东西.
当然,我总是可以重新定义绘画方法,但是我正在寻找一种更简洁的方法.
解决方法:
您创建一个带有图标的JLabel,并创建一个带有文本“ 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,为其提供Border Layout,并在所需位置添加组件.
button.setLayout(new BorderLayout());
button.add(iconLabel, BorderLayout.WEST);
button.add(clickMe, BorderLayout.CENTER);
我给每个标签加了一个边框,这样您就可以看到每个标签的样子,因为clickMe标签不会正好在JButton的中心,而是在其JLabel的中心:


我认为这没什么大不了的,因为几乎没有边界

标签:java,swing,jbutton
来源: https://codeday.me/bug/20191012/1902481.html
这篇博客解决了在Java Swing中如何设置JButton,使其图标显示在左侧,而文本保持居中的问题。通过创建两个JLabel分别设置图标和文本,并使用BorderLayout布局将它们添加到JButton中,实现了所需效果。这种方法避免了直接修改按钮的绘制方法,提供了一种简洁的解决方案。
943

被折叠的 条评论
为什么被折叠?



