gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:13:33 28 4
gpt4 key购买 nike

我正在尝试创建一个带有图标和一些文本的 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 - JButton:图标左对齐,文本右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13027223/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com