如何將 Java 中 JComboBox 的專案居中對齊?
JComboBox 是 JComponent 類的一個子類,它是 文字欄位 和 下拉列表 的組合,使用者可以從中選擇一個值。當用戶對組合框執行操作時,JComboBox 可以生成 ActionListener、ChangeListener 和 ItemListener。預設情況下,JCombobox 中的項呈 左對齊,我們還可以透過使用 DefaultListCellRenderer 類的 setHorizontalAlignment(DefaultListCellRenderer.CENTER) 方法更改為 居中 對齊。
示例
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxAlignmentTest extends JFrame {
private JComboBox comboBox;
private DefaultListCellRenderer listRenderer;
public JComboBoxAlignmentTest() {
setTitle("JComboBoxAlignment Test");
setLayout(new FlowLayout());
Object[] items = new Object[] {"item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7"};
comboBox = new JComboBox(items);
add(comboBox);
listRenderer = new DefaultListCellRenderer();
listRenderer.setHorizontalAlignment(DefaultListCellRenderer.CENTER); // center-aligned items
comboBox.setRenderer(listRenderer);
setSize(375, 250);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String []args) {
new JComboBoxAlignmentTest();
}
}輸出
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP