mre*_*mre 3 java swing jbutton
我想设置文本上方和下方一个JButton的图标.目前,为了实现这一点,我覆盖了布局管理器并使用了三个JLabel实例(即2个用于文本,1个用于图标).但这似乎是一个肮脏的解决方案.
有更直接的方法吗?
注意 -
我不是在寻找多线解决方案,我正在寻找一种多标签解决方案.虽然这条是指它作为一个多行的解决方案,它实际上似乎是指一个多标签解决方案.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)

无法在JButton的顶部/底部之间拆分文本.这将涉及定制绘画.
由于我不确定您的具体要求,我将通过一些随机的想法:
您可以使用带有文本和图标的JButton.API中有一些方法允许您控制文本相对于图标的位置.那么你需要另一个标签用于另一行文本.基本上与您当前的解决方案相同,但您只需要两个标签.
使用JTextPane.它支持insertIcon()方法.因此,您可以添加一行文本,添加图标,然后添加另一行文本.如果您不希望文本左对齐,则可以使用文本窗格的段落属性来在文本窗格内水平对齐文本.您还可以使用背景颜色使其看起来像标签.
使用CompoundIcon的示例:
import java.awt.*;
import javax.swing.*;
public final class JButtonDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JButton button = new JButton();
CompoundIcon icon = new CompoundIcon(CompoundIcon.Axis.Y_AXIS,
new TextIcon(button, "Top Label"),
UIManager.getIcon("OptionPane.informationIcon"),
new TextIcon(button, "Bottom Label"));
button.setIcon( icon );
button.setFocusPainted( false );
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add( button );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6307 次 |
| 最近记录: |