Reputation: 2652
Hello I am new to Java and I am practicing by creating a simple to do list app.
Everything works till now but I have a problem with 1 simple thing. How to print the values on my screen in a table form
To Do Date added
Delete nothing 1-1-2012
Delete something 2-2-2013
Delete test 3-2-2012
I already get every record in my console by doing a println
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
}
I have created this everything now with a MVC design but as you expect my VIEW is empty.. My question what is the best way to print this out on my JFrame with the help of the view?
Upvotes: 1
Views: 755
Reputation: 14806
You can't use System.out.println();
to print anything on frame. Use JTable
instead:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class Reshad {
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//Create frame
JFrame frame = new JFrame();
//Create table
JTable table = new JTable();
//Create table model (DefaultTableModel in this case)
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"To do","Date added"});
//set model
table.setModel(model);
//To populate table call this method from model:
model.addRow(new Object[]{"something","1-1-2012"});
//Create scroll pane
JScrollPane scrollPane = new JScrollPane(table);
//Add scroll pane to center of your frame
frame.add(scrollPane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Upvotes: 3
Reputation: 34657
Populate a DefaultTableModel, as in the following:
public class TodoModel extends DefaultTableModel {
public TodoModel(ResultSet rs) {
this.dataVector = new Vector<Vector<String>>();
for(rs.first();!rs.isAfterLast(); rs.next()) {
Vector<String> row = new Vector<String>();
row.add("Delete?");
row.add(rs.getString(1));
row.add(rs.getString(2));
this.dataVector.add(row);
}
this.columnIdentifiers = new Vector<String>();
this.columnIdentifiers.add("");
this.columnIdentifiers.add("To Do");
this.columnIdentifiers.add("Date added");
}
}
Pass an instance of this to your JTable constructor and you should be golden. Let me know how you get on.
Upvotes: 3