0

Here's my code:

private void show(java.awt.event.ActionEvent evt) {
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "phone";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "school";
    try {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url + dbName, userName, password);
        PreparedStatement pStmt = conn.prepareStatement("SELECT * FROM contacts");
        ResultSet rs = pStmt.executeQuery();
        JFrame frame1 = new JFrame();
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame1.setSize(300, 150);
        frame1.setVisible(true);
        while (rs.next() == true) {

            Object rowData[][] = {{"Name"},
                {"Phone"}};
            Object columnNames[] = {"Column One", "Column Two"};
            JTable table = new JTable(rowData, columnNames);
            JScrollPane scrollPane = new JScrollPane(table);
            frame1.add(scrollPane, BorderLayout.CENTER);


        }
        rs.close();
        pStmt.close();
        conn.close();
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

I want to display the record in a separate window but its showing a blank screen. Any corrections suggested?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ankur
  • 1
  • 2
  • Is `rs.next()` _ever_ true? Note `if (rs.next())` is a sufficient predicate. – trashgod Jul 01 '11 at 18:55
  • @trashgod but still it shows a blank screen. – Ankur Jul 01 '11 at 18:58
  • @Ankur do you know if `SELECT * FROM contacts` returns any rows at all? Meaning do you know for sure that this table has rows? – Sai Jul 01 '11 at 19:04
  • 1
    @Ankur : *"Any corrections suggested?"* Add components to the `JFrame` then call `pack()` before calling `setVisible(true)`. Drop the call to `setSize()`. If that doesn't work for you 1) first check this works with hard coded data, & (if you cannot get that working) 2) post an [SSCCE](http://pscode.org/sscce.html) (rather than uncompilable code snippets). – Andrew Thompson Jul 01 '11 at 19:10
  • @Sai I did System.out.println too. – Ankur Jul 01 '11 at 19:17

4 Answers4

1
            Vector columnNames = new Vector();
            Vector data = new Vector();                 
            try{
            Connection conn = null;
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            conn = DriverManager.getConnection(
            "jdbc:oracle:thin:@localhost:1521:XE","yedal ","yedal121288");
            Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("");            
                ResultSetMetaData meta=rs.getMetaData();                
                int columns = meta.getColumnCount();
                for (int i = 1; i <= columns; i++) 
                {
                    columnNames.addElement( meta.getColumnName(i) );
                }
                while (rs.next()) 
                { 
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++)
                    {
                        row.addElement( rs.getObject(i) );
                    }   
                    data.addElement( row );
                }
                rs.close();
                stmt.close();
                } 
             catch (SQLException ex) { 
                ex.printStackTrace(); 
                } 
             t= new JTable(data, columnNames); t.setVisible(true);             
             TableColumn col; 
             for (int i = 0; i < t.getColumnCount(); i++) 
             {
                 col = t.getColumnModel().getColumn(i);
                 col.setMaxWidth(200);
             } 
             JScrollPane scrollPane = new JScrollPane(t);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
orcan
  • 11
  • 1
0

it is better to use a library file rs2xml.jar . include it into ur library

first create a connection with the database using jdbc. import this --> import net.proteanit.sql.DbUtils;

 String query ="select * from employee"; //let
 pst = conn.prepareStatement(query);

  rs = pst.executeQuery();
  s.append (QueryArea.getText()).append("\n");
  jTable.setModel(DbUtils.resultSetToTableModel(rs));

There will be an exception thrown in this ,so handle it by a try catch statement. if any problem with this u can ask.

0

You're creating multiple JTables in your while loop, I assume that's not what you're intending to do, and also you don't give them size. you must set the size of JTable with setPreferredSize or setSize method:

tblObj.setPreferredSize(new Dimension(300,400));

also you pass true to setFillsViewportHeight method for your table content to fill the view port.

Here's a link on how to use JTable:

How To Use JTable

Headshota
  • 21,021
  • 11
  • 61
  • 82
  • *"you must set the size of JTable with setSize method:"* -1 Rubbish. 1) It is rarely necessary to call `setSize()` & usually counter-productive. 2) The preferred size is more often used than the size. – Andrew Thompson Jul 01 '11 at 19:13
0

I suppose you see an exception java.lang.ArrayIndexOutOfBoundsException if you look into your console. The JTable is populated with a table model which has two columns but you construct it with an array with data of only one.

Please note since you set the frame to visible before this exception occurs, the frame is shown, the component is added to it but when swing tries to paint it it will fail.

If you replace your test data with e.g.

Object rowData[][] = { { "Name", "Phone" }, { "Name2", "Phone2" } };

it'll work (unless rs.next() is never true).

Howard
  • 38,639
  • 9
  • 64
  • 83
  • yeah, its showing the same, but how to insert data from database in JTable? – Ankur Jul 01 '11 at 19:36
  • @Ankur this is a completely different topic. You may find several options in the answers to ["How to fill data in a JTable with database?"](http://stackoverflow.com/questions/2192764/how-to-fill-data-in-a-jtable-with-database). – Howard Jul 01 '11 at 19:42