2013-10-28 33 views

回答

13

之前有人說:「你可以將渲染器設置爲JComboBox中它可以是一個JLabel JLabel的有#setHorizo​​ntalAlignment(JLabel.RIGHT) 「

是的,默認的renederer是JLabel,因此您不需要創建自定義渲染器。你可以使用:

((JLabel)comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT); 
+0

+1,你的回答比我的好,謝謝你的提供。 – UDPLover

+0

Idk ...我認爲更好的答案仍然是你的兩個答案的組合。特別是,您的答案對我更有用,因爲我使用自己的自定義渲染器。另一方面,我可以看到如果你只是在模型中使用普通的字符串數組(或者對於組合框中的對象使用toString()就足夠好),那麼這樣做會更有用。 – searchengine27

6

好了,你可以用ListCellRenderer做的,是這樣的:

import java.awt.Component; 
import java.awt.ComponentOrientation; 
import javax.swing.DefaultListCellRenderer; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JList; 
import javax.swing.SwingUtilities; 

public class ComboboxDemo extends JFrame{ 
    public ComboboxDemo(){ 
     JComboBox<String> comboBox = new JComboBox<String>(); 
     comboBox.setRenderer(new MyListCellRenderer()); 
     comboBox.addItem("Hi"); 
     comboBox.addItem("Hello"); 
     comboBox.addItem("How are you?"); 

     getContentPane().add(comboBox, "North"); 
     setSize(400, 300); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    private static class MyListCellRenderer extends DefaultListCellRenderer { 
     @Override 
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
      Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 
      component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 
      return component; 
     } 
    } 

    public static void main(String [] args){ 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new ComboboxDemo().setVisible(true); 
      } 
     }); 
    } 
} 
+0

謝謝梅拉曼 –

+0

我不能選擇方向*中心*!只從左到右,從右到左 – shareef

0

這個工作對我好,短

comboFromDuration.setRenderer(new DefaultListCellRenderer() { 
      @Override 
      public void paint(Graphics g) { 
       setHorizontalAlignment(DefaultListCellRenderer.CENTER); 
       setBackground(Color.WHITE); 
       setForeground(Color.GRAY); 
       setEnabled(false); 
       super.paint(g); 
      } 
     }); 

,避免每次油漆的制定者(圖形)調用,你也可以使用匿名的構造塊:

comboFromDuration.setRenderer(new DefaultListCellRenderer() { 
    { 
     setHorizontalAlignment(DefaultListCellRenderer.CENTER); 
     setBackground(Color.WHITE); 
     setForeground(Color.GRAY); 
     setEnabled(false); 
    } 
}); 
相關問題