我想设置一个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