Reputation: 167
I have a JList
on a panel.
How can I center align the text in the JList
?
I can't seem to find the settings anywhere for the model?
I have looked for align settings on the GUI but cant seem to find any there.
Upvotes: 4
Views: 12347
Reputation: 2634
All the answers seem outdated or at least they did not work for me, I solved like this:
list.setCellRenderer((list, project, index, isSelected, cellHasFocus) -> {
JLabel label = new JLabel(value.getName())
label.setHorizontalAlignment(JLabel.CENTER);
return label;
});
Upvotes: 0
Reputation: 285405
This has nothing to do with the model since it involves the view, the ListCellRenderer to be specific. One solution; get the renderer and set its horizontalAlignment to SwingConstants.CENTER. Assuming that you're not using a custom cell renderer you could for example do:
DefaultListCellRenderer renderer = (DefaultListCellRenderer) myJList.getCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
Upvotes: 13
Reputation: 1211
Try the following:
JList list = new JList(args);
DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
renderer.setHorizontalAlignment(JLabel.CENTER);
Upvotes: 5