Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let the content in JComboBox display in the center?

Currently I have this JComboBox, how can I get to center the content inside it?

String[] strs = new String[]{"15158133110", "15158133124", "15158133458"};
JComboBox com = new JComboBox(strs);
like image 213
SUN XIAOYU Avatar asked Aug 23 '12 03:08

SUN XIAOYU


People also ask

How do I center text in JComboBox?

By default, items in the JCombobox are left-aligned, we can also change to center alignment by using the setHorizontalAlignment(DefaultListCellRenderer.

What is the difference between JList and JComboBox?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

How do I make JComboBox not editable?

u can make ur jcombobox uneditable by calling its setEnabled(false). A JComboBox is unEditable by default. You can make it editable with the setEditable(boolean) command. If you are talking about enabled or disabled you can set that by the setEnabled(boolean) method.


2 Answers

You need to create a Renderer then apply it to the JComboBox

DefaultListCellRenderer dlcr = new DefaultListCellRenderer(); 
dlcr.setHorizontalAlignment(DefaultListCellRenderer.CENTER); 
com.setRenderer(dlcr); 

also import this,

import javax.swing.DefaultListCellRenderer; 
like image 81
Sean F Avatar answered Oct 12 '22 02:10

Sean F


((JLabel)jComboBox1.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

Try This

like image 27
Shinwar ismail Avatar answered Oct 12 '22 02:10

Shinwar ismail