Adding a Column to a JTable

I have a simple gui where I query a database and return a result set in a JTable using a table model. I would like to be able to add a new column with checkboxes as the first column in the table. I've seen examples using checkboxes with boolen data from the database, but this column is not being returned from the database it is a new added column.
The first task is to add the column and I am struggling with this. My code is below.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class DatabaseTest extends JFrame {
  private QueryTableModel qtm;
  public DatabaseTest()
    super("JTable Test");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(350, 200);
    qtm = new QueryTableModel();
    JTable table = new JTable(qtm);
    JScrollPane scrollpane = new JScrollPane(table);
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(3, 2));
    p1.add(new JLabel("Click here to Query the DB: "));
    JButton jb = new JButton("Search");
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
        qtm.Query();
    p1.add(jb);
    getContentPane().add(p1, BorderLayout.NORTH);
    getContentPane().add(scrollpane, BorderLayout.CENTER);
  public static void main(String args[]) {
    DatabaseTest tt = new DatabaseTest();
    tt.setVisible(true);
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
class QueryTableModel extends AbstractTableModel {
  Vector cache;
  private int colCount;
  private String[] headers;
  Statement statement;
  private static Connection conn = null;
  public QueryTableModel() {
    cache = new Vector();
  public String getColumnName(int i) {
    return headers;
public int getColumnCount() {
return colCount;
public int getRowCount() {
return cache.size();
public Object getValueAt(int row, int col) {
return ((String[]) cache.elementAt(row))[col];
public void Query() {
cache = new Vector();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:*****","******","*******");
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("Select username from dba_users where rownum < 6");
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
// Now we must rebuild the headers array with the new column names
headers = new String[colCount];
for (int h = 1; h <= colCount; h++) {
headers[h - 1] = meta.getColumnName(h);
while (rs.next()) {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
cache.addElement(record);
fireTableChanged(null);
// Add column code here?
} catch (Exception e) {
cache = new Vector(); // blank it out and keep going.
e.printStackTrace();
}Not sure how to add the column. I've tried a few variations of the following code with no luck:TableColumn tc = new TableColumn(0, 120);
tc.setHeaerValue("Name");
table.getColumnModel().addColumn(tc);Any help would be appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

The first task is to add the column Well, I like the suggestions from the link given in the above posting :-) It shows you how to dynamically alter the TableModel after its initial creation, and is probably the best generic solution.
But, just so you understand better how a TableModel works I"ll just put another thought in your mind. Maybe in this case you just create the TableModel correctly the first time so you don't need to do a dynamic change. The TableModel doesn't know where the data came from. It doesn't care that it came from a ResultSet. All it knows it that you have data in an array. So whats to prevent you from hard coding the first column to contain Boolean data?
{code}headers = new String[colCount+1];
headers[0] = "Boolean Column";
for (int h = 1; h <= colCount; h++)
headers[h] = meta.getColumnName(h);
while (rs.next())
String[] record = new String[colCount+1];
record[0] = new Boolean.FALSE;
for (int i = 1; i <= colCount; i++)
record[i] = rs.getString(i);
}{code}

Similar Messages

  • Dynamically adding a column to a jtable - simple & urgent

    I am new to using JTables.
    I have read the tutorial and looked at several examples, but I am still confused as to how to add/remove columns and how to add rows to the table.
    I want to have a totally dynamic table which will allow me to add/remove columns and to add rows.
    The table gets the data to be displayed (and the column header values) from an outside object. I thought about writing my own table model.
    Here is the code for my simple table model:
    import javax.swing.table.*;
    import java.util.Vector;
    public class MyTableModel extends AbstractTableModel{
       private Vector columnHeaders;
       private Vector data;
       // simple constructor
       public MyTableModel() {
          columnHeaders = new Vector();
          data = new Vector();  // data is a vector of vectors
       public int getColumnCount() {
          return columnHeaders.size();
       public int getRowCount() {
          if (data.size() == 0) {
              return 0;
          Vector columnData = (Vector)data.elementAt(0);
          return columnData.size();
       public Object getValueAt(int row, int column) {
          Vector columnData = (Vector)data.elementAt(column);
          return columnData.elementAt(row);
       // the method I call for dynamically adding a new empty column
       public void addNewEmptyColumn(String value) {
           columnHeaders.add(value);
           fireTableStructureChanged();
    }Here is how I use the table model with my table
    import javax.swing.*;
    public class Demo extends JFrame{
        private JTable table;
        public Demo() {
            super("test");
            table = new JTable(new MyTableModel());
            getContentPane().add(table);
            pack();
            show();
        public void addColumn(String value) {
            MyTableModel model = (MyTableModel)table.getModel();
            model.addNewEmptyColumn(value);
        public static void main(String[] args) {
            Demo demo = new Demo();
            // here I am trying to add columns...
            demo.addColumn("one");
            demo.addColumn("two");
    }I try to add columns, but nothing happens!!!
    What am I doing wrong?
    I would appreciate if someone who take himself/herslef to be a JTable expert could give me his/her e-mail and this way I won't bother the rest of the world with my stupid JTable questions...
    Sincerely
    Nir

    I have another question.
    What if I want to render the table headers in a certain way.
    I would like to use:
    TableColumn's setHeaderRenderer(TableCellRenderer headerRenderer).
    But in order to do it, I need to get a TableColumn.
    How do I get it from the model?
    I thought about subclassing JTable and overriding:
    public void tableChanged(TableModelEvent e)that function is called everytime I invoke fireTableStructureChanged().
    In that function, I am assuming that a column has been added, however, when I query for JTable's getColumnCount(), I keep getting 0!

  • Adding A Column into a JTable

    Hi
    I have a JTable with two soccer teams in. What i want to do is to add in a column between them that just says "VS". I ahev to do this when the user clicks a button as the table is constructed from details stored in a MySQL database.
    Can anyone give me any help?
    Jason

    the DefaultTableModel supports an addColumn() method, so:
    a) create your table and TableModel
    b) add a column to the end of the DefaultTableModel
    Now the TableColumnModel controls the order in which the columns are painted, so
    a) get the TableColumnModel from the table
    b) move the colum to the center

  • Adding new columns in a JTable?

    How can i add a new column every time a button is pressed? I have
    String columns[][] = {{"1", "2", "3"}}But i don't know how to add a new {} row...
    Help?
    Or can someone show me a better way to do it?

    Use a Collection instead of arrays.
    Arrays are fixed-size. If you need a bigger array, you need to create the new one, copy the old content over and fill in the new values.
    Collections hide all that complexity from you by providing simple .add() and .remove() methods.
    Arrays: low-level mechanism.
    Collections: more comfortable high-level mechanism

  • Adding/removing columns in jtable

    Hello everyone,
    i was looking for a way to add/remove columns from a jtable. The way i envision it working is... Initially have a predefined number of columns, of these only show the user say 5 of those on startup. but then provide a drop down (or list box etc) of the other column headings, so that when the user selects one... it adds it to the jtable. also to remove ..... is there a way to have a pop-up when the user right-clicks the table header and put a option to remove that column there? if not what is the best way to trigger a remove of a column? So i need a way to keep track of all the columns in case the user wants to add it again. anyone know how this can be done or any part of it?

    I need a intutive way for the user to remove a column from the gui (like with adding could be a dropdown box with column headers as labels).Create a custom ComboBoxModel. This model would simply contain TableColumns and display the header value in the combo box. The first combo box would display the currently showing columns. When you click on an item in the combo box:
    a) remove the TableColumn from the TableColumnModel
    b) remove the TableColumn from the model
    c) add the TableColumn to the "hidden" combo box model
    The same basic logic (but in reverse) would then apply when you click on the "hidden" combo box.

  • Adding mouse listener to the column header of a column in a JTable

    Hi
    I want to add a mouse listener to the column header of the 3rd column in a JTable. I dont find any appropriate method to do this. The code I have written to do this is below. But on using this code, the mouselistener is invoked if I click on any column header. Can anyone please help me to fix this.
    table.getTableHeader().addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    /* some actions */
    }

          table.getTableHeader().addMouseListener(new MouseAdapter(){
               public void mousePressed(MouseEvent me) {
                   int tableColumn  =table.columnAtPoint(me.getPoint());//it returns the column index
            });

  • Selective reordering of columns in a Jtable

    Hi
    I have this problem where I need to allow the first 8 columns to be reordered but not the remaining columns in a Jtable.
    I have tried a few approaches by adding listeners to the jtable header and identifying the column which is clicked for reordering and accordingly setting the rearrange policy / feature of the jtable to true/false.
    This works fine in almost all scenarios except for one where the user selects a column which can be reordered and drags it to a position beyond the allowed 8 columns, and now that column is frozen since it is beyond the permissible index of 8.
    I was wondering if there was a 'cleaner'/ better way to go about implementing this.

    Thanks for the link...
    I went through it but seems like a big change for the functionality I want to achieve.
    I am thinking about allowing the user to reorder the column and then if he has chosen an invalid column (one which cannot be rearranged) just undo that action using the moveColumn method.
    I tried overriding the columMoved method to inform me about a column reorder evernt but that method keeps getting fired while the user is rearranging.
    Is there anyway to get a notification once the user is done rearranging the column.
    Thanks

  • Problem in updating first column header in JTable

    hi
    I am using JTable in my application. I want to change first column name of JTable every time when a JList is selected. I am using DefaultTableModel for JTable. I added first column in Constructor and another in a method. I have to edit only first column header. How can i do this???
    I used this code but it is not working.
    table.getColumnModel().getColumn(0).setHeaderValue("Name of column");
    table.getTableHeader().resizeAndRepaint();
    Your help will be appreciated.
    Thanks in advance
    Sonal

    table.getColumnModel().getColumn(0).setHeaderValue("Name of column");
    table.getTableHeader().repaint();Works for me so post a SSCCE ( http://www.sscce.org/ ) that shows the problem.

  • How to get all the values in one column of a JTable

    How to get all the values in one column of a JTable as a Collection of String.
    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column.

    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column. You could always write a custom TableModel that stores the data in the format you want it. It would probably be about 50 lines of code. Or you could write a loop in 3 lines of code. I'll let you decide which approach you want to take.

  • How can I add custom right-click-menu to column headers in JTable?

    Can anyone point me to a topic on how to customize a popup menu for column headers in JTable? Specifically, I want to add things like "auto-size column" and "hide column".
    Thanks,
    Matt

    Right-click on your table.  Then go to Advanced->Runtime Shortcut Menu->Edit.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to create Hyperlink column in a JTable

    Can anyone help in creating a hyperlink column in a JTable.
    Thanks in advance,
    Sridhar.

    If the parent is an Applet it is very simple .
    catch the mouse click on columns and execute the following code
    String url = getValueAt(i,j);
    getAppletContext().showDocument(new
    URL(url ), "_blank");
    thatz all .
    if ur program is an application use this getRuntime.exec() and use parameters to rundll32.exe url and iexplore.exe in Windows platform,
    if u have still doubts plz get back to me
    Renjith K.V

  • Adding a column in the MSS Approval view

    What are the options for adding a column in the MSS approval view (CATS regular) ?

    there are lot of colums available in cats customisation for this
    Please check
    In the IMG (transaction SPRO), go to
    - SAP Customizing Implementation Guide
      - Cross-Application Components
        - Time Sheet
          - Specific Setting for CATS regular
            - CATS regular
              - Approve Working Time
                - Define Field Selection for Individual Approval View
                - Define Field Selection for Detail View
    Here you can assign lot of columns to your profile
    which is easily customisable

  • How to add get the field name for a newly added site column.

    I have the following:-
    Enterprise wiki site collection inside SharePoint server 2013.
    I added a new site column of type managed metadata.
    I opened the enterprisewiki.aspx page layout using the SP designer, to add the newly added site column to it.
    But I have noted that to add any site column I need to know the field name , for example the default wiki category column is referenced inside the page layout as follow:-
    <Taxonomy:TaxonomyFieldControl FieldName="Wiki_x0020_Page_x0020_Categories" EmptyValueDescriptionForTargetTemplate="<%$Resources:cms,enterwiki_nocategories_assigned%>" DisableInputFieldLabel="true" runat="server"/>
    <b>
    So my question is how I can know the field name for my newly added site column?
    Thanks in advance for any help.
    Regards

    Hi,
    The “FieldName” should be the internal name of the column, you will find it at the address bar at the “Site Columns”->”Edit Column” page:
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • How to fix the value of first column in the JTable in java swing for every

    Hi ,
    I have a swing page that have table panel in which there is a table of size 7x4 now when I click on the perticulat row then that row data will displayin the table like that the selected row become the second column in the new table and the fist column of this table will remain constant for all the entry but the second column update according to the roe which is selected .How it is possible .
    Thanks in Advace,
    anu

    One thing you can do is to prevent the user from editing that column and programatically supply the values of that column yourself.
    JTable table = new JTable() {
       public boolean isCellEditable(int row, int col) {
           if(col == 0) {
              return false;
           return super.isCellEditable(row, col);
    };This allows you to prevent the user from editing the column information so you can supply some sort of a default value for the column always
    ICE

  • Looking for component: flexible rows like columns in a JTable

    Hello,
    I need a swing component to display several rows which can be moved up and down, the height resized, interchanged with the mouse like the columns in a JTable. But there is no need for columns. I think there is no standard swing component.
    Any ideas, resource hints?
    Thanks, Ulrich

    One more piece of advice. It is not very easy to get "pre-written custom components". Most developers do things to meet their own needs and these may not be exactly what you are looking for. The best thing to do is to try to develop this yourself. It will give you loads of experience and in later programmes you may write, based on the experience you obtained from the "pain-staking" development process you'll know how to go round these problems quicker and may be able to help others also.
    So just start writing some stuff. You may end up finishing sooner than you think. And remember forum members are always ready to help with problems (accompanied by minimal code examples of the actual problem).
    ICE

Maybe you are looking for

  • Why wont my itunes uninstall

    i have windows vista an ever since i updated itunes it wont let me sign in to apple store. wen i try to uninstall i says the installer has insufficient privileges to modify this file C:\Program Files\Common Files\Apple\CoreFP\CoreFP.icxs  Also gave e

  • Re:Report by invoice

    the client wants to know how much he paid for a project (WBS elements) against the invoices .. How we will get standard reports only invioces particulat WBS elements

  • CSS ver 7.2

    We have just upgraded our CSS(s) to 7.2 bld 106 and are seeing some odd behaivor. Is anyone else seeing any issues with this version of code? Our first issue is with our HSE, after upgrading our HSE only sees about 23 out of the 70 services configure

  • OSB: Proxy service used in the WSDL address hostname, I want to use IP

    Hi all, I have a proxy service , open the WSDL address is as follows : ============================================================================================== <?xml version="1.0" encoding="UTF-8"?> <s0:definitions name="GeneralInboundServiceDe

  • Process chains data load

    Can any body help in data scheduling issue I am able to load data manually the issue is i selected some of the datafields  in InfoPackage  data selection field and saved . i put this Ip in the process chain.now the issue is i don't to load data immed