2013-06-03 175 views
0

我在我的應用程序中使用JComboBox,我想增加填充。我的組合框中的所有初始內容都與左邊界非常接近,所以我想填充它以使它看起來有點清晰。如何填充組合框?

這是一些示例代碼,我在應用程序中使用:

jPanelPatientInfo.add(jComboBoxNation, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, 
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 10, 0, 0), 0, 0)); 

回答

1

給你的組件面板上的更多的空間,最簡單的辦法是添加邊框面板。它看起來像您正在使用的GridBagLayout這樣的代碼會是這樣的:

JPanel panel = new JPanel(new GridBagLayout()); 
panel.addBorder(new EmptyBorder(10, 10, 10, 10)); 
panel.add(component1, constraints); 

現在,如果你在不同行,他們將全部縮進10個像素添加組件。

+0

感謝我知道了。 –

0

嘗試在組合框調用setPrototypeDisplayValue。這將根據使用的文本量設置寬度。正如鏈接文檔中提到的那樣,如果不存在,那麼它會根據每個元素的大小使用首選寬度。

2

我假設你想增加內(清單部分)的填充。提問時你需要更具體。

這裏有一種方法來墊JComboBox的內部。

import java.awt.Component; 

import javax.swing.DefaultListCellRenderer; 
import javax.swing.JLabel; 
import javax.swing.JList; 
import javax.swing.ListCellRenderer; 
import javax.swing.border.Border; 
import javax.swing.border.EmptyBorder; 

public class BorderListCellRenderer implements ListCellRenderer { 

    private Border insetBorder; 

    private DefaultListCellRenderer defaultRenderer; 

    public BorderListCellRenderer(int rightMargin) { 
     this.insetBorder = new EmptyBorder(0, 2, 0, rightMargin); 
     this.defaultRenderer = new DefaultListCellRenderer(); 
    } 

    @Override 
    public Component getListCellRendererComponent(JList list, Object value, 
      int index, boolean isSelected, boolean cellHasFocus) { 
     JLabel renderer = (JLabel) defaultRenderer 
       .getListCellRendererComponent(list, value, index, isSelected, 
         cellHasFocus); 
     renderer.setBorder(insetBorder); 
     return renderer; 
    } 

} 

然後,你使用這樣的類。 @ camickr

JComboBox comboBox = new JComboBox(elements); 
comboBox.setRenderer(new BorderListCellRenderer(20)); 
+0

謝謝@ Gilbert Le Blanc:我通過引用您的重要方法得到了解決方案。 –