Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to right align the text in a JCombobox

I want to have a JComboBox with right align. how can I do that? someone before said "You can set a renderer to the JComboBox which can be a JLabel having JLabel#setHorizontalAlignment(JLabel.RIGHT)" but I don't know how can I do that?

like image 658
Naeem Baghi Avatar asked Oct 28 '13 17:10

Naeem Baghi


2 Answers

someone before said "You can set a renderer to the JComboBox which can be a JLabel having JLabel#setHorizontalAlignment(JLabel.RIGHT)"

Yes, the default renederer is a JLabel so you don't need to create a custom renderer. You can just use:

((JLabel)comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
like image 173
camickr Avatar answered Sep 17 '22 17:09

camickr


Well, you can do with ListCellRenderer, like this:

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);
            }
        });
    }
}
like image 30
nullptr Avatar answered Sep 20 '22 17:09

nullptr