2010-05-05 87 views
1

我該如何讓每個列的JTable顯示特定的東西?如何在JTable中設置特定的列設置?

我可以使用多個列的對象嗎?我想有一個顯示日期(dd.mm.yyyy)和另一個顯示時間(hh:mm)的列,但是現在它只顯示Date對象的字符串表示形式。

public class AppointmentTableModel extends AbstractTableModel { 
    ... 
    @Override 
    public Object getValueAt(int rowIndex, int columnIndex) { 
     return appointments.get(rowIndex).getByColumn(columnIndex); 
    } 
} 

public class Appointment { 
    ... 
    public Object getByColumn(int columnIndex) { 
     switch (columnIndex) { 
      case 0: return date; 
      case 1: return date; 
      case 2: return sample; 
      case 3: return sample; 
      case 4: return history; 
      case 5: return comment; 
     } 
     return null; 
    } 
} 

回答

3

您可以設置爲兩列具體的渲染器,一個將採取Date對象,並將其格式化爲一個日期字符串,另一個將採取Date對象並將其格式化爲時間字符串。

對日期渲染的例子見this tutorial

+0

+1:這比我的解決方案更優雅:) – 2010-05-05 18:32:43

1

你唯一需要改變的是你的getByColumn

你只需要申請的兩套不同格式case 0case 1例如。


您可以使用此一SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); 
// ... 
case 0: return dateFormat.format(date); 
case 1: return timeFormat.format(date);