繁体   English   中英

JButton:图标左对齐,文本右对齐

[英]JButton: Icon left-aligned, text right-aligned

我正在尝试创建一个带有图标和一些文本的JButton 我的问题是我希望图标左对齐并且文本右对齐(没有必要右对齐,但我不希望文本粘在图标上)。

我自己无法做到这一点,我尝试了一个略有不同的解决方案。 我使用iconTextGap在图标和文本之间创建了一些空间,原则上工作得很好,但是当我创建多个按钮时,它们都具有最宽的宽度,图标不再位于左侧(除了文本最长的按钮)。

我提供了一个代码来证明:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.File;
import java.net.MalformedURLException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;


public class Main{

 private JFrame frame;
 private JPanel buttonPanel;
 private GridBagConstraints constraints;

 public Main() throws MalformedURLException{

    frame = new JFrame();

    buttonPanel = new JPanel();
    frame.add(buttonPanel);

    buttonPanel.setLayout(new GridBagLayout());
    constraints = new GridBagConstraints();

    constraints.insets = new Insets(5, 5, 3, 5);
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.gridx = 0;
    constraints.gridy = 0;


    String[] text = { "some Text", "this text is longer" };

    for (int i = 0; i < text.length; i++) {
        JButton button= new JButton(text[i], new ImageIcon(new File("icon.png").toURI().toURL()));
        button.setAlignmentX(SwingConstants.WEST);
        button.setIconTextGap(30);
        button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 10));


        buttonPanel.add(button, constraints);
        constraints.gridy++;
    }

    frame.pack();
    frame.setVisible(true);


}

 public static void main(String[] args){
    try {
        new Main();
    } catch (Exception e) {
        e.printStackTrace();
    }
 }

}

有没有人知道如何在左端使用图标并在图标和文本之间留出一些空格(或文本右对齐)?

此问题的经典解决方案是使用具有布局的其他面板,该布局可以对齐诸如BorderLayout组件。 然后将按钮和标签放在其中,并使用相应的布局对齐方式。 打包或验证框架。

尝试将margin设置为小于按钮属性中的默认值,然后设置iconTextGap以使其位于最右侧的水平位置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM