我有一台带DateFormat的JFormattedTextField。格式为"ddMMyy“。此格式允许快速input.On焦点丢失我希望字段中的文本更改为LocalDate,因为这样更容易阅读:
输入:"200295“。使用getValue()转换为LocalDate将得到1995年2月20日的LocalDate。这一切都很好,文本是"1995-02-25“(LocalDate.toString())。
当字段失去焦点时,我希望显示在字段中的文本更改为LocalDate.toString(),而不是字段的实际值从200295/ 20日开始更改。
有没有什么方法可以让文本覆盖在字段上而不是改变它的值/文本?
到目前为止,我一直在想:
主类:
public class FormatDateTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TheFrame();
}
});
}
}Frame类:
public class TheFrame extends JFrame{
JPanel panel;
JPanel textPanel;
JFormattedTextField dateField;
JButton button;
JTextArea textArea;
DateFormat format;
public TheFrame() {
button = new JButton("click");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//temporarily crates a date to be converted.
Date date = (Date) dateField.getValue();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// sends the different values of the textarea
textArea.append("The value: " + dateField.getValue() + "\n");
textArea.append("the Date: " + date.toString() + "\n");
textArea.append("the LocalDate: " + localDate.toString() + "\n");
}
});
//Sets the text to the localDate for prettyness
button.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
Date date = (Date) dateField.getValue();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
dateField.setText(localDate.toString());
}
@Override
public void focusGained(FocusEvent arg0) {
dateField.setText("");
}
});
textArea = new JTextArea();
panel = new JPanel();
textPanel = new JPanel();
panel.setLayout(new BorderLayout());
textPanel.setLayout(new BorderLayout());
//datefield and format
format = new SimpleDateFormat("ddMMyy");
dateField = new JFormattedTextField(format);
textPanel.add(textArea,BorderLayout.CENTER);
panel.add(dateField,BorderLayout.NORTH);
panel.add(button, BorderLayout.CENTER);
add(panel,BorderLayout.NORTH);
add(textPanel,BorderLayout.CENTER);
pack();
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}发布于 2015-08-31 05:23:12
使用带有CardLayout的JPanel。在其中放入两个组件-输入字段和格式正确的组件(我假设JTextField就可以了)。将焦点放在其中任何一个上,将格式化的字段放在前面(使用CardLayout上的方法),并让用户输入数据。在焦点丢失时,处理该值(记住处理错误!)而且,如果解析正常,请将格式正确的值放在JTextField中,并将其放在前面。
--基于备注的更新--
轻量级解决方案:对格式化部分使用JLabel而不是JTextField。记得给setFocusable(true)打电话。
更轻量级的:子类JTextField。覆盖paintComponent,以便: a)当组件被聚焦时,将绘图委托给super。b)当没有聚焦时,自己绘制格式正确的文本。
https://stackoverflow.com/questions/32300630
复制相似问题