- 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
Advertisements