【发布时间】:2011-11-13 18:32:19
【问题描述】:
我想将文本上下设置为JButton 的图标。目前,为了实现这一点,我重写了布局管理器并使用了三个 JLabel 实例(即 2 个用于文本,1 个用于图标)。但这似乎是一个肮脏的解决方案。
有没有更直接的方法?
注意 -
我不是在寻找 multi-line 解决方案,我在寻找 multi-label解决方案。虽然this 文章将其称为多行解决方案,但实际上它似乎是指多标签解决方案。
示例
import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public final class JButtonDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JMultiLabelButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class JMultiLabelButton extends JButton
{
private static final long serialVersionUID = 7650993517602360268L;
public JMultiLabelButton()
{
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(new JCenterLabel("Top Label"));
add(new JCenterLabel(UIManager.getIcon("OptionPane.informationIcon")));
add(new JCenterLabel("Bottom Label"));
}
}
private static final class JCenterLabel extends JLabel
{
private static final long serialVersionUID = 5502066664726732298L;
public JCenterLabel(final String s)
{
super(s);
setAlignmentX(Component.CENTER_ALIGNMENT);
}
public JCenterLabel(final Icon i)
{
super(i);
setAlignmentX(Component.CENTER_ALIGNMENT);
}
}
}
【问题讨论】:
-
不确定我是否理解要求。按钮的边框呢?如果您希望文本超出边界,那么我认为您需要使用您的方法。或者你是否试图让文本在边框内?如果您摆脱了边框,那么为什么要使用按钮?你需要鼠标支持吗?发布您的 SSCCE,展示您目前所做的事情,以便我们可以看到您想要实现的确切外观。