【问题标题】:JButton with both icon (on top) and text (on bottom) aligned to the leftJButton 的图标(顶部)和文本(底部)都向左对齐
【发布时间】:2020-07-18 04:09:27
【问题描述】:

我想要一个 JButton,其图标(顶部)和文本(底部)都向左对齐。用户可以调整 Button 的大小,并且两者都应始终保持向左对齐,如下所示:

我试过了

// Text alignment
comp.setHorizontalAlignment(SwingConstants.LEFT);
// text position
comp.setVerticalTextPosition(SwingConstants.BOTTOM);
//set icon alignment?!
comp.setHorizontalTextPosition(SwingConstants.CENTER);

但这是我的结果(图标始终相对于文本保持居中!):

有什么想法吗?

【问题讨论】:

    标签: java swing alignment jbutton


    【解决方案1】:
    • 您可以使用<br> 标记将JButton 文本与<html> 标记一起拆分为多行。
    • 另一种常见的方法是通过设置LayoutManagerJButton 上放置多个JLabel

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    public final class ButtonTextAlignmentTest {
      private Component makeUI() {
        Icon icon = UIManager.getIcon("FileView.directoryIcon");
        String text = "The text aligned to the left";
    
        String html = String.format("<html><img src='%s'/><br/>Html: %s", makeIconUrl(icon), text);
        JButton button1 = new JButton(html);
    
        JLabel iconLabel = new JLabel(null, icon, SwingConstants.LEADING);
        JLabel textLabel = new JLabel("Layout: " + text);
        JButton button2 = new JButton();
        button2.setLayout(new GridLayout(0, 1));
        button2.add(iconLabel);
        button2.add(textLabel);
    
        JPanel p = new JPanel();
        p.add(button1);
        p.add(button2);
        return p;
      }
    
      private static String makeIconUrl(Icon icon) { // Create a dummy URL for testing
        try {
          File file = File.createTempFile("dummy", ".png");
          file.deleteOnExit();
          BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
          Graphics2D g2 = bi.createGraphics();
          icon.paintIcon(null, g2, 0, 0);
          g2.dispose();
          ImageIO.write(bi, "png", file);
          return file.toURI().toURL().toString();
        } catch (IOException ex) {
          return "";
        }
      }
    
      public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          frame.getContentPane().add(new ButtonTextAlignmentTest().makeUI());
          frame.setSize(320, 240);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
        });
      }
    }
    

    【讨论】:

    • 非常感谢@aterai!带有布局的选项 2 正是我所需要的。我不认为解决方案太容易了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2012-02-16
    相关资源
    最近更新 更多