【问题标题】:JButton: Icon left-aligned, text right-alignedJButton:图标左对齐,文本右对齐
【发布时间】:2012-10-13 04:40:45
【问题描述】:

我正在尝试创建一个带有图标和一些文本的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();
    }
 }

}

有谁知道将图标放在左端并在图标和文本(或文本右对齐)之间留出一些空间的方法?

【问题讨论】:

    标签: java swing icons alignment jbutton


    【解决方案1】:

    【讨论】:

    • 它确实适用于setHorizontalAlignment(SwingConstants.LEFT)
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      尝试在按钮属性中将边距设置为小于默认值, 然后将 iconTextGap 设置为最右边的水平位置

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-19
        • 2012-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多