2013年9月6日 星期五

[Java] JComboBox/ComboBox 字體顯示置中 display in the center / 在下拉式選單中顯示置中 center align the text in the comboBox

最近遇到 java combox 需要在下拉式選單中把選項的字  置中 與 顯示出來也置中  如圖












如何達成圖上這個效果

直接來看一下片段代碼


////////////// 在下拉式選單中 顯示置中  代碼開始     (Code Start ) ///////////////////
.
.
import javax.swing.DefaultListCellRenderer;
.
.

 DefaultListCellRenderer dlcr = new DefaultListCellRenderer();  //set Jcombox 's text in the center
dlcr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);

JComboBox Box  = new JComboBox();
Box.setRenderer(dlcr);

////////////////在下拉式選單中 顯示置中  代碼結束      (Code End)///////////////////////



如果是 "顯示"出來想要置中   則再增加以下兩行

JTextField editor =  (JTextField)Box.getEditor().getEditorComponent();
editor.setHorizontalAlignment(JTextField.CENTER);

有問題歡迎討論







沒有留言:

張貼留言