简体   繁体   English

JTable:选择行时从数据库获取值

[英]JTable: get value from database when a row is selected

I have three files, TopicData, TopicView, TopicTableModel. 我有三个文件,TopicData,TopicView,TopicTableModel。 My program displays a table using values from a database. 我的程序使用数据库中的值显示一个表。 Right now, when I click on a row, the index of the row is printed. 现在,当我单击一行时,将打印该行的索引。 I want to modify the code such that the topicID from my database is printed instead. 我想修改代码,以便打印数据库中的topicID。 The value of topicID is stored in the ArrayList but not displayed in the table, so I can't use JTable.getValueAt(). topicID的值存储在ArrayList中,但不显示在表中,因此我不能使用JTable.getValueAt()。

Please advise on how to modify my codes. 请告知如何修改我的代码。 Thanks in advance. 提前致谢。

More information: 更多信息:

  1. TopicData takes the data from the database and stores it in an ArrayList. TopicData从数据库中获取数据并将其存储在ArrayList中。

  2. The ArrayList is then passed to TopicTableModel where the data is made suitable to be displayed in JTable. 然后,将ArrayList传递给TopicTableModel,使数据适合于在JTable中显示。

  3. TopicView creates a JTable and takes in the TopicTableModel to generate the JTable. TopicView创建一个JTable,并接受TopicTableModel生成JTable。

TopicData.java 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 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 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;
}

You're doing it the hard way. 您正在用困难的方式做。 Rather than converting TopicData into an array, just have your TableModel read the ArrayList of TopicData objects directly, so each TopicData corresponds to a row. 无需将TopicData转换为数组,只需让TableModel直接读取TopicData对象的ArrayList,因此每个TopicData都对应一行。

TopicTableModel.java: 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);
}

}

With a few minor modifications to TopicView.java, you can now get the TopicData for the selected row and print its ID. 通过对TopicView.java进行一些小的修改,您现在可以获取所选行的TopicData并打印其ID。

TopicView.java: 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;
    }
}

You actually have everything right under your nose. 实际上,您的一切都在您的鼻子底下。

All you need to do is change your TableModel so that it keeps the ArrayList instead of transforming that list into an Object[][] . 您需要做的就是更改TableModel ,使其保留ArrayList而不是将该列表转换为Object[][]

Something like this (may have some typo issues): 这样的事情(可能有错字问题):

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
}

}

Side effect: you will need to make your TopicData Serializable if you use Java serialization (or other technologies that take advantage of Serializable ) 副作用:如果您使用Java序列化(或其他利用Serializable技术),则需要使TopicData Serializable Serializable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM