Jtable column name

Hi frds,
I developed a JTable for my java application and it is working fine but I need some modifications which i'm unable to do.my JTable is actually linked with mysql database and the data in Jtable comes from the database.my requirement is when i change data in the JTable, the change must reflect in the database.can u plz help me out..

hi,
if you have taken the data from the database,this means that you have no problem with java database connectivity.to inform the database you have to run some sql commands.
http://www.cab.u-szeged.hu/local/doc/pgsql/sql-commands.html
in the previous link you will find the sql commands.
i think that you want update,so click the hyperlink with the name update.
if something wrong is going wrong let me know.

Similar Messages

  • JTable column names with custom model

    I'm having problems with column names in a JTable which uses a custom model. For some reason, the colums are being shown as A, B, C etc. The data, however, displays fine.
    This is the code which constructs the table.
    MyTableModel tableModel = new MyTableModel(myArrayList);
      myTable = new JTable(tableModel);
      myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      myTable.setFillsViewportHeight(true);This is the class, MyTableModel
    class MyTableModel extends AbstractTableModel {
            private ArrayList<Account> data;
            private String[] colNames = {"", "Name","Type","Group","Created","Modified"};
            public MyTableModel(ArrayList<Account> data) {
                this.data = data;
            public int getRowCount() {
                return data.size();
            public int getColumnCount() {
                return 6;
            public Object getValueAt(int row, int col) {
                Account account = (Account)data.get(row);
                switch(col) {
                    case 0:
                        return account.getIcon();
                    case 1:
                        return account.getName();
                    case 2:
                        return account.getType();
                    case 3:
                        return account.getGroup();
                    case 4:
                        return account.getDateCreated();
                    case 5:
                        return account.getDateModified();
                    default:
                        return "";
            public String getColumName(int index) {
             System.out.println("N:"+colNames[index]);
                return colNames[index];
        }When the table is displayed, nothing's displayed to the console, but I'd have thought getColumnName would print the current column name. Am I missing something obvious?

    Oh great. I'll go back under my rock.
    Thanks =)

  • JTable, column names not appearing!

    I am using the following code:
    Vector columnNames = new Vector();
            Vector data = new Vector();
            try
                //  Connect to the Database
                Common.Data.DataAccesser da = new Common.Data.DataAccesser();
                Connection connection = da.getConnection();
                //  Read data from a table
                String sql = "Select * from schedule1";
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery( sql );
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                //  Get column names
                for (int i = 1; i <= columns; i++)
                    columnNames.addElement( md.getColumnName(i) );
                //  Get row data
                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(Exception e)
                System.out.println( e );
            //  Create table with database data
            JTable table = new JTable(data, columnNames);
            jPanel2.setLayout(new java.awt.BorderLayout());
            jPanel2.add(table, BorderLayout.CENTER);I know its a bit messy, wat im tryin to do is add the table to the panel. the rows are showing perfectly but the column names do not show! Can anyone help?

    1) Please ask Swing questions in the Swing forum.
    2) Don't forget to specifically make the table header display. You do this by adding the table header to the jpanel in the borderlayout NORTH position, and you get the table header by calling getTableHeader. Have a look here for instance:
    http://forum.java.sun.com/thread.jspa?threadID=5235339&tstart=0

  • JTable Column Names Not Displaying

    Hi there
    I create a JTable by passing the JTable constructor my custom TableModel which extends AbstractTableModel.
    For column names I have a String[] containing the column names in my custom TavleModel and have coded the TableModel methods accordingly.
    For some reason when I run the code the table is displayed, but the column names are not!?!
    Any advance is appreciated!

    Sorted!
    After looking at sample code in the JTable tutorial, it seems the table likes/needs to be added to a JScrollPane, as once I did this the column headings started appearing.
    e.g. JScrollPane scrollPane = new JScrollPane(table);

  • Changing JTable column names

    I have a JTable where the user can right click on the table header to change what data is displayed. When the user selects different data to display, I would like to change the column name to reflect this. What is the best way to do this?
    TIA
    ZeroFK

    table.getColumnModel().getColumn(???).setHeaderValue(???).

  • WRAP JTable Column Name into 2 lines

    I have a JTable with a long column Name. Can I wrap the Column Name into multiple (2) lines.

    baskaraninfo wrote:> set the following to a table column,<html><body>Employee<br>Name</body></html>>The break tag got lost cos you didnt use the code tags
    <html><body>Employee<br>Name</body></html>

  • Easier way to set post-constructor JTable column names?

    I have a class that extends JTable. It also has a pair of inner classes that extend DefaultTableCellRenderer and AbstractTableModel so I can dynamicaly adjust the number of rows and their contents. That's not the problem - that part works fine. The problem is the column headers. My table doesn't currently have any but I want to add them.
    The column quantity is constant at 3 and should always be the same 3 Strings. It would be nice if I could use the JTable constructors that take a Vector or Object[] of column names from the start in my new class' constructor. But I don't think I can because at that point I don't know how many rows there will be or what they'll contain. Trying to set rowData to null just caused runtime exceptions.
    So the alternative seems to be to call setColumnModel() within the constructor, passing it a DefaultTableColumnModel. Which then requires I call addColumn() three times. Each time passing it a new TableColumn object. Each of which requires that I separately call setHeaderValue() after I construct it to set the header name. Am I right in that is the only way to do it? It just seems overly complex.

    I'll post a streamlined version of my class in case that will help...
    public class TotalsTable extends JTable
       private static int NUM_COLUMNS = 3;
       static final public String columnNames[] = {
             "Col Name 1", "Col Name 2", "Col Name 3"};
       protected Vector data = null;
       private TotalsModel tableModel;
       public TotalsTable()
          tableModel = new TotalsModel();
          setModel(tableModel);
          TableCellRenderer renderer = new TotalsCellRenderer();
          setDefaultRenderer(Object.class, renderer);
       public void updateTable(Vector pData)
          data = pData;
          tableModel.update();
       class TotalsCellRenderer extends DefaultTableCellRenderer
          public Component getTableCellRendererComponent
             (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
             super.getTableCellRendererComponent(table, value, isSelected,
                                                 hasFocus, row, column);
             if (column == 0) {
                setForeground(Color.blue);
             else {
                setForeground(Color.black);
             return this;
       class TotalsModel extends AbstractTableModel
          public TotalsModel()
             super();
          protected void update()
             fireTableStructureChanged();
           * Retrieves number of columns
           * (Necessary for AbstractTableModel implementation)
          public synchronized int getColumnCount()
             return NUM_COLUMNS;
          public synchronized int getRowCount()
             if (playerData == null)
                System.out.println("No rows found in table");
                return 0;
             else
                return playerData.size();
           * Returns cell information of a record at location row,column
           * (Necessary for AbstractTableModel implementation)
          public synchronized Object getValueAt(int row, int column)
             try
                MyObject p = (MyObject) data.elementAt(row);
                switch (column)
                   case 0:
                      return p.getName();
                   case 1:
                      return ("" + p.getDataItem2());
                   case 2:
                      return ("" + p.getDataItem3());
                   default:
                      System.out.println("getValueAt() Error: Invalid column");
             catch (Exception e)
                System.out.println("Exception in getValueAt(): " +
                                   e.getMessage());
             return "";
          public String getColumnName(int col)
             if (col < NUM_COLUMNS)
                return columnNames[col];
             else
                return "";
          public Class getColumnClass(int c)
             return getValueAt(0, c).getClass();
    }

  • JTable Column Names

    Hi, how can I change the names of the columns of a JTable that gets its data from a database;

    Thanks mate, but I cannot use this constructor since my table automaticaly gets its data (what you declare as rowData) from an external database.
    I found the solution to my problem to the next lines of code...
    JTable table = new JTable;
    TableColumnModel tcm = table.getColumnModel();
    TableColumn tc = tcm.getColumn(0);
    tc.setHeaderValue( "ABC" );
    thanks anyway

  • Can't get JTable column names to show

    Here are some extracts for some code that I wrote to create a simple JTable:
    columnNames = new Vector();
    columnNames.add("column1");
    columnNames.add("column2");
    columnNames.add("column3");
    rowData = new Vector();
    basic = new Vector();
    basic.add("SKY BASIC");
    basic.add("1");
    basic.add("?100");
    family = new Vector();
    family.add("SKY FAMILY");
    family.add("2");
    family.add("?200");
    rowData.add(basic);
    rowData.add(family);
    incomeTable = new JTable(rowData, columnNames);
    incomeTable.setPreferredScrollableViewportSize(new Dimension(1000, 150));When I do this the table appears on the GUI with all the required information in the table cells, except no Column headings appear.
    Any ideas what this might be?

    Or override the isCellEditable method of JTable:
            JTable table = new JTable( ... )
                public boolean isCellEditable(int row, int column)
                        return false;
            };

  • JTable - Help with column names and rowselection

    Hi,
    Is there anyone that can help me. I have successfully been able to load a JTable from an MS access database using vectors. I am now trying to find out how to hardcode the column names into the JTable as a string.
    Can anyone please also show me some code on how to be able update a value in a cell (from ''N'' to ''Y'') by double clicking on that row.
    How can I make all the other columns non-editable.
    Here is my code:
         private JTable getJTable() {
              Vector columnNames = new Vector();
    Vector data = new Vector();
    try
    // Connect to the Database
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // String url = "jdbc:odbc:Teenergy"; // if using ODBC Data Source name
    String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Documents " +
              "and Settings/Administrator/My Documents/mdbTEST.mdb";
    String userid = "";
    String password = "";
    Class.forName( driver );
    Connection connection = DriverManager.getConnection( url, userid, password );
    // Read data from a table
    String sql = "select * from PurchaseOrderView";
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery( sql );
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    // Get column names
    for (int i = 1; i <= columns; i++)
    columnNames.addElement( md.getColumnName(i) );
    // Get row data
    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(Exception e)
    System.out.println( e );
              if (jTable == null) {
                   jTable = new JTable(data, columnNames);
                   jTable.setAutoCreateColumnsFromModel(false);
                   jTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
                   jTable.setShowHorizontalLines(false);
                   jTable.setGridColor(java.awt.SystemColor.control);
                   jTable.setRowSelectionAllowed(true);
                   jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
                   jTable.setShowGrid(true);     
              return jTable;
         }

    this method has a default behavior to supply exactly what you're seeing: column names consisting of the capitalized letters, "A", "B", "C".Thanks Pete, had seen that but never really thought about it... about 10 days ago somebody needed to obtain Excel column names, I'd offered a rigorous solution and now see it would have been shorter and simpler (if a little heavier) to extend DefaultTableModel and provide the two additional methods needed (getOffsetCol and getColIndex).
    Not much of a difference in LOC but certainly more elegant ;-)
    Darryl

  • How do i change the color of a JTable's column names

    hai,
    i'm very new to java and trying to customize the look of a JTable.
    how do i change the color of a JTable's Column names. i know its very simple, i just couldn't figure out how to do it!!
    thanx in advance

    table.getTableHeader().setForeground(Color.RED);

  • JTable can't display column names and scroll bar in JDialog !!

    Dear All ,
    My flow of program is JFrame call JDialog.
    dialogCopy = new dialogCopyBay(frame, "Bay Name Define", true, Integer.parseInt(txtSourceBay.getText()) ,proVsl ,300 ,300);
    dialogCopy.setBounds(0, 0, 300, 300);
    dialogCopy.setVisible(true);        Then,I set the datasource of JTable is from a TableModel.
    It's wild that JTable can diplay the data without column names and scroll bar.
    I have no idea what's going wrong.Cause I follow the Sun Tutorial to code.
    Here with the code of my JDialog.
    Thanks & Best Regards
    package com.whl.panel;
    import com.whl.vslEditor.vslDefine;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class dialogCopyBay extends JDialog {
        vslDefine glbVslDefine;
        int lvCnt = -1;
        JTable tableCopyBay;
        int bgnX = 0;
        int bgnY = 30;
        int tableWidth = 100;
        int tableHeight = 100;
        public dialogCopyBay(Frame frame, String title, boolean modal, int sourceBay,
                vslDefine pVslDefine, int ttlWidth, int ttlHeight) {
            super(frame, title, true);
            Container contentPane = getContentPane();
            System.out.println("dialogCopyBay Constructor");
            glbVslDefine = null;
            glbVslDefine = pVslDefine;
            copyBayModel copyBay = new copyBayModel((glbVslDefine.getVslBayStructure().length - 1),sourceBay);
            tableCopyBay = new JTable(copyBay);
            tableCopyBay.setPreferredScrollableViewportSize(new Dimension(tableWidth, tableHeight));
            JScrollPane scrollPane = new JScrollPane(tableCopyBay);
            scrollPane.setViewportView(tableCopyBay) ;
            tableCopyBay.setFillsViewportHeight(true);
            tableCopyBay.setBounds(bgnX, bgnY, tableWidth, tableHeight);
            tableCopyBay.setBounds(10, 10, 100, 200) ;
            contentPane.setLayout(null);
            contentPane.add(scrollPane);
            contentPane.add(tableCopyBay);
        class copyBayModel extends AbstractTableModel {
            String[] columnNames;
            Object[][] dataTarget;
            public copyBayModel(int rowNum ,int pSourceBay) {
                columnNames = new String[]{"Choose", "Bay Name"};
                dataTarget = new Object[rowNum][2];
                for (int i = 0; i <= glbVslDefine.getVslBayStructure().length - 1; i++) {
                    if (pSourceBay != glbVslDefine.getVslBayStructure().getBayName() &&
    glbVslDefine.getVslBayStructure()[i].getIsSuperStructure() == 'N') {
    lvCnt = lvCnt + 1;
    dataTarget[lvCnt][0] = false;
    dataTarget[lvCnt][1] = glbVslDefine.getVslBayStructure()[i].getBayName();
    System.out.println("lvCnt=" + lvCnt + ",BayName=" + glbVslDefine.getVslBayStructure()[i].getBayName());
    public int getRowCount() {
    return dataTarget.length;
    public int getColumnCount() {
    return columnNames.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int rowIndex, int columnIndex) {
    return dataTarget[rowIndex][columnIndex];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
    if (col == 1) {
    // Bay Name Not Allow To modify
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    dataTarget[row][col] = value;
    fireTableCellUpdated(row, col);

    Dear DB ,
    I am not sure what you mean.
    Currently,I don't undestand which code is error.
    And I also saw some example is add JTable and JScrollPane in JDialog.
    Like Below examle in Sun tutorial
    public class ListDialog extends JDialog implements MouseListener, MouseMotionListener{
        private static ListDialog dialog;
        private static String value = "";
        private JList list;
        public static void initialize(Component comp,
                String[] possibleValues,
                String title,
                String labelText) {
            Frame frame = JOptionPane.getFrameForComponent(comp);
            dialog = new ListDialog(frame, possibleValues,
                    title, labelText);
         * Show the initialized dialog. The first argument should
         * be null if you want the dialog to come up in the center
         * of the screen. Otherwise, the argument should be the
         * component on top of which the dialog should appear.
        public static String showDialog(Component comp, String initialValue) {
            if (dialog != null) {
                dialog.setValue(initialValue);
                dialog.setLocationRelativeTo(comp);
                dialog.setVisible(true);
            } else {
                System.err.println("ListDialog requires you to call initialize " + "before calling showDialog.");
            return value;
        private void setValue(String newValue) {
            value = newValue;
            list.setSelectedValue(value, true);
        private ListDialog(Frame frame, Object[] data, String title,
                String labelText) {
            super(frame, title, true);
    //buttons
            JButton cancelButton = new JButton("Cancel");
            final JButton setButton = new JButton("Set");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.dialog.setVisible(false);
            setButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.value = (String) (list.getSelectedValue());
                    ListDialog.dialog.setVisible(false);
            getRootPane().setDefaultButton(setButton);
    //main part of the dialog
            list = new JList(data);
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            list.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        setButton.doClick();
            JScrollPane listScroller = new JScrollPane(list);
            listScroller.setPreferredSize(new Dimension(250, 80));
    //XXX: Must do the following, too, or else the scroller thinks
    //XXX: it's taller than it is:
            listScroller.setMinimumSize(new Dimension(250, 80));
            listScroller.setAlignmentX(LEFT_ALIGNMENT);
    //Create a container so that we can add a title around
    //the scroll pane. Can't add a title directly to the
    //scroll pane because its background would be white.
    //Lay out the label and scroll pane from top to button.
            JPanel listPane = new JPanel();
            listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
            JLabel label = new JLabel(labelText);
            label.setLabelFor(list);
            listPane.add(label);
            listPane.add(Box.createRigidArea(new Dimension(0, 5)));
            listPane.add(listScroller);
            listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    //Lay out the buttons from left to right.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(cancelButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
            buttonPane.add(setButton);
    //Put everything together, using the content pane's BorderLayout.
            Container contentPane = getContentPane();
            contentPane.add(listPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
            pack();
        public void mouseClicked(MouseEvent e) {
            System.out.println("Mouse Click");
        public void mousePressed(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseReleased(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseEntered(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseExited(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseDragged(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseMoved(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
         * This is here so that you can view ListDialog even if you
         * haven't written the code to include it in a program.
    }

  • JTable : How to display an icon near the column name ?

    Hi all,
    I'd like to display an icon near the column name of my JTable when an user click on the column; the icon specify the sorting applied to the data of JTable.
    I know that i have to write a render, but how ?
    Cheers.
    Stefano

    Hi all,
    I found the solution at http://exampledepot.com/egs/javax.swing.table/IconHead.html
    Cheers anyway.
    Stefano

  • How to add pop up menu on the column name of a jtable

    hi all,
    i am naive to swing .
    i want to know that how can i open a pop up menu on the right click of the column of a jtable build in frame.i mean to say i on th eright click on the header of table which has column names.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html#popup]How to Use Popup Menus.

  • [Swing] JTable & Oracle DB: SQL Query for Column Names Change

    Hello,
    I apologise for the 'stupid' thread subject name.
    Now i have a JTable wich i fill with rows from an Oracle DB.
    The query is something like this: "SELECT location_id, location_name FROM locations*bold*", and in the table i will have the columns names LOCATION_ID & LOCATION_NAME.
    I want to change this query like: "SELECT location_id "Location ID", location_name "Location Name" FROM locations".
    The only problem is that i CAN NOT insert "" inside ""
    So if anyone know how to fix this 'problem' please share that with me.
    Thank you,
    B.

    found it.. \" \"
    :)

Maybe you are looking for

  • J1INCHLN

    HI GURU'S Presently we are maintianing TDS,Surcharge,Ecess and Higher education cess in the dedction. It means 4 TDS line item I get at the time of the invlice or payment. And When i am running J1INCHLN I am getting only 3 line items. Surcharge line

  • Logon Failed - Invalid element error when trying to connect to SalesForce

    I had a working crystal reports database connection to salesforce until I installed a Crystal Reports update on my machine.  It is currently running v12.2.0.290 (CR Developer). Since the update when trying to connect, I enter my password and salesfor

  • Apple TV slideshow with video and images

    I want to make a "slideshow" with alternating video clips (from one movie) and pictures.Can I tell the movie to play for a certain amount of time and then switch to an image and then go back to the movie, repeating until the movie is over and then ha

  • Database connectivity in struts ( EJB) with Oracle 9

    hi, We are developing a Banking application using Struts & EJB, & I need to use Oracle 9 as a database. Could anyone please let me know, the professional way of connecting this application to the oracle database using Struts and EJB. A good example w

  • MinionPro v. 2004 and Serbian glyphs for Wikipedia

    At the Serbian Wikipedia we are thinking about an OpenType solution to correctly display Serbian glyphs instead of the standard/Russian ones. We are scanning the Web for fonts containing Serbian glyphs and I personally think MinionPro should be our c