3

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

}

左端にアイコンを配置し、アイコンとテキスト (またはテキストを右揃え) の間にスペースを空ける方法を知っている人はいますか?

4

3 に答える 3

6

JButton#setHorizo​​ntalTextPositionとJButton #setHorizo​​ntalAlignmentをご覧ください

そして、それが役立つかもしれないという理由だけでJButton#setVerticalTextPositionJButton#setVerticalAlignment

于 2012-10-23T09:30:42.693 に答える
1

この問題に対する古典的な解決策は、 などのコンポーネントを整列できるレイアウトを持つ追加のパネルを使用することBorderLayoutです。次に、対応するレイアウト配置でボタンとラベルをその中に配置します。フレームをパックまたは検証します。

于 2012-10-23T09:33:07.747 に答える
1

ボタンのプロパティで margin をデフォルト値よりも小さい値に設定してから、iconTextGap を設定して右端の水平位置にします。

于 2013-03-25T07:13:21.590 に答える