How to let the content in JComboBox display in the center?
Asked Answered
R

2

9

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);
Reamonn answered 23/8, 2012 at 3:6 Comment(0)
K
14

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; 
Kissner answered 23/8, 2012 at 3:22 Comment(2)
I'm glad you got to that before I (foolishly) suggested HTML formatting. Now I can pretend I was never going to say that. ;)Sophey
I'd go further than 'much simpler'. Your answer is better classified as 'correct approach'. HTML formatting is a hack.Sophey
H
1
((JLabel)jComboBox1.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

Try This

Horan answered 13/8, 2017 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.