- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to center align the items of a JComboBox in Java?
A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener and an ItemListener when the user actions on a combo box. By default, items in the JCombobox are left-aligned, we can also change to center alignment by using the setHorizontalAlignment(DefaultListCellRenderer.CENTER) method of DefaultListCellRenderer class.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxAlignmentTest extends JFrame { private JComboBox comboBox; private DefaultListCellRenderer listRenderer; public JComboBoxAlignmentTest() { setTitle("JComboBoxAlignment Test"); setLayout(new FlowLayout()); Object[] items = new Object[] {"item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7"}; comboBox = new JComboBox(items); add(comboBox); listRenderer = new DefaultListCellRenderer(); listRenderer.setHorizontalAlignment(DefaultListCellRenderer.CENTER); // center-aligned items comboBox.setRenderer(listRenderer); setSize(375, 250); setResizable(false); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String []args) { new JComboBoxAlignmentTest(); } }
Output
- Related Articles
- How to display the items in a JComboBox in Java
- Align items to center not working in SAPUI5
- How to Align Navbar Items to Center using Bootstrap 4?
- How can we sort the items of a JComboBox in Java?
- Align gathered items in the center in Bootstrap 4
- Usage of CSS align-items property center value
- How to display the different font items inside a JComboBox in Java?
- How to add items in a JComboBox on runtime in Java
- Align single rows of items in the center with Bootstrap 4
- How can we set the border to JComboBox items in Java?
- Align flex items at the center of the container with CSS
- Align gathered items in the center on different screens in Bootstrap 4
- Align flex items in the center on different screen sizes in Bootstrap
- Align single rows of items in the center on different screens in Bootstrap 4
- How to center align component using BoxLayout with Java?

Advertisements