简体   繁体   中英

Use swing controls in other class Java

EDIT : I am now able to access the tableData by making a MainFrame.java instance in my Database.java but it's not working. The rows is not added.

I am new to Java and still learning. I am making a desktop app with mySQL interaction. I have a JTable which is declared in MainFrame.java like so

public javax.swing.JTable tableData;

Then I have a Database.java which has all the methods if interacting to the database. Then in Database.java I have function

private void writeResultSet(ResultSet resultSet) throws SQLException {
    MainFrame mainframe = new MainFrame();
    DefaultTableModel model = (DefaultTableModel)mainframe.tableData.getModel();
    // resultSet is initialised before the first data set
    while (resultSet.next()) {
        String id = resultSet.getString("id");
        String name = resultSet.getString("name");
        model.addRow(new Object[]{id, name});
    }
}

Then on that function I want to access tableData JTable because I will append rows in there based from the resultSet . Is it possible? Or what is the best way?

best approach would be a book ^^

use the table model to access table data, best practice is to use DefaultTableModel

DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);

now you can easily add/remove data from your table by simply adding/removing data to your table model

now you can add your data to your table by querying your ResultSet

ResultSet rs; // i really hope you already have performed your query
while(rs.next() ){
    String str = rs.getString(...); //your Code here

    //now you can add your data to the model:
    model.addRow(new Object[]{str});
}

honestly - this is only a 10-line-tutorial, i think you have to do some more practise! but dont feel embarresed, i think you will learn quickly ^_^

It would be better to fetch the result set and update the tableData in MainFrame class only.

Also if you want to update this in Database.java class you need to have instance of MainFrame.java here. And would not be recommended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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