提供一個可編輯的下拉框,預置 9 種常見日期時間格式模板,用戶可選擇或自行輸入模式(如 dd MMMMM yyyy),即時顯示格式化後的當前日期時間。輸入非法模式時顯示紅色錯誤提示。
public class ComboBoxDemo extends JPanel implements ActionListener {
private JLabel resultLabel;
private String currentPattern;
private JComboBox patternComboBox;
public ComboBoxDemo() {
// 1. 預置格式模板
String[] patterns = {
"dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
"yyyy.MM.dd G 'at' hh:mm:ss z", "EEE, MMM d, ''yy",
"h:mm a", "H:mm:ss:SSS", "K:mm a,z",
"yyyy.MMMMM.dd GGG hh:mm aaa"
};
currentPattern = patterns[0];
// 2. 可編輯 ComboBox
patternComboBox = new JComboBox<>(patterns);
patternComboBox.setEditable(true);
patternComboBox.addActionListener(this);
// 3. 結果顯示區
resultLabel = new JLabel(" ");
resultLabel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(5, 5, 5, 5)
));
// 4. 佈局組裝(BoxLayout 垂直堆疊)
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(createPromptPanel());
add(patternComboBox);
add(Box.createRigidArea(new Dimension(0, 10)));
add(createResultPanel());
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
reformat(); // 初始格式化
}
// ... 事件處理與格式化邏輯見下
}
@Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
currentPattern = (String) cb.getSelectedItem();
reformat();
}
private void reformat() {
Date now = new Date();
try {
SimpleDateFormat formatter = new SimpleDateFormat(currentPattern);
String formatted = formatter.format(now);
resultLabel.setForeground(Color.BLACK);
resultLabel.setText(formatted);
} catch (IllegalArgumentException ex) {
resultLabel.setForeground(Color.RED);
resultLabel.setText("Error: " + ex.getMessage());
}
}
| 輸入模式 | 輸出示例 |
|---|---|
dd MMMMM yyyy | 14 January 2025 |
yyyy.MM.dd G 'at' hh:mm:ss z | 2025.01.14 AD at 10:30:45 CST |
H:mm:ss:SSS | 10:30:45:123 |
非法模式 | Error: Illegal pattern character 'X' |
setEditable(true) 允許用戶自由輸入,配合預置選項兼顧效率與靈活性ActionListener 捕獲選擇/輸入完成事件,立即重新格式化IllegalArgumentException,以紅色文本友好提示,不拋出棧跡SimpleDateFormat 支持 Locale 參數,易擴展多語言Java 8+ 推薦使用 java.time.format.DateTimeFormatter 替代 SimpleDateFormat:線程安全、API 更豐富、支持時區規則更新。配合 LocalDateTime.now() 可無縫遷移。