How to diplay data of resultset using JTable?
JTable is component of java swing toolkit. JTable class is helpful in displaying data in tabular format. You can also edit data. JTable provide view of data, stored in database, file or in some object. It does not contain data. You can define your table as ?
JTable table=new JTable(data,columneName);
JTable constructors-
Here is a JTable populate with resultset example ?
import java.sql.*; import java.util.*; import javax.swing.*; import javax.swing.table.TableColumn; public class JTableResultSet { public static void main(String[] args) { Vector columnNames = new Vector(); Vector data = new Vector(); JPanel panel = new JPanel(); // try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root"); String sql = "Select name,address from user"; Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(sql); ResultSetMetaData metaData = resultSet.getMetaData(); int columns = metaData.getColumnCount(); for (int i = 1; i <= columns; i++) { columnNames.addElement(metaData.getColumnName(i)); } while (resultSet.next()) { Vector row = new Vector(columns); for (int i = 1; i <= columns; i++) { row.addElement(resultSet.getObject(i)); } data.addElement(row); } resultSet.close(); statement.close(); } catch (Exception e) { System.out.println(e); } JTable table = new JTable(data, columnNames); TableColumn column; for (int i = 0; i < table.getColumnCount(); i++) { column = table.getColumnModel().getColumn(i); column.setMaxWidth(250); } JScrollPane scrollPane = new JScrollPane(table); panel.add(scrollPane); JFrame frame = new JFrame(); frame.add(panel); //adding panel to the frame frame.setSize(600, 400); //setting frame size frame.setVisible(true); //setting visibility true } }
Description: - Vector class allows you to implement dynamic array of objects. That is the size of vector can grow or shrink as data is added or deleted.
JPanel is light weighted container used for general purpose. By default, panels have only their background. If can set colors and borders. test is database and user is table in test. First create connection to database.
ResultSetMetaData is used here to take information about the types and properties of columns in resultset object.
JTable table = new JTable(data, columnNames); //Creating object of JTable JscrollPane is used for providing the facility of scrolling.It is light weight component of swing.
JScrollPane scrollPane = new JScrollPane(table) //Here we are adding facility of scrolling into our table.
Ads