, , JTable, , .
, , , , SimpleDateFormat, .
:
public class DateControl extends JPanel {
@SuppressWarnings("unchecked")
private JComboBox<String>[] combos = new JComboBox[3];
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
final int ranges[][] = {{2012,2050},{1,12},{1,31}};
public DateControl() {
super();
combos[0] = new JComboBox<String>();
combos[1] = new JComboBox<String>();
combos[2] = new JComboBox<String>();
for (int i = 0; i<combos.length; i++)
for (int j = ranges[i][0]; j<ranges[i][1]; j++)
combos[i].addItem((j<9?"0":"")+Integer.toString(j));
this.setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
for (JComboBox<String> c: combos) {
c.setUI(new BasicComboBoxUI() {
protected JButton createArrowButton() {
return new JButton() {
public int getWidth() {
return 0;
}
};
}
});
this.add(c);
}
this.setBorder(BorderFactory.createRaisedBevelBorder());
setDate(new Date());
}
public DateControl(Date date) {
this();
setDate(date);
}
public void setDate(Date d) {
String[] date = df.format(d).split("/");
for (int i=0;i<combos.length; i++)
combos[i].setSelectedItem(date[i]);
}
public Date getDate() {
String str = combos[0].getSelectedItem()+"/"+combos[1].getSelectedItem()+"/"+combos[2].getSelectedItem();
Date ret = null;
try {
ret = df.parse(str);
} catch (ParseException e) {e.printStackTrace();}
return ret;
}
}
, :
class DateCellEditor extends AbstractCellEditor implements TableCellEditor {
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
private DateControl dateControl;
public DateCellEditor() {
dateControl = new DateControl();
}
@Override
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
Date d = new Date();
try {
Object str = table.getValueAt(row, column);
if (str!=null)
d = df.parse((String)str);
} catch (ParseException e) {
e.printStackTrace();
}
dateControl.setDate(d);
return dateControl;
}
@Override
public Object getCellEditorValue() {
return df.format(dateControl.getDate());
}
}
The new cell editor can be used in the table columns as follows:
TableColumn c = myTable.getColumnModel().getColumn(0);
c.setCellEditor(new DateCellEditor());
I must remind you that this is the "Editor" cell, it will be displayed only when the cell is under the editor. The date value will be displayed as a normal Renderer cell as a simple string with the format yyyy / MM / dd.
I hope all this helps someone :)
source
share