1

I want to display the data from MySQL in JTable but showed the last row from the table and more nothing. Help me, please. I understand that I have a problem because jt = new JTable(data, columns) each time create a new table for each row (deleting previous) but I can't find the right option.

public class Test2  extends JPanel {

    static final String USERNAME = "root";
    static final String PASSWORD = "root";
    static final String CONN_STRING = "jdbc:mysql://localhost:3306/mydbtest?useSSL=false";

    JTable jt;
    public Test2 () {

        try {
            Connection conn;
            conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
            Statement stmt = (Statement) conn.createStatement();
            String query = "Select title, season, episode from movie";
            ResultSet rs = stmt.executeQuery(query);

            rs.beforeFirst();

            while (rs.next()) {
                String title = rs.getString("Title");
                String season = rs.getString("Season");
                String episode = rs.getString("Episode");

            String[] columns = {"Title", "S", "E"};
            String[][] data = {{title, season, episode}};


            jt = new JTable(data, columns);
            };

            jt.setPreferredScrollableViewportSize(new Dimension(450, 63));
            jt.setFillsViewportHeight(true);

            JScrollPane jps = new JScrollPane(jt);
            add(jps);
        }
        catch (Exception er) {System.err.println(er);}
    }

    public static void main(String[] args) {
        JFrame jf = new JFrame();
        Test2 t = new Test2();
        jf.setTitle("Test");
        jf.setSize(500,500);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(t);
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Yevgen
  • 93
  • 1
  • 1
  • 8

2 Answers2

6

Your problem is here:

while (rs.next()) {
    String title = rs.getString("Title");
    String season = rs.getString("Season");
    String episode = rs.getString("Episode");

    String[] columns = { "Title", "S", "E" };
    String[][] data = { { title, season, episode } };

    jt = new JTable(data, columns); // *** you're making many JTables here!! ***
}

Each time the while loop loops, you create and discard a new JTable object. The exception is on the last time through the loop, the data from the last row of the result set is not discarded and is then displayed in final JTable created. To solve this, to display all of the data within the JTable, you need to collate all of your result set data within the while loop, and then add it to the JTable, and the easiest way to do this is to create a table model, here a simple DefaultTableModel, before the while loop, and populate it within each row of result set data within the while loop:

// create a table model with the appropriate column headers
// and with 0 rows (to start with)
String[] columnNames = {"Title", "Season", "Episode"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);

while (rs.next()) {
    String title = rs.getString("Title");
    String season = rs.getString("Season");
    String episode = rs.getString("Episode");

    // create a single array of one row's worth of data
    String[] data = { title, season, episode } ;

    // and add this row of data into the table model
    tableModel.addRow(data);
}

jt.setModel(tableModel); // place model into JTable

Or perhaps better, change the last line to:

jt = new JTable(tableModel); // to create a new JTable
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • The idea is very smart but now displaying error java.lang.NullPointerException. What a reason? – Yevgen Aug 27 '17 at 12:14
  • @Yevgen: that's a separate issue, one which you should debug. If you haven't done so, check the answers to the canonical question on this subject: [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it). – Hovercraft Full Of Eels Aug 27 '17 at 12:16
  • @Yevgen: The heuristic for debugging a NullPointerException is almost always the same: You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. – Hovercraft Full Of Eels Aug 27 '17 at 12:16
  • @Yevgen: ah, do you call `new JTable(...)` in the updated code? You need to do this. Perhaps change `jt.setModel(tableModel);` to `jt = new JTable(tableModel);` – Hovercraft Full Of Eels Aug 27 '17 at 12:25
  • Yes, the reason was here. I now begin to understand the causes of error NPE thanks to you. – Yevgen Aug 27 '17 at 12:41
1

Try This... You Can Do it easily....

public final void EmployeeGridView(){

    try{

        Connection conn = DBConn.connect();
        PreparedStatement ps = conn.prepareStatement("Select * from empdetails");
        ResultSet rs=ps.executeQuery();
        DefaultTableModel tm = (DefaultTableModel)jTable1.getModel();
        tm.setRowCount(0);

        while(rs.next()){

            Object o[] = {rs.getInt("EMPID"),rs.getString("FirstName"),rs.getString("LastName"),rs.getString("Designation"),rs.getString("NIC"),rs.getString("PhoneNO"),rs.getString("DOB"),rs.getString("Address"),rs.getString("Gender")};
            tm.addRow(o);



        }


    }
    catch(Exception e){

        JOptionPane.showMessageDialog(null,"Error in Employee Grid View..... "+e);
    }



}