java – JTable中的JSpinner(Time)
作者:互联网
我试图将JSpinner实现到JTable的时间,它在第一次看起来是preaty goot但是在失去了单元格的焦点后,编辑的单元格被设置为“Thu Jan 01 time UTC 1970”时间正在被设置正确.如何从时间中删除日期?
这是我的洞SpinnerEditor.class,添加了一些评论.
代码:
public SpinnerEditor(String timeFormat) {
super(new JTextField());
// Default Time I want to Display (1 Hour)
Time date = new Time(3600000);
SpinnerDateModel timeModel = new SpinnerDateModel(date, null, null,Calendar.MINUTE);
spinner = new JSpinner(timeModel);
editorDate = new JSpinner.DateEditor(spinner, timeFormat);
spinner.setEditor(editorDate);
editorDate = ((JSpinner.DateEditor)spinner.getEditor());
// println result : "Thu Jan 01 01:00:00 UTC 1970"
System.out.println(editorDate.getTextField().getValue());
textField = editorDate.getTextField();
textField.addFocusListener( new FocusListener() {
public void focusGained( FocusEvent fe ) {
System.err.println("Got focus");
//textField.setSelectionStart(0);
//textField.setSelectionEnd(1);
SwingUtilities.invokeLater( new Runnable() {
public void run() {
if ( valueSet ) {
textField.setCaretPosition(1);
}
}
});
}
public void focusLost( FocusEvent fe ) {
}
});
textField.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent ae ) {
stopCellEditing();
}
});
}
// Prepares the spinner component and returns it.
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column
) {
if ( !valueSet ) {
spinner.setValue(value);
}
SwingUtilities.invokeLater( new Runnable() {
public void run() {
textField.requestFocus();
}
});
return spinner;
}
public boolean isCellEditable( EventObject eo ) {
System.err.println("isCellEditable");
if ( eo instanceof KeyEvent ) {
KeyEvent ke = (KeyEvent)eo;
System.err.println("key event: "+ke.getKeyChar());
textField.setText(String.valueOf(ke.getKeyChar()));
valueSet = true;
} else {
valueSet = false;
}
return true;
}
// Returns the spinners current value.
public Object getCellEditorValue() {
return spinner.getValue();
}
public boolean stopCellEditing() {
System.err.println("Stopping edit");
// after stopcellEditing is called the TextField is being set with the wrong values (Thu Jan 01 01:00:00 UTC 1970)
super.stopCellEditing();
try {
if( editorNumeric!=null)
{
editorNumeric.commitEdit();
spinner.commitEdit();
}
if( editorDate!=null)
{
SimpleDateFormat lFormat = new SimpleDateFormat("HH:mm");
textField.setText((spinner.getValue() != null) ? lFormat.format(spinner.getValue()) : "");
}
} catch ( java.text.ParseException e ) {
JOptionPane.showMessageDialog(null,
"Invalid value, discarding.");
}
return true;
}
解决方法:
你让编辑和渲染器感到困惑.编辑器是在编辑单元格时显示的小部件.当不再编辑单元格时,单元格渲染器用于“绘制”单元格.这一切都在this paragraph中解释过.我真的建议你阅读它,因为它清楚地解释了如何执行表格渲染.
你应该做的是,为所涉及的列使用Custom CellRenderer,以便它使用你的日期格式化程序.
有关单元格编辑器和单元格渲染器的更多信息,请查看this tutorial.
标签:jspinner,java,date,swing,jtable 来源: https://codeday.me/bug/20190928/1826181.html