Search code examples
javaswingalignmentjcomboboxrenderer

JComboBox how to show the right end of the item?


I have the following Java code:

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class EnumsRightVisible {

    public void show() {
        JFrame frame = new JFrame("Combo box");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] items = {"aaaaaaaaa__________zzzzzzzzz",
                          "aaaaaaaaa__________zzzzzzzzz",
                          "aaaaaaaaa__________zzzzzzzzz"};
        JComboBox combo = new JComboBox(items);
        combo.setPreferredSize(new Dimension(100,20));
        frame.add(combo, BorderLayout.CENTER);
        frame.setLocation(600, 100);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        EnumsRightVisible enumsRightVisible = new EnumsRightVisible();
        enumsRightVisible.show();
    }
}

Running it you can see that the visible text is left oriented.

Please note that this code does not solve my problem (it aligns the text to the right, but only when the combo box is expanded):

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

How can I display the right end of the text in the same window (...__zzzzzz)? Thanks in advance!


Solution

  • Use a custom renderer that uses FontMetrics to measure the String's width and does the ellipsis (...) manually. More info here: http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer