如何在 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;
   }
}

輸出

更新日期:2019 年 7 月 30 日

346 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.