7

Is there a method for a combobox in Java that will center the items in the combobox? I tried this but it didn't work:

myCombobox.setAlignmentY(CENTER_ALIGNMENT);

Thanks!

JimmyPena
  • 8,694
  • 6
  • 43
  • 64
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
  • There is a better answer here [How to let the content in JComboBox display in the center?](http://stackoverflow.com/questions/12084188/how-to-let-the-content-in-jcombobox-display-in-the-center) – Stéphane Bruckert May 28 '15 at 15:40

2 Answers2

18

Try this link: How to Use Combo Boxes (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

class ComboBoxRenderer extends JLabel
                   implements ListCellRenderer {
  public ComboBoxRenderer() {
    setOpaque(true);
    setHorizontalAlignment(CENTER);
    setVerticalAlignment(CENTER);
  }
  //. . .

or

((JLabel)comboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
aterai
  • 9,658
  • 4
  • 35
  • 44
5

You have look at Renderers concept, described about in the JTable tutorial on Oracles pages, thic concept is similair for JComboBox, JList, JTable and JTree, in the Renderer you can centering desired text

mKorbel
  • 109,525
  • 20
  • 134
  • 319