How to center items in a Java combobox

AndroidDev picture AndroidDev · Jun 13, 2012 · Viewed 15.4k times · Source

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!

Answer

aterai picture aterai · Jun 13, 2012

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);