JButton со значком (вверху) и текстом (внизу), выровненным по левому краю - PullRequest
2 голосов
/ 06 апреля 2020

Я бы хотел, чтобы кнопка JButton была выровнена по левому краю, а значок (вверху) и текст (внизу). Размер кнопки может быть изменен пользователем, и оба должны всегда оставаться выровненными по левому краю, например:

enter image description here

Я пробовал это

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

но это мой результат (значок всегда остается в центре по отношению к тексту!):

enter image description here

Есть идеи?

1 Ответ

3 голосов
/ 06 апреля 2020
  • Вы можете использовать тег <br>, чтобы разбить текст JButton на несколько строк вместе с тегами <html>.
  • Другой распространенный способ - поместить несколько JLabel s на JButton путем установки LayoutManager.

screenshot

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);
    });
  }
}
...