2010-05-05 92 views
0

我想建立一個小表來顯示約會。 這是我到目前爲止。也許你可以給我一個暗示我做錯了什麼,或者走哪條路。Java Swing:如何使用JTable工作?

  public class AppointmentTable extends JFrame{ 


     public static void main(String[] args) { 
      JTable table = new JTable(new AppointmentTableModel(10, 6, new ArrayList<Appointment>())); 
      JScrollPane scrollPane = new JScrollPane(table); 
      table.setFillsViewportHeight(true); 
      AppointmentTable frame = new AppointmentTable(); 
      frame.add(scrollPane); 
      frame.setVisible(true); 
     } 
    public class AppointmentTable extends JFrame{ 


    public static void main(String[] args) { 
     JTable table = new JTable(new AppointmentTableModel(10, 6, new ArrayList<Appointment>())); 
     JScrollPane scrollPane = new JScrollPane(table); 
     table.setFillsViewportHeight(true); 
     AppointmentTable frame = new AppointmentTable(); 
     frame.add(scrollPane); 
     frame.setVisible(true); 
    } 
    } 

    public class AppointmentTableModel extends AbstractTableModel { 
     private int columns; 
     private int rows; 
     ArrayList<Appointment> appointments; 

     public AppointmentTableModel(int columns, int rows, 
       ArrayList<Appointment> appointments) { 
      this.columns = columns; 
      this.rows = rows; 
      this.appointments = appointments; 
     } 

     @Override 
     public int getColumnCount() { 

      return columns; 
     } 

     @Override 
     public int getRowCount() { 

      return rows; 
     } 

     @Override 
     public Object getValueAt(int rowIndex, int columnIndex) { 

      return appointments.get(rowIndex).getByColumn(columnIndex); 
     } 
    } 

public class Appointment { 

    private Date date; 
    private Sample sample; 
    private String comment; 
    private ArrayList<Action> history; 

    public Appointment(Date date, Sample sample, String comment) { 
     this.date = date; 
     this.sample = sample; 
     this.comment = comment; 
     this.history = new ArrayList<Action>(); 
    } 

    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; 
    } 

} 
public class Action { 
String action; 

public Action(String act){ 
    this.action=act; 
} 

} 
+0

有人可以給你的最好的建議(但這不是你的代碼的問題的直接答案)將是使用GlazedLists(開源),將爲您提供模型。 請注意,對於Appointment類(使用get/set方法)而不是使用將GUI(表中的列索引)與業務(約會數據)混合在一起的getByColumn(),這是很好的做法。 – jfpoilpret 2010-05-06 05:40:03

回答

1

首先,模型的getRowCount()方法不正確,應該是

public int getRowCount() { 
    return appointments.size(); 
} 

然後,你傳遞一個空的約會列表中你的模型,所以表顯示了什麼!

JTable table = new JTable(new AppointmentTableModel(10, 6, new ArrayList<Appointment>())); 

在創建表之前用一些數據初始化您的列表。