JTable column-spanning headers

It there a neat way of creating an equivalent of the HTML colspan effect in JTables, particularly in the headers?
I want to produce a table with headers divided into major and minor categories.
I guess I can write my own extension of JTableHeader, but that's going to get messy.

For the benefit of anyone searching for a solution.
I've found a way of doing this that isn't too much hastle. I create a secondary DefaultTableColumnModel and add columns initialised to the combined width of the groups of columns in the table's TableColumnMode which the more generic headers corespond to. Column reordering is disabled on both models and width changes on the extra one.
Based on this I create a JTableHeader component which I juxtapose with the table and main header using a Box.
I add a TableColumnModelListener to the original ColumnModel. the columnMarginsChanged method causes all the widths in the secondary column model to be recalculated from the original.
The only problem I've had is to persuade the new JColumnHeader to addopt a sensible size. I've had to set both minimum and maximum dimensions before the display will layout properly.
Haven't tried this with a JScrollPane yet but you should be able to bolt the two headers together and stick them in the header slot of the scrollpane.

Similar Messages

  • Column span and crashing

    Hi,
    Is anyone else facing this kind of problem? I have a page with various columns (three). The columns are hosting a narrow, but long table. The introductory paragraphs (title and legend) are spanned across the columns.
    Each time I do any edit (applying a text style, deleting a line) InDesign freezes. I get this kind of error in the Console:
    12/06/10 13:45:18 [0x0-0x36d36d].com.apple.Safari[30282] Sat Jun 12 13:45:18 MacBook-Pro-di-PaoloT.local Safari[30282] <Error>: CGImageDestinationCreate destination parameter is nil
    12/06/10 13:45:18 [0x0-0x36d36d].com.apple.Safari[30282]  
    12/06/10 13:46:56 /usr/sbin/spindump[91509] process 91490 is being monitored
    12/06/10 13:46:57 /usr/sbin/spindump[91509] process 91490 is being force quit
    12/06/10 13:46:59 kernel IOHIDSystem::relativePointerEventGated: Capping VBL time to 20000000 (was 26824595)
    12/06/10 13:47:03 com.apple.launchd[169] ([0x0-0x528127c].com.adobe.InDesign[91490]) Exited: Terminated
    12/06/10 13:47:29 SubmitReport[91514] missing kCRProblemReportProblemTypeKey
    12/06/10 13:47:31 /usr/sbin/ocspd[91517] starting
    12/06/10 13:47:33 SubmitReport[91514] Submitted compressed hang report for Adobe InDesign CS5
    12/06/10 13:50:32 /usr/sbin/spindump[91527] process 91518 is being monitored
    12/06/10 13:50:34 /usr/sbin/spindump[91527] process 91518 is being force quit
    12/06/10 13:50:38 com.apple.launchd[169] ([0x0-0x5287282].com.adobe.InDesign[91518]) Exited: Terminated
    I reported this to Adobe, but I would see if anyoady has a workaround. I solved using the old way (separated text frames), but this prevents one of the features of CS5.
    Paolo

    I tried to reproduce the crashing that Eugene reported, and could not. I have a decent C2D with 4 gigs of RAM, and with those specs all I could do was experience slightly-slower-than-expected performance when working with column-spanning headers. However, when I start my Ubuntu VM, and start the processes that cause it to consume about 2 gigs of RAM, then my system specs degrade to the minimum RAM acceptable to ID (just more than 2 gigs) and I start experiencing multi-second delays.
    My hunch is that this particular feature requires more resources than the minimum spec from Adobe... or that a buggy plugin is crashing when it doesn't do garbage collection quick enough to prevent the host system from running out of available RAM. Just a hunch, I'm not a developer at all, but the whole thing smells like a memory leak to me. I could never get it to crash, though, so perhaps I'm only muddying the path with my posts about my attempts to reproduce it.

  • Export JTable Column headers to Excel document

    Hello all!!! I am having a small problem while trying to export some data from a jTable to an excel document.
    I have a jTable and I use a custom TableModel with this:
    private String[] columnNames = {"First", "Second", "Third", "Forth"};as names for each column of the table.
    The thing I am trying to do is to export exactly the same "headers" from the columns of the jTable to the excel spreadsheet using Jakarta POI. Unfortunately I don't know how to do it and I haven't found anything yet on this forum. Can anyone help me with this?
    In simple words I want to know how I can have the same headers from my jTable columns, with the headers from the excel doument I will create.
    Many thanks in advanve!!!
    Kostas

    Thank you for your reply first of all. The problem is how to get the heading text and how to put it to the excel's first row OR to excels "headings" (if it is possible...). [in other words replace A,B,C,D from the excel document with the headers I get from the jTable...] .
    I hope now you can see what I am looking for... If there is no solution to this please tell me what are the alternatives. (B) could be a good example.
    Thanks you very much!!
    Kostas

  • How to change JTable column header text

    How do you set the text in the JTable column headers? I know you can create a JTable specifying the text in an array:
    <li>JTable(Object[][] rowData, Object[] columnNames)
    But if you create the JTable specifying a TableModel,
    <li>JTable(TableModel dm)
    the header text defaults to "A", "B", "C", etc. I cannot figure out how to access the text in the header names so it can be changed to something useful. I know how to get the JTableHeader for the table, but it does not seem to have methods for actually setting header values.

    I'm sure that model allows you to specify header values so you don't have to do so manually. I would be very surprised if it didn't override the default getColumnName() method to provide a reasonable names.She wasn't writing the class, but [url http://forums.oracle.com/forums/thread.jspa?messageID=9200751#9200751]outlining a design for me to implement. And, based on a previous comment I had made, I think she assumed I wanted the new design to look as much like the old as possible. There were no headers in the original design, which wasn't even a table.
    Anyway, this works:
        final static String statisticsColumnNames[] = {
         "Type", "Count",
         "Red QE", "Green QE", "Blue QE", "Average QE",
         "Distance"
         qErrors = new QEBeanTableModel();
         JTable errorTable = new JTable(qErrors);
         TableColumnModel tcm = errorTable.getColumnModel();
         for (int col = 0; col < statisticsColumnNames.length; col++)
             tcm.getColumn(col).setHeaderValue(statisticsColumnNames[col]);
    It looks like setHeaderValue() on the TableColumn is what I was looking for.Again, only used if you are dynamically changing the values at run time or you don't like the defaults provided by the Bean-aware model.I coded the above before I read your last post. The QEBeanTableModel is extremely specific to my program. I.e. I cannot imagine it being used anywhere else. Would it still be better to implement a getColumnName() within the table model? Looking at your [url http://www.camick.com/java/source/RowTableModel.java]RowTableModel.java source, I can see that it would not be difficult to do so.
    Just decided to add the getColumnName() method. This whole sub-project is based on implementing a clean modern design (and learning about Java Beans). You've clearly stated twice that the method I have implemented is for dynamic header values only, which has already answered what I asked last paragraph.

  • Setting size of JTable columns

    Hi everybody,
    Can anyone help me ?
    How can I set a column widths of a JTable, but also allow the user to resize them ?
    I tried with a code like
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
       if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setPreferredWidth(preferedSizeArray);
    But it doesn't work :(
    When i do [ define the minWidth and maxWidth ]
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
        if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setMinWidth(preferedSizeArray);
    tableColumnModel.getColumn(i).setMaxWidth(preferedSizeArray[i]);
    Columns's sizes are exactly what i want but ... the colums are no more resizable.
    So,
    if anyone can help me and tell me how can i set a predefined size for some colums and also allow the user to resize them ... that would be kind from him.
    Thanks

    Hi guys,
    It's me again ... but I tried your tricks and they don't work :(
    Look this example :
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    public class JTableResizing extends JFrame implements ActionListener {
        private JScrollPane scpnl = new JScrollPane();
        private JButton btnClose = new JButton();
        Object[][] data={   new Object[]{"Hi", "everybody", "this is ", "a row"},
                            new Object[]{"and ", "this ", "is the second", "row"},
                            new Object[]{"of a", "very ","usefull","jtable"}
        Object[] columnNames={"Column1", "Column2", "Column3", "Column4"};
        TableModel dataModel=new DefaultTableModel(data, columnNames);
        private JTable jTable = new JTable(dataModel);
        public JTableResizing() {
            try {
                /* We don't care about this code !! just see the code below !
                 * It has been made really quick [and dirty :D]
                this.setSize(new Dimension(530, 400));
                this.getContentPane().setLayout(new GridBagLayout());
                btnClose.setText("close");
                btnClose.addActionListener(this);
                scpnl.getViewport().add(jTable, null);
                this.getContentPane().add(scpnl,    new GridBagConstraints(0, 0, 1, 1, 1.0, 0.5,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.BOTH,
                                                                        new Insets(50, 50, 50, 50),
                                                                        0, 0));
                this.getContentPane().add(btnClose, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.NONE,
                                                                        new Insets(0, 0, 20, 0),
                                                                        0, 0));
                /* is this really necessary ??? I really don't think so */
                JTableHeader headers = jTable.getTableHeader();
                if (headers != null) {
                    headers.setResizingAllowed(true);
                 * Start watching the code from here.
                 * I created a JTable [jTable] with n columns. Now, I want to fix
                 * a size for some columns and the question is how ?? 
                 * Maybe the easiest way is to create a method !!
                 setColumnsSizes(jTable, new int[]{0, 100, 0, 50});
            } catch(Exception e) {
                e.printStackTrace();
        /* I know, the code is not the best but I don't care !! This is a quick
         * and dirty sample code to make you understand my problem ...*/
        public static void setColumnsSizes(JTable jTable, int[] columnsSizes) {
            /* look the array supplied above.  columnsSizes =  int[]{0,100,0,50}
             * but any array can be supplied !!
             * This one means that the second and the fourth columns should take
             * resectively a width of 100 and 50 and the two others columns
             * the first one and the third one, fill as much as possible depending on
             * the available space in the scrollpane.
             * Also, when I resize the frame, the scrollpane is resized
             * (look the gridbagconstraints above, and also here columns with
             * no prefered size must be
            /* Which mode should I suplpy ? I need an autoresize only for columns
               where no prefered size has been defined and I don't think it exists */
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            TableColumnModel tableColumnModel = jTable.getColumnModel();
            for (int i=0; i < columnsSizes.length; i++) {
                if (columnsSizes[i] > 0) {
                    /* If I define a minimum width, the colum will be resizeable but,
                       we will be unable to resize it under his minSize. This can be
                       a good behaviour !*/
                    tableColumnModel.getColumn(i).setMinWidth(columnsSizes);
    /* If I define a prefered width, I'm not sure it will be the
    width of the column.
    I mean, when I define a prefered size on a column, other
    columns are resized depending of the autoResizeMode !*/
    tableColumnModel.getColumn(i).setPreferredWidth(columnsSizes[i]);
    /* if I define a maxWidth (next line code) the column will be fixed */
    // tableColumnModel.getColumn(i).setMaxWidth(columnsSizes[i]);
    public static void main(String[] args) {
    JTableResizing jTableResizing = new JTableResizing();
    jTableResizing.setLocationRelativeTo(null);
    jTableResizing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jTableResizing.setVisible(true);
    * method performed when clicking on button close
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    Copy, paste and run it and you'll understand the problem.
    Also, try to read comments I added (I think they are understandable, although I know they are full of grammar mistakes, but this is another question ... )
    Thanks for your help.
    And may the force be with you

  • How Can I set up a JTable columns?

    Dear All,
    How can I set up my JTable columns to have the amount the user specifies?
    for example when the user types in 50 in JTextField 1 I want the JTables columns to then set to 50.
    How can this be done?
    Thanks
    lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

    As you can see I have tried this, but no success.
    If I am doing something wrong please accept my apology, and address me in the right direction.
    Thanks
    Lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
         ((DefaultTableModel)perstab.getModel()).setColumnCount(Integer.parseInt(name.getText()));
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

  • F2 key not working with custom JTable Column

    I have a custom JTable Column (which is a JPanel with a JTextfield and JButton). Everything works as expected, except when the user presses "F2" to start editing the custom column cell. When the user presses F2, the custom cell goes into editing mode, but I am unable to type anything in it.
    Below is the SSCCE.
    Steps to Reproduce problem:
    1) Run the Program
    2) Select any cell in first Column.
    3) Press "F2" and try to type into the cell. Can't type anything.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class TextButtonCellFrame extends javax.swing.JFrame {
        // Variables declaration - do not modify                    
        private JTextField inputText;
        private JScrollPane jScrollPane1;
        private JPanel testPanel;
        private JTable testTable;
        // End of variables declaration                  
        public TextButtonCellFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            testPanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            testTable = new JTable();
            inputText = new JTextField();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            testTable.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            testTable.setCellSelectionEnabled(true);
            testTable.setRowHeight(52);
            testTable.setSurrendersFocusOnKeystroke(true);
            testTable.getColumnModel().getColumn(0).setCellRenderer(new MyTableCellRenderer());
            testTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor(new JTextField()));
            testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
            jScrollPane1.setViewportView(testTable);
            testPanel.add(jScrollPane1);
            inputText.setPreferredSize(new Dimension(50, 20));
            testPanel.add(inputText);
            getContentPane().add(testPanel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-576)/2, (screenSize.height-417)/2, 576, 417);
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextButtonCellFrame().setVisible(true);
        public class MyTableCellRenderer extends JPanel implements TableCellRenderer {
            Point point;
            JButton button1 = new JButton("Test 1");
            JTextField txtField = new JTextField();
            public MyTableCellRenderer() {
                setLayout(new BorderLayout());
                this.add(button1, BorderLayout.EAST);
                this.add(txtField,BorderLayout.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
                if (isSelected) {
                    txtField.setBackground(testTable.getSelectionBackground());
                    txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                else {
                    txtField.setBackground(testTable.getBackground());
                    txtField.setBorder(null);
                return this;
        public class MyTableCellEditor extends DefaultCellEditor {
            JPanel panel = new JPanel();
            JButton button1 = new JButton ("Test 1");
            JTextField txtField;
            MyTableCellEditor(JTextField txtField) {
                super (txtField);
                this.txtField = txtField;
                panel.setLayout(new BorderLayout());
                panel.add(button1, BorderLayout.EAST);
                panel.add(txtField,BorderLayout.CENTER);
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == button1)
                    JOptionPane.showMessageDialog(null, "Action One Successful");
            public Component getTableCellEditorComponent(JTable table, Object value,
                                        boolean isSelected, int row, int column) {
                return panel;
           public boolean isCellEditable(final EventObject anEvent) {
              if (anEvent instanceof KeyEvent) {
                 final KeyEvent keyEvent = (KeyEvent) anEvent;
                 SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                       if (!Character.isIdentifierIgnorable(keyEvent.getKeyChar())) {
                          txtField.setText(txtField.getText() + keyEvent.getKeyChar());
                       txtField.setCaretPosition(txtField.getText().length());
                       txtField.requestFocusInWindow();
                return super.isCellEditable(anEvent);
    }The code for isCellEditable(final EventObject anEvent) which is needed to edit the cell using keyboard was provided by DarrylBurke here
    regards,
    nirvan.

    The F2 key when pressed generates an action event (either JTable generates it or some other component). I am not sure how to handle the action event in the isCellEditable() method. Also, F(X) range of keys other than F2 dump some junk character in the JTextfield when pressed. I am now stuck at this point and don't know how handle F(X) range of keys.
    regards,
    nirvan.

  • How to catch selected text in JTable Column

    Hi there,
    I am learning JTable. Need help for How to get the selected text from the JTable Column which is set to be editable.
    for example in JTextFiled you have method on getSelectedText(), is there any method for tracking the selected text.
    Thanks in advance
    Minal

    Here's an example of the model I used in my JTable. Not the "getValueAt" method & "getRecordAt" method. You will have to have a Record object - but it only contains the attributes of an inserted record (with appropriate getters & setters). Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • How To Search For a Text In JTable Column?

    hi there
    i want to search for specific text in a JTable Column
    And If The Text Exists Highlits it?
    any ideas or useful links or tutorials?

    Well, then that would be a Swing related question. Did you search the Swing forum to see how rendering works.

  • Dynamically set number-columns-spanned

    Hi all,
    I have a cross tab which has a dynamic number of columns. Each column has a header "Location" (which is determined by the data), but the table also has a master header "Volume" which should span all of the locations. How can I acheive this?
    I currently have:
    <xsl:attribute xdofo:ctx="block" name="number-columns-spanned">2</xsl:attribute> Volumne
    But this is obviously static.
    Many Thanks
    Andy

    Hi lmd2,
    Attached is a quick example of one way to do what you are asking. This is only a general example, and there may be a bettter implementation depending on the architecture of your application.  The link here also has information on setting the number of sockets for a specific sequence file. Hope this helps.
    Regards,
    Ebele O.
    National Instruments
    Attachments:
    ParallelModel.seq ‏455 KB

  • Custom JTable column (JCheckBox) not included in row selection.

    I am trying to use JCheckBox (for display only data) as one of my JTable columns. I have written custom cell renderer for the same. Every thing is working fine except that when I select a row, the new custom JCheckBox column is not included in selection. Here is the code that I am using.
        protected class CheckBoxColumnRenderer extends DefaultTableCellRenderer {
            JCheckBox ckb = new JCheckBox();
            public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                if (value instanceof Boolean) { // Boolean
                  ckb.setSelected(((Boolean) value));
                  ckb.setHorizontalAlignment(JLabel.CENTER);
                  ckb.setBackground(super.getBackground());
                  if (isSelected || hasFocus) {
                      ckb.setBackground(table.getSelectionBackground());
                return ckb;
        }How can I include the custom cell in the row selection.
    regards,
    nirvan.

    they have lots of dependencies and it is not always easy to strip out an SSCCE without a considerable effort.Exactly. And is the cause of the problem the dependencies or something else. The only way to know for sure is to strip out the code and simplify the problem, that way you truly understand what the problem is.
    The majority of time this can be done with minimal effort as in this case.
    Some times we are sure that the problem is with certain part of the code Is the problem the code or the way the code is invoked? How do we know the TableModel is created properly or that the column class is overwritten correctly when we can't see it?
    someone having a third look at it may actually find the enhancement required with ease.Exactly, but we need to see the big picture.
    So are you sure that I should post an SSCCE with every possible question where coding is involved ?In the majority of cases a SSCCE is easily created in 5-10 minutes, so if you want the fastest help then yes.
    Just twice this past week I was ready to ask a question on the forum and was preparing a SSCCE to post and sure enough both times the creation of the SSCCE caused me to look at the problem differently and I solved it. I would much rather solve a problem on my own then post a question and wait for hours (days) hoping someone else knows the answer.

  • What method should be used for resizing the particular JTable Column width

    I have a four table. Only one table which are on top have a table header. I want that when user resize the topmost table with a mouse other table colume also be resized automatically. So I want to know that what method should be used for resizing the particular JTable Column width.
    Thanks
    Lalit

    maybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
    for example:
    toptable.addComponentListener(
    new ComponentAdapter(){
    public void componentResized(ComponentEvent e){
    table1.setSize(....);
    table2.setSize(....);
    /*Optionally, you must also call function revalidate
    anywhere;*/
    );

  • Set JTable in another JTable Column

    Hai Java Experts
    Can we Set JTable in another JTable Column
    In jsp we add one table in a column of another table. Like the previous way can we do it in swing?
    Pls Help me with example..
    Thanks

    [http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender]
    db
    edit And adding a table in a column of another table doesn't make any sense at all. Perhaps you meant showing a table in a cell of another table.
    Edited by: DarrylBurke

  • How to create a dynamic table were the JTable columns keep varying

    How to create a dynamic table were the JTable columns keep varying based on the input to the jtable

    Oooh, I lied. DefaultTableModel has an API for adding and
    removing columns. I didn't know that. You should have read
    the API.
    As for preferring to extend AbstractTableModel rather than
    DefaultTableModel, I think it's more correct. DefaultTableModel
    is a simple implementation of Abstract for basic cases. It isn't
    intended to be extended. I figure most people extending
    DefaultTableModel are also extending JFrame, JPanel, and Thread
    instead of encapsulating the first two and implementing
    Runnable for the third.

  • Set background color to selected jtable columns cell

    I am clicking on jtables column.I want to select any column and that column (only selected cell of column)should get displayed with specific background color.
    plz help

    You can write your own tablemodel,
    i.e. use DefaultTableModel or implement AbstractTableModel.
    Good luck!

Maybe you are looking for

  • How to run a java program in the JVM of an already running program?

    As far as I know about JVM, each time we run a program a separate instance of JVM is created where the program runs. Correct me if I am wrong. Is there any way for another program to execute itself in the same JVM? Currently I am working on JFCUnit w

  • How can I print / export in portrait mode?

    I would like to print in portrait mode, but I can't find anywhere to do it. Is it possible?

  • Does the iPhone five comes with hotspot Feature?

    I want to buy an unlocked iPhone 5 but I want to know if it has hotspot included, because I have seen iPhones 4 s with it but some iPhones 5 that don't , does it depend on the carrier that You pick? Does it come with the unlocked  iPhone 5?

  • Class cast exception while casting FTPConnectionFactory object

    Hi I have SOA Suite Advanced installation - 10.1.3.4 MLR#5. I have developed a BPEL which polls an FTP site using a JCA FTPConnectionFactory registered in JNDI - eis/Ftp/My_Ftp. If file is present, then BPEL doesnt fetchs it... instead calls a java p

  • Can't load jdbc driver from localhost

    I'm having problems loading the jdbc driver from localhost when using a java com object in ASP. The simple class compiles fine and runs perfect from dos command line but gives this exception when run from personal webserver: java.lang.ClassNotFoundEx