2013-01-11 134 views
1

我有三個文件,TopicData,TopicView,TopicTableModel。我的程序使用數據庫中的值顯示一個表。現在,當我點擊一行時,行的索引被打印出來。 我想修改代碼,以便打印來自我的數據庫的topicID。 topicID的值存儲在ArrayList中,但未顯示在表中,因此我無法使用JTable.getValueAt()。JTable:選擇一行時從數據庫中獲取值

請告訴我如何修改我的代碼。提前致謝。

的更多信息:

  1. TopicData從一個ArrayList數據庫並存儲它需要的數據。

  2. 然後將ArrayList傳遞給TopicTableModel,使數據適合在JTable中顯示。

  3. TopicView創建一個JTable並接受TopicTableModel來生成JTable。

TopicData.java

public class TopicData { 
int id; 
String name; 
String date; 
String category; 
String user; 

public TopicData(){ 
} 

public TopicData(int id, String name, String date, String category, String user) { 
    this.id = id; 
    this.name = name; 
    this.date = date; 
    this.category = category; 
    this.user = user; 
} 



public TopicData(String name, String date, String category, String user) { 
    this.name = name; 
    this.date = date; 
    this.category = category; 
    this.user = user; 
} 

public int getId() { 
    return id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getDate() { 
    return date; 
} 

public void setDate(String date) { 
    this.date = date; 
} 

public String getCategory() { 
    return category; 
} 

public void setCategory(String category) { 
    this.category = category; 
} 

public String getUser() { 
    return user; 
} 

public void setUser(String user) { 
    this.user = user; 
} 


public ArrayList<TopicData> getTopicList(){ 
    ArrayList<TopicData> topicList = new ArrayList<TopicData>(); 
    ResultSet rs = null; 
    DBController db = new DBController(); 
    db.setUp("myDatabase"); 
    String dbQuery = "SELECT topicID, topicName, topicDate, topicCategory, topicUser FROM topicTable ORDER BY topicDate"; 

    rs = db.readRequest(dbQuery); 

    try{ 
     while(rs.next()){ 
      int id = rs.getInt("topicID"); 
      String name = rs.getString("topicName"); 
      String date = rs.getString("topicDate") ; 
      String category = rs.getString("topicCategory"); 
      String user = rs.getString("topicUser"); 

      TopicData topic = new TopicData (id, name, date, category, user); 
      topicList.add(topic); 
     } 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    db.terminate(); 
    return topicList; 
} 

TopicTableModel.java

public class TopicTableModel extends AbstractTableModel { 

private static final long serialVersionUID = 1L; 
private int rowCount, colCount; 
private String[] columnNames = {"Name", "Date", "User"}; 
private Object [][] data; 

public TopicTableModel(ArrayList<TopicData> listOfObjects) { 
    rowCount = listOfObjects.size(); 
    colCount = columnNames.length; 
    data = new Object[rowCount][colCount]; 

    for (int i = 0; i < rowCount; i++) { 
     //Copy an ArrayList element to an instance of MyObject 
     TopicData topic = (listOfObjects.get(i)); 
     data[i][0] = topic.getName();    
     data[i][1] = topic.getDate(); 
     data[i][2] = topic.getUser(); 
    }    
} 

@Override 
public int getColumnCount() { 
    // TODO Auto-generated method stub 
    return colCount; 
} 

@Override 
public int getRowCount() { 
    // TODO Auto-generated method stub 
    return rowCount; 
} 

@Override 
public String getColumnName(int col) { 
    return columnNames[col]; 
} 

@Override 
public Object getValueAt(int rowIndex, int columnIndex) { 
    // TODO Auto-generated method stub 
    return data[rowIndex][columnIndex]; 
} 

@Override 
public boolean isCellEditable(int rowIndex, int colIndex) { 
    return false; //Disallow the editing of any cell 
} 

} 

TopicView.java

private JTable getTable() { 
    if (table == null) { 
     TopicData topic= new TopicData(); 
     TopicTableModel tableModel = new TopicTableModel(topic.getTopicList()); 
     table = new JTable(tableModel); 

     table.setShowGrid(false); 
     table.setFillsViewportHeight(true); 
     table.setBounds(173, 87, 456, 263); 
     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
     table.getTableHeader().setReorderingAllowed(false); 
     table.getTableHeader().setResizingAllowed(false); 
     table.getColumnModel().getColumn(0).setPreferredWidth(500); 

     ListSelectionModel rowSM = table.getSelectionModel(); 
     rowSM.addListSelectionListener(new ListSelectionListener() { 
      public void valueChanged(ListSelectionEvent e) { 
       //Ignore extra messages. 
       if (e.getValueIsAdjusting()) return; 

       ListSelectionModel lsm = (ListSelectionModel)e.getSource(); 
       if (lsm.isSelectionEmpty()) { 
        System.out.println("No rows are selected."); 
       } 
       else { 
        int selectedRow = lsm.getMinSelectionIndex(); 
        System.out.println("Row " + selectedRow + " is now selected."); 
       } 
      } 
     }); 
    } 
    return table; 
} 

回答

3

實際上,你的一切權利在你的鼻子。

您只需更改TableModel,以便保留ArrayList而不是將該列表轉換爲Object[][]

像這樣的東西(可能有一些錯字的問題):

public class TopicTableModel extends AbstractTableModel { 

private static final long serialVersionUID = 1L; 
private int rowCount, colCount; 
private String[] columnNames = {"ID", "Name", "Date", "User"}; 
private List<TopicData> listOfObjects; 
public TopicTableModel(ArrayList<TopicData> listOfObjects) { 
    this.listOfObjects = listOfObjects; 
} 

@Override 
public int getColumnCount() { 
    return columnNames.length; 
} 

@Override 
public int getRowCount() { 
    return listOfObjects.size(); 
} 

@Override 
public String getColumnName(int col) { 
    return columnNames[col]; 
} 

@Override 
public Object getValueAt(int rowIndex, int columnIndex) { 
    TopicData data = listOfObjects.get(rowIndex); 
    switch(columnIndex) { 
     case 0: 
      return data.getId(); 
     case 1: 
      return data.getName(); 
     case 2: 
      return data.getDate(); 
     case 3: 
      return data.getUser(); 
    } 
    return null; 
} 

@Override 
public boolean isCellEditable(int rowIndex, int colIndex) { 
    return false; //Disallow the editing of any cell 
} 

} 

副作用:你需要讓你的TopicDataSerializable如果你使用Java序列化(或者利用Serializable其他技術)

+0

我認爲AmuletxHeart想要打印的ID在println語句,在TopicView.java,而不是你做了添加ID列表。 – rob

+0

我剛剛使用這個並刪除「return data.getId();」。我現在可以從數據庫中獲取ID,而不必在桌面上顯示ID。謝謝。 – AmuletxHeart

+0

這個答案仍然不正確,因爲它增加了另一列而不是解決問題中提出的問題。 – rob

4

你這樣做是艱難的。不必將TopicData轉換爲數組,只需讓TableModel直接讀取TopicData對象的ArrayList,使每個TopicData對應一行。

TopicTableModel.java:

import java.util.ArrayList; 

import javax.swing.table.AbstractTableModel; 

public class TopicTableModel extends AbstractTableModel { 

private static final long serialVersionUID = 1L; 
private String[] columnNames = {"Name", "Date", "User"}; 
private ArrayList<TopicData> data; 

public TopicTableModel(ArrayList<TopicData> listOfObjects) { 
    data = listOfObjects; 
} 

@Override 
public int getColumnCount() { 
    return columnNames.length; 
} 

@Override 
public int getRowCount() { 
    return data.size(); 
} 

@Override 
public String getColumnName(int col) { 
    return columnNames[col]; 
} 

@Override 
public Object getValueAt(int rowIndex, int columnIndex) { 
    switch (column) { 
    case 0: 
     return data.getName(); 
    case 1: 
     return data.getDate(); 
    case 2: 
     return data.getUser(); 
    default: 
     throw new ArrayIndexOutOfBoundsException(); 
    } 
} 

@Override 
public boolean isCellEditable(int rowIndex, int colIndex) { 
    return false; //Disallow the editing of any cell 
} 

public TopicData getTopic(int row) { 
    return data.get(row); 
} 

} 

有一些小的修改TopicView.java,你現在可以得到TopicData對於選擇的行並打印其ID。

TopicView.java:

import javax.swing.JTable; 
import javax.swing.ListSelectionModel; 
import javax.swing.event.ListSelectionEvent; 
import javax.swing.event.ListSelectionListener; 


public class TopicView { 
    JTable table; 

    private JTable getTable() { 
     if (table == null) { 
      TopicData topic= new TopicData(); 
      final TopicTableModel tableModel = new TopicTableModel(topic.getTopicList()); 
      table = new JTable(tableModel); 

      table.setShowGrid(false); 
      table.setFillsViewportHeight(true); 
      table.setBounds(173, 87, 456, 263); 
      table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
      table.getTableHeader().setReorderingAllowed(false); 
      table.getTableHeader().setResizingAllowed(false); 
      table.getColumnModel().getColumn(0).setPreferredWidth(500); 
      table.setDefaultRenderer(TopicData.class, new TopicDataTableCellRenderer()); 

      ListSelectionModel rowSM = table.getSelectionModel(); 
      rowSM.addListSelectionListener(new ListSelectionListener() { 
       public void valueChanged(ListSelectionEvent e) { 
        //Ignore extra messages. 
        if (e.getValueIsAdjusting()) return; 

        int row = table.getSelectedRow(); 
        if (row < 0) { 
         System.out.println("No rows are selected."); 
        } 
        else { 
         System.out.println("id " + tableModel.getTopic(row).getId() + " is now selected."); 
        } 
       } 
      }); 
     } 
     return table; 
    } 
} 
+0

我不會使用渲染器來選擇要顯示的數據。這會將您的TableModel(用於columnNames)和CellRenderer(如果有)與您的CellEditor一起收緊。 TableModel負責返回適當的數據。 –

+0

@rob錯了,請不要,您的代碼示例違反了幾條規則, – mKorbel

+0

@mKorbel,請您詳細說明一下嗎? – rob

相關問題