About JTable.

Hello , Can anyone please give me a hint on how to use the ResultSet to populate the JTable from the database , I have my ResultSet ready but I'm confused about how to use it , do I have to create a String Array to hold each row , and another to hold the column names , or are there special methods in the ResultSet Class that I can use ?
I created an inner class to be the Table Model for my MyTable class , but here the IDE underlines the columnName,rset variables in the methods ( getColumnCount() , getRowCount() ...) saying : "Cannot find symbol" ...Why so?
class MyTableModel extends AbstractTableModel {
public MyTableModel(){
    String columnName;
    ResultSet rset = MyTable.useConnAndGetData();
    try
         ResultSetMetaData rsmd = rset.getMetaData();
         int numColumns = rsmd.getColumnCount();
        // Get the column names; column indices start from 1
        for (int i=1; i<numColumns+1; i++) {
            columnName = rsmd.getColumnName(i);
            // Get the name of the column's table name
            //String tableName = rsmd.getTableName(i);
    catch (SQLException e)
        System.out.println(e.getMessage());
        public int getColumnCount() {
            return columnName.getMetaData();
        public int getRowCount() {
            return rset.getFetchSize();
        public String getColumnName(int col) {    // confused about this..
            return columnName[col];
        public Object getValueAt(int row, int col) {
            return rset[row][col];
}Thanks...

Okay , I got the answer from another thread , but now when I run this code the IDE says "running" and nothing is happening , no excpetions thrown or anything ,
the progress bar just keeps on going , Why is that happening ?
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
public class MyTable extends JPanel {
public MyTable()
final ResultSetTableModel model = new ResultSetTableModel();
JTable myTable = new JTable(model);
myTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
myTable.setFillsViewportHeight(true);
JScrollPane pane = new JScrollPane(myTable);
JPanel mainPanel = new JPanel();
mainPanel.add(pane);
mainPanel.setOpaque(true);
    JFrame frame = new JFrame("My Table Demo");
    frame.setSize(400, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // frame.setContentPane(new MyTable());
    frame.pack();
    frame.add(mainPanel);
    try
    model.setResultSet(useConnAndGetData());
    catch(SQLException e)
    e.getMessage();
  private static Connection getConnection()
    Connection con = null;
     try
        String driverName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName);   //registering JDBC Driver
        String serverName = "localhost";
        String portNumber = "1521";
        String sid = "mydb";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String user = "fundinfo";
        String pw = "tadapps";
        con = DriverManager.getConnection(url, user, pw);
     catch (ClassNotFoundException e) {
                                    System.out.println(e.getMessage());
                                    System.exit(0);
     catch (SQLException e) {
                              System.out.println(e.getMessage());
                              System.exit(0);
    return con;
    public static ResultSet useConnAndGetData()
        Connection con = getConnection();
    try
         Statement stmt = con.createStatement();
         String select = "select title,year,price from movie order by year";
         ResultSet rows = stmt.executeQuery(select);
         return rows;
    catch(SQLException e) {
             System.out.println(e.getMessage());
        return null;
    public static void main (String[] args)
                try
                  new MyTable().setVisible(true);
                catch (Exception ex)
                    System.err.println(ex.getMessage());
                    ex.printStackTrace();
class ResultSetTableModel extends AbstractTableModel {
    // Currently displayed result set
    private ResultSet rs;
    // Associated metadata
    private ResultSetMetaData rsMeta;
    // Column count
    private int columnCount;
    // Column nmaes
    private final Vector<String> columnNames = new Vector<String>();
    // Vector of rows
    private final Vector<Object[]> cache = new Vector<Object[]>();
    /** Set new result set */
    public void setResultSet(ResultSet rs)
            throws SQLException
        if (this.rs != null)
            this.rs.close();
        cache.clear();
        // 'Cache' some metadata data
        rsMeta = rs.getMetaData();
        columnCount = rsMeta.getColumnCount();
        columnNames.clear();
        for(int col = columnCount; col > 0; col--) {
            columnNames.add(rsMeta.getColumnName(col));
        // 'Cache' new resultest data
        while(rs.next()) {
            Object rowData[] = new Object[columnCount];
            for(int col = columnCount; col > 0; col--)
                rowData[col - 1] = rs.getObject(col);
            cache.add(rowData);
        // Reload table structure
        fireTableStructureChanged();
    /** Close result set */
    public void close() throws SQLException {
        rs.close();
    /** ## TableModel interface ## */
    public String getColumnName(int column) {
        return columnNames.get(column);
    /** ## TableModel interface ## */
    public Object getValueAt(int rowIndex, int columnIndex) {
        Object[] row = cache.get(rowIndex);
        return row[columnIndex];
    /** ## TableModel interface ## */
    public int getRowCount() {
        return cache.size();
    /** ## TableModel interface ## */
    public int getColumnCount() {
        return columnCount;
}

Similar Messages

  • Best practices about JTables.

    Hi,
    I'm programming in Java since 5 months ago. Now I'm developing an application that uses tables to present information from a database. This is my first time handling tables in Java. I've read Sun's Swing tutorial about JTable, and several information on other websites, but they limit to table's syntax and not in best practices.
    So I decided what I think is a proper way to handle data from a table, but I'm not sure that is the best way.Let me tell you the general steps I'm going through:
    1) I query employee data from Java DB (using EclipseLink JPA), and load it in an ArrayList.
    2) I use this list to create the JTable, prior transformation to an Object[][] and feeding this into a custom TableModel.
    3) From now on, if I need to search an object on the table, I search it on the list and then with the resulting index, I get it from the table. This is possible because I keep the same row order on the table and on the list.
    4) If I need to insert an item on the table, I do it also on the list, and so forth if I'd need to remove or modify an element.
    Is the technique I'm using a best practice? I'm not sure that having to keep synchronized the table with the list is the better way to handle this, but I don't know how I'd deal just with the table, for instance to efficiently search an item or to sort the table, without doing that first on a list.
    Are there any best practices in dealing with tables?
    Thank you!
    Francisco.

    Hi Joachim,
    What I'm doing now is extending DefaultTableModel instead of implementing AbstractTableModel. This is to save implementing methods I don't need and because I inherit methods like addRow from DefaultTableModel. Let me paste the private class:
    protected class MyTableModel extends DefaultTableModel {
            private Object[][] datos;
            public MyTableModel(Object[][] datos, Object[] nombreColumnas) {
                super(datos, nombreColumnas);
                this.datos = datos;
            @Override
            public boolean isCellEditable(int fila, int columna) {
                return false;
            @Override
            public Class getColumnClass(int col) {
                return getValueAt(0, col).getClass();
        }What you are suggesting me, if I well understood, is to register MyTableModel as a ListSelectionListener, so changes on the List will be observed by the table? In that case, if I add, change or remove an element from the list, I could add, change or remove that element from the table.
    Another question: is it possible to only use the list to create the table, but then managing everything just with the table, without using a list?
    Thanks.
    Francisco.

  • A question about JTable .setValueAt(...)

    hi, I write some code which use the Table to represent the data fetched from MS-ACCESS.
    the problem is about the UpdateObject(...) method which is in the implement of the AbstractTableModel method setAtValue(). when transfered OBJECT TYPE is java.lang.String, I can't get the correct result in the JTable view.
    by the way, I use java2SE 6 Beta version
    my code is as below, could somebody point me out my problem
    public class MyTableModel extends AbstractTableModel {
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        /** Creates a new instance of MyTableModel */
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
    /* table model retrieve the Class type of a column method here*/
    public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
    //method of update database and JTable after user edited a table cell
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);    //the JTable row index is start from 0,so plus 1
                    rs.updateObject(columnIndex+1, aValue);//the JTable column index is start from 0, so plus 1
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
        } when the column type is about java.lang.String, the cell's result is incorrect, it looks like "[B@1f8f72f" and database can't update.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Yes, I have implemented them all.
    I paste them all now. thank all here, first.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.AbstractTableModel;
    * @author qhj
    public class MyTableModel extends AbstractTableModel {
        /** Creates a new instance of MyTableModel */
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
        public int getRowCount() {
            try {
                rs.last();
                return rs.getRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public int getColumnCount() {
            try {
                return rsmd.getColumnCount();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public Object getValueAt(int rowIndex, int columnIndex) {
            try {
                rs.absolute(rowIndex+1);
                return rs.getObject(columnIndex+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return null;
        public String getColumnName(int column){
            try {
                return rsmd.getColumnName(column+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return "N/A";
        public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return true;
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);
                    rs.updateObject(columnIndex+1, aValue);
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            fireTableDataChanged();
    }

  • Question about JTable...

    Hi people,
    I have a question about class JTable of Java and how can i add dynamic content to it. More specific i would like
    to create a table which has a dynamic content at its rows and columns (etc i will use a method which will generate
    dates of 1/02/05 to 1/03/05 format and i will add them as titles in the row section of my table and in the column
    section i will add times of the day divided in quarters like 00.00 00.15 00.30 00.45..... just like a calendar) Any ideas????

    Use the DefaultTableModel. It has addRow and addColumn methods.

  • Need help about JTable

    Can some one please help me about how to sort a column in a JTable when click on the the column title

    Can't tell you off the top of my head but I know you will find it here...
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#selection

  • Confused about JTable::setCellEditor

    Hi
    I'm a bit confused about what JTable::setCellEditor does.
    I wrote my own TableCellEditor implementation which can handle dates and other additional stuff and which can decide for itself what type of editing control to display.
    Now I want my table to use only this editor.
    However using
    tblTest.setCellEditor( MyEditorInstance );didn't work. But when I used
    tblTest.getColumnModel().getColumn(0).setCellEditor( MyEditorInstance );
    tblTest.getColumnModel().getColumn(1).setCellEditor( MyEditorInstance );
    tblTest.getColumnModel().getColumn(2).setCellEditor( MyEditorInstance );for every column it worked fine.
    How can I avoid setting the default editor manually and set it for all columns?
    As always, any help is greatly appreciated
    Marcus

    I agree with you, its not clear what that method does.
    If you don't set a cell editor to a column then JTable determines which of its default editors to use based on the Class returned from the getColumnClass() method, which is defined by the JTable and the TableModel. If you are using the default implementation of this method then it will always return Object as the class type. You can use your editor as the default by doing:
    table.setDefaultEditor(Object.class, MyEditorInstance);

  • Simple requirement about JTABLE

    hello friends,
    Learning JTable...
    Somewhere while searching i found a java file named QueryTableModel.java
    which has extended the AbstractTableModel. I used it but was unable to format
    Double (for amount etc) and Date. It alway returns String class and not Date, Double
    etc. I dont know why .....
    can somebody help me, guide me so that using cell renderers i can format the
    data being populated in the JTable, as per my need?
    thanks in advance
    anandaScreen

    The TableBasic class is about as simple as it gets for displaying a table. You add whatever objects you want to the TableModel and then override the getColumnClass() method to tell the table what type of data is in each column. The table will choose the appropriate renderer for the data type:
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class TableBasic extends JFrame
         public TableBasic()
              String[] columnNames = {"Date", "String", "Integer", "Boolean"};
              Object[][] data =
                   {new Date(), "A", new Integer(1), Boolean.TRUE },
                   {new Date(), "B", new Integer(2), Boolean.FALSE},
                   {new Date(), "C", new Integer(9), Boolean.TRUE },
                   {new Date(), "D", new Integer(4), Boolean.FALSE}
              JTable table = new JTable(data, columnNames)
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableBasic frame = new TableBasic();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Please help me..about JTable ..Please please

    I have a JTable and tried to set the width for its columns..but I dont
    know why it doesnt work..here's my codes:
    Please help me..thanks..
    import javax.swing.table.TableColumn;
    import javax.swing.table.*;
    JTable table = new JTable();
    //a method{
    DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
    public boolean isCellEditable(int row, int col){   return false; }
    table.setModel(model);
    TableColumn column = tblEntryList.getColumnModel().getColumn(0);
    column.setPreferredWidth(25);
    column = tblEntryList.getColumnModel().getColumn(1);
    column.setPreferredWidth(100);

    I did feed the data into the table..you can tell by looking at my codes..
    please show me..dont know why it doesnt work.
    I just have my tlbEntrylist declared as
    String[][] rowData = new String[0][];
    String[] columnNames = {"Cnt","Name","Text"};
    JTable tblEntryList = new JTable(rowData, columnNames);
    //then whenever I click a a button , will call loadTableEntries()
    to remove all row data and refresh with new data..so I have to
    set new new model for this table.
    private void loadTableEntries()
    tblEntryList.removeAll(); // Remove old entries
    Object[][] rowData = new Object[entries.length][3];
    //feed the table of new data
    for(int i=0;i<rowData.length;i++)
    rowData[0] =new Integer(entries[i].getTimesUsed());
    rowData[i][1] = entries[i].getName();
    rowData[i][2] = entries[i].getText();
    String[] columnNames = {"Cnt","Name","Text"};
    // Create a new model and load it with new values
    DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
    public boolean isCellEditable(int row, int col){   return false; }
    tblEntryList.setModel(model);
    TableColumn col = tblEntryList.getColumn(tblEntryList.getModel().getColumnName(0));
    col.setPreferredWidth(10);
    col = tblEntryList.getColumn(tblEntryList.getModel().getColumnName(1));
    col.setPreferredWidth(25);
    I dont know what i'm doing wrong here but it ddint work..

  • Please help about JTable...thanks

    HI everyone!
    Please tell me how to write a ACTIONLISTENER for a JTABLE?
    JTABLE table;
    Object[][] myArray = {  {"Mary", new Integer(5)},
    {"Alison", new Integer(3)},
    {"Angela", new Integer(1)}
    String[] columnNames = {"First Name", "Scores"};
    table = new JTable(myArray, columnNames);
    how do you write a actionlistener for a JTable?
    thanks

    One of the things I'd recommend is reading the tutorial on "How to use Tables" at the Sun website. Unless you have a button or something like that on the container the JTable is in, I don't think you want an ActionListener. One of the things you can do is set up a ListSelectionListener. It allows you to do something when a value changes in the ListSelectionModel. When you select rows in a JTable, a ListSelectionModel is created. Retrieve the ListSelectionModel from your JTable, and add a listener to it, something like:
    JTable runTable = new JTable(yourTableModel);
    runTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); // set mode
    //or use default
    ListSelectionModel rowSM = runTable.getSelectionModel();
    rowSM.addListSelectionListener(new TimeSelectionListener());
    class TimeSelectionListener implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    // ...//no rows are selected
    } else {
    ... // If some rows are selected, do something here!!!
    I hope this helps.

  • URGENT!!!  Help me about JTable, Please.

    I have a JTable, it is contained into JScrollPane and I show JScrollPane on a Dialog. When I use JTable, I have some problem :
    + How can I change the data in a JTable, change quantity of columns, quantity of rows (example : I can increase or decrease quantity of columns or rows at the run time).

    if you have the JDK documentation installed than search for JTable, you will get everything on tables there, no offence but it sounds really stupid that you cant get what you want coz according to your question, i have seen more than enough information.
    asrar

  • Problem about jtable and database

    The problem is that when i clicked the button to save the values of textfields and text area, although the table is supposed to show the new list of datas from the db, it adds the new data list to the end of the first list. I have to list one old and one new in jtable.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * DatabaseConnection.java
    * Created on 28.Aðu.2008, 11:24:52
    package databaseconnection;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    * @author ARAGORN
    public class DatabaseConnection extends javax.swing.JFrame {
        /** Creates new form DatabaseConnection */
        public DatabaseConnection() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Students", "admin", "1837837");
                st = con.createStatement();
            } catch (Exception e) {
                System.out.println("Database Connection Error!");
            try {
                ResultSet rs = st.executeQuery("SELECT*FROM studentdata");
                while (rs.next()) {
                    Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
                    row.addElement(rowValues);
                data = new Object[row.size()][7];
                for(int i=0;i<row.size();i++){
                    data=(Object[]) row.get(i);
    } catch (Exception e) {
    System.out.println("reading error!");
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jSeparator1 = new javax.swing.JSeparator();
    jLabel2 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField3 = new javax.swing.JTextField();
    jTextField4 = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jTextField5 = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jTextField6 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowOpened(java.awt.event.WindowEvent evt) {
    formWindowOpened(evt);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(data,heading)
    jScrollPane1.setViewportView(jTable1);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Öðrenci Bilgileri", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
    jLabel1.setText("Öðrenci No : ");
    jLabel2.setText("Adý : ");
    jLabel3.setText("Sýnýf : ");
    jLabel4.setText("Soyad : ");
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane2.setViewportView(jTextArea1);
    jLabel5.setText("Adress : ");
    jLabel6.setText("Tel : ");
    jLabel7.setText("Þube : ");
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(22, 22, 22)
    .addComponent(jLabel1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(364, Short.MAX_VALUE))
    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(40, 40, 40)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel6)
    .addComponent(jLabel2)
    .addComponent(jLabel4)
    .addComponent(jLabel5))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addComponent(jTextField4)
    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
    .addGap(28, 28, 28)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel3)
    .addComponent(jLabel7))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
    .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)))
    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(49, 49, 49))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel1)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel2)
    .addComponent(jLabel3)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel4)
    .addComponent(jLabel7)
    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel5)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel6)
    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap())
    jButton1.setText("Kaydet");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Temizle");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    jButton3.setText("Çýk");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jButton1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton3)))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jButton1)
    .addComponent(jButton2)
    .addComponent(jButton3))
    .addGap(38, 38, 38))
    pack();
    }// </editor-fold>
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    System.exit(0);
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    jTextField1.setText("");
    jTextField2.setText("");
    jTextField3.setText("");
    jTextField4.setText("");
    jTextField5.setText("");
    jTextField6.setText("");
    jTextArea1.setText("");
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    st.executeUpdate("INSERT studentdata(Ogrenci_no,Ad,Soyad,Sinif,Sube,Adres,Tel) VALUES(" +
    Integer.parseInt(jTextField1.getText()) + ", '" +
    jTextField2.getText() + "', '" +
    jTextField4.getText() + "', " +
    Integer.parseInt(jTextField3.getText()) + ", '" +
    jTextField6.getText() + "', '" +
    jTextArea1.getText() + "', " +
    Integer.parseInt(jTextField5.getText()) +
    } catch (SQLException e) {
    System.out.println("Writing data Error!");
    try {
    ResultSet rs = st.executeQuery("SELECT * FROM studentdata");
    while (rs.next()) {
    Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
    row.addElement(rowValues);
    data = new Object[row.size()][7];
    for(int i=0;i<row.size();i++){
    data[i]=(Object[]) row.get(i);
    } catch (Exception e) {
    System.out.println("reading error!");
    jTable1.setModel(new MyTableModel());
    jTable1.setVisible(true);
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new DatabaseConnection().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration
    Connection con;
    Statement st;
    Vector row = new Vector();
    Object[][] data;
    Object[] heading = {"Öðrenci_No","Ad","Soyad","Sýnýf","Sube","Adres","Tel"};
    class MyTableModel extends AbstractTableModel{
    public int getColumnCount(){
    return heading.length;
    public int getRowCount(){
    return data.length;
    @Override
    public String getColumnName(int column){
    return heading[column].toString();
    public Object getValueAt(int row, int column){
    return data[row][column];
    public boolean isCellEditable(){
    return false;
    @Override
    public void setValueAt(Object value, int row, int column){
    data[row][column] = value;
    fireTableCellUpdated(row, column);
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    any one to help ?

  • Problem about JTable's DataVector probelm

    I'm writing a database program with JTable, I want to make a copy of the data content of the jtable before editing the values.
    I first get the TableModel of the table then get the DataVector out to clone a copy to a new Vector, but when I change the values in the table, the values in both Vector also changed.
    Can anyone tell me why this happen? I really need your help. Thanks!
    Code:
    originalTable = (DefaultTableModel)jTablePO.getModel();
    originalVector = (Vector) (orgtable.getDataVector().clone());

    You don't actually want to copy the contents of that Vector to another Vector. That's because the contents of the Vector consists of references to a bunch of objects. Copies of those references are actually references to the same objects. That's what you're seeing there.
    So you don't want just copies of the references in the Vector. You want the new Vector to contain references to copies of whatever the original Vector contained references to. And since in a JTable, those things you're cloning are themselves Vectors, you have the same problem again at this level.
    You need a deep copy of the Vector, is what it boils down to. You should be able to google for that phrase or for deep clone.
    Edit: Good, while I was typing all that in a form that I hoped wasn't too confusing, you were already taking my advice.
    Message was edited by:
    DrClap

  • URGENT!!! : About JTable

    I want to change all content of a Table (create by class JTable), then I will show the Table with new content(new datum). How can I do that?
    Please help me !!!
    Thanks.

    do you mean to refresh or so called "update" the table with new data???

  • URGENT !!! Help me about JTable.

    I want to make a program with swing. I use class JTable to show my datum and I have a problem :
    When I create an Object of class JTable (with a Vector , you can review constructor of JTable), I add it into a Scroll (JScrollPane class) and then I add whole into a Dialog (JDialog). My main problem is :
    - When Dialog is showed, it contained Table with ScrollPane. On Table, there is some datum and now, I want to clear old datum and show new datum on Table. How can I do that???
    Thanks !!!

    Instead of passing a Vector to your JTable constructor, do:
    // The second arg is the names of the columns.  Adjust the number and names as required.
    DefaultTableModel model = new DefaultTableModel(yourVector,
        new String[]{"Names", "For", "The", "Columns"});
    JTable table = new JTable(model);When you want to change the data:
    // 2nd are is the column names again.
    model.setDataVector(newData, new String[]{"New", "Column", "Names", "(or old ones)"});

  • Some questions about JTable formatting

    Hi everybody, I am currently developing a project using JTable. I found difficulty on modifying JTable cell width and setting style of JTableHeader?
    Does anybody have idea on that? Thanks.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables

Maybe you are looking for