如何在 Java 中右对齐 ComboBox 中的文本
要右对齐 JComboBox 中的文本,请使用以下代码
ComponentOrientation.RIGHT_TO_LEFT
以下是对齐 ComboBox 中文本的示例
示例
import java.awt.Component; import java.awt.ComponentOrientation; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JList; public class SwingDemo extends JFrame { public SwingDemo() { JComboBox<String> combo = new JComboBox<String>(); combo.setRenderer(new MyListCellRenderer()); combo.addItem("One"); combo.addItem("Two"); combo.addItem("Three"); combo.addItem("Four"); combo.addItem("Five"); getContentPane().add(combo, "North"); setSize(600, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { new SwingDemo().setVisible(true); } } class MyListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); c.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); return c; } }
输出
广告