我知道有一种简单的方法可以将JComboBox中的所有项居中,但我已经搜索了StackOverflow和整个网络,没有讨论如何仅将选定项居中.
为了清楚起见,当我从组合框中 Select 一项时,此框关闭列表并仅显示所选的项.我想要居中的就是这件衣服.
有没有办法做到这一点?
我知道有一种简单的方法可以将JComboBox中的所有项居中,但我已经搜索了StackOverflow和整个网络,没有讨论如何仅将选定项居中.
为了清楚起见,当我从组合框中 Select 一项时,此框关闭列表并仅显示所选的项.我想要居中的就是这件衣服.
有没有办法做到这一点?
这由渲染器控制.
当传递给渲染器的索引为-1时,将渲染选定的项.
您可以创建自定义呈现器并根据索引更改文本的对齐方式:
import java.awt.Component;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
public class ComboRenderer
{
public void makeUI()
{
JComboBox<String> comboBox = new JComboBox<>(new String[]{"A", "B", "C"});
comboBox.setRenderer(new BasicComboBoxRenderer()
{
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setHorizontalAlignment( index == -1 ? JLabel.CENTER : JLabel.LEFT );
return this;
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(comboBox);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(() -> new ComboRenderer().makeUI() );
}
}