2012-10-23 80 views
3

我試圖創建一個帶有圖標和一些文本的JButton。我的問題是,我希望圖標左對齊,文本右對齊(不需要右對齊,但我不希望文本粘在圖標上)。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(); 
    } 
} 

} 

有誰知道的方法有在左端的圖標,並有文字右對齊圖標和文本之間的一些空間(或)?

回答

1

經典解決這個問題使用有alows對準部件,如BorderLayout佈局附加面板。然後將其中的按鈕和標籤與相應的佈局對齊。打包或驗證幀。

1

嘗試設置餘量較小則默認值按鈕屬性, 然後設置iconTextGap有它最右邊的水平位置