dis*_*992 0 java swing jtable cell
尝试为日期编写自己的单元格渲染器.以此为例:
class MyRenderer extends DefaultTableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable jtab, Object v, boolean selected, boolean focus, int r, int c){
JLabel rendComp = (JLabel) super.getTableCellRendererComponent(jtab, v, selected, focus, r, c);
SimpleDateFormat formatter=new SimpleDateFormat("dd.MM.yy", Locale.ENGLISH);
rendComp.setText(formatter.format(v));
System.out.println(formatter.format(v));
return rendComp;
}
}
class DateModel extends AbstractTableModel{
String colName[]={"Date"};
public int getRowCount(){
return 5;
}
public int getColumnCount() {
return 1;
}
public String getColumnName(int c){
return colName[c];
}
public Object getValueAt(int r, int c){
return Calendar.getInstance().getTime();
}
}
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table=new JTable(new DateModel());
table.setDefaultRenderer(Date.class, new MyRenderer());
JScrollPane pane=new JScrollPane(table);
frame.add(pane);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
但我的渲染器不能正常工作,并返回此:

当尝试格式化日期时,就像在我自己的单元格渲染器中一样,提示输出都很好.
在调试中没有得到getTableCellRendererComponent方法.
将此方法添加到DateModel类:
@Override
public Class<?> getColumnClass(int columnIndex) {
return Date.class;
}
Run Code Online (Sandbox Code Playgroud)
此方法可帮助JTable识别您为其提供的数据类型,并将数据与相应的渲染器相关联.JavaDoc说:
返回列中所有单元格值的最特定超类.JTable使用它来为列设置默认渲染器和编辑器.
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |