JTable: Easy groupable column headers with hideable columns

Hi All,
I have a requirement to make a JTable which displays
columns with 2 values - a current value and an old one.
The old value can be hidden or shown by user preference.
The values are not editable. The 2 values have a single
heading.
I've been mucking about with GroupableTableHeader and
HideableTableColumnModel and all that. This way of
solving the problem requires siginificant coding.
Then I had an idea - just use the TableCellRenderer to
make it look like 2 columns ! This fits my requirements
and is much simpler.
So for anyone who has the same requirement, here is
some sample code. I think you'll all agree that in my
specific case it is a very good way of providing the needed
functionality.
Here is the sample code:
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
public class DoubleColumnTable extends JTable {
    private boolean secondValueVisible = true;
    public DoubleColumnTable() {
        super();
        setModel(new AbstractTableModel() {
            public String getColumnName(int column) {
                return column + "";
            public int getColumnCount() {
                return 5;
            public int getRowCount() {
                return 5;
            public Object getValueAt(int rowIndex, int columnIndex) {
                return new Integer[]{new Integer(rowIndex), new Integer(columnIndex + 10)};
        setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Integer[] twoValues = (Integer[])value;
                JPanel panel = new JPanel();
                if (secondValueVisible) {
                    panel.setLayout(new GridLayout(0, 2));
                    JLabel firstLabel = new JLabel(twoValues[0].toString(), JLabel.CENTER);
                    JLabel secondLabel = new JLabel(twoValues[1].toString(), JLabel.CENTER);
                    secondLabel.setBackground(Color.lightGray);
                    secondLabel.setOpaque(true);
                    secondLabel.setBorder(new LeftBorder());
                    panel.add(firstLabel);
                    panel.add(secondLabel);
                } else {
                    panel.setLayout(new GridLayout(0, 1));
                    JLabel firstLabel = new JLabel(twoValues[0].toString(), JLabel.CENTER);
                    panel.add(firstLabel);
                return panel;
    private void toggle() {
        secondValueVisible = !secondValueVisible;
        repaint();
    class LeftBorder extends AbstractBorder {
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            g.setColor(Color.gray);
            g.drawLine(x, y, x, height);
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        frame.setLocation(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        final DoubleColumnTable table = new DoubleColumnTable();
        contentPane.add("North", new JButton(new AbstractAction("Toggle") {
            public void actionPerformed(ActionEvent e) {
                table.toggle();
        contentPane.add("Center", new JScrollPane(table));
        frame.setVisible(true);
}Message was edited by:
NY_Consultant
Message was edited by:
NY_Consultant
Message was edited by:
NY_Consultant

This should read
"I have a table with column headers and a row headers using a single column from a second table."

Similar Messages

  • Columns merged with other columns?

    how do I achieve the following?
    I want to have a tabular form as following
    The first line of the tabular form will only be 3 columns (eg. col1,col2,col3). those three columns will then be broken down into 9 columns (ed. col1 - no column, col2 will have col4,col5,col6, and col7, col3 wil have col8 to col12.) on the second line.
    Any ideas? I know it is possible to do with html but i'm not sure how to process it in APEX

    What I typically do first is to look at a report template from the current theme and see what CSS classes they are using against the tables, headers and rows. I will copy the entries to a text document so I can easily reference them.
    The you create a new report template from scratch and as a Named Column (row template).
    This type template allows you to specify where each column goes by using a substitution variable for the selected column.
    The query I used in the example was
    select ename, job, sal
    from emp
    For the Row Template 1 field under Row Template section, I put
    <tr><td>#ENAME#</td><td>#JOB#</td><td>#SAL#</td></tr>
    In the Before first and after last row text section I put
    1. in the Before rows field
    <style type="text/css">
    table.outln {border-collapse:collapse;}
    table.outln td {border: solid #000 1px;padding:5px;}
    </style>
    <table cellpadding="0" border="0" cellspacing="0" summary="" class="t9standardalternatingrowcolors outln" border="1">
    <tr><th class="t9header" colspan="2">Name / Job</th><th class="t9header">Salary</th></tr>
    2. In the After Rows field
    </table>
    This type of template is REALLY powerful. The only issues that I have run into in the past is that the order of the columns in your query should be the same as the order in which they are used in your row template. I am not sure if it is still an issue, but I have experience issues in the past that when you later change the query and the order is different then the rows are actually put in by position and not by name. To fix that problem I just drop the report and recreate.
    If you happen to have my book by Oracle Press, HTML DB Handbook, there is a good description of this type of template on pages 211- 215.
    The book is a little old now (almost 2 years). Just happened that they renamed HTML DB to ApEx the month before the book was published. It covers ver 2.0, but still has some good info in it.

  • Add each column record with next column record

    Dear all,
    I have created a crosstab with the column "Order Numbers". Each Order number is calculated per day.
    I would like to know how can I create a formula so that each record in the column field is calculated by adding the next column field.
    For example
    Order numbers
    1
    2
    3
    4
    5
    Formula should display the records like this
    Order Numbers
    1
    3 (12)+
    6 (123)
    10 (1234)+
    15 (12345)
    So in other words each record in each field of the column is adding the next field.
    Something like ColumnRecord= Column Record+Next column Record.
    How can we achieve this?
    Many thanks
    Regards
    Jehanzeb

    Hellooo,
    I have sorted it.
    here is what I did
    Firstly I selected the Column field (percentage field).
    Clicked format -
    > then Suppress and clicked on x+2
    added the following formula
    whileprintingrecords;
    numbervar x := x + currentfieldvalue;
    false
    Then I clicked on Display String x+2 and entered this.
    whileprintingrecords;
    numbervar x;
    totext(x,2)+"%"
    Then I clicked on border->background> and added this formula
    whileprintingrecords;
    numbervar x := 0;
    defaultattribute
    all set and it is working perfectly.
    I hope this helps someone who is seeking this type of formula
    Regards
    Jehanzeb

  • Simple 9 column table with a column header

    I have looked for hours at the docs for creating a scrollable table. I think what I want is so simple, that the complexity of the docs overwhelms me. I need a jTable that once is fills over 8 rows, it begins to scroll. The table then is 9 columns wide by 8 rows in height. Each of the 9 columns are not the same size. Can anyone get me started with creating this ??? Sorry, I have no duke $$. :o(

    I actually had to change a few things. The latest code is a follows:
    My vertical lines appeared when I added the row,col(8,9) in the DefaultTableModel. And when I did that, the model.add... actually produced 18 columns, so I had to change to "model.setColumnIdentifiers()" to fix that. So the only part is the centered headers. That's gotta be Netbeans. I'm using jBuilder 2005. Thanks for your input. I'm almost there. :o)
    int columnWidths[] = {24,27,115,30,40,33,46,46,25};
    String columnIDs[] = {"Trans #","Ticket","Transaction Code","Gallons",
                            "Price","Variance","Charge Amt","Credit Amt","Age"};
    DefaultTableModel model = new DefaultTableModel(8,9);
      JTable jTable1 = new JTable(model);
    jTable1.setFont(new java.awt.Font("Courier New", Font.PLAIN, 13));
        jTable1.setPreferredSize(new Dimension(620, 160));
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.setShowHorizontalLines(false);
        model.setColumnIdentifiers(columnIDs);
        for( int j = 0; j < 9; j++ ) {
          TableColumn col = jTable1.getColumnModel().getColumn(j);
          col.setPreferredWidth(columnWidths[j]);
        jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.
                                                  HORIZONTAL_SCROLLBAR_NEVER);

  • Auto size columns but with hidden columns

    I want to hide some columns for interal use with the following statements:
    jTable.getColumnModel().getColumn(i).setMaxWidth(0);
    jTable.getColumnModel().getColumn(i).setMinWidth(0);
    jTable.getColumnModel().getColumn(i).setPreferredWidth(0);
    Now I find that the widths of hidden columns become not zero.
    But I still want to auto-size the columns, so I add
    setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    Then I find that the widths of hidden columns become not zero.
    Could anyone tell me how to auto size the columns while keeping the hidden columns with zero widths?
    Thanks!

    If you want to hide columns then remove them from the TableColumnModel. The data is not removed, the columns are just not painted. Here is an example:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411506

  • Mulitple Line column headers for a column in ALV using Web Dynpro for ABAP

    Hi WD4A Gurus,
           I have requirement to display the header name in multiple lines for a single column using ALV. How to achieve this, do I need to do some custom code? Please help me with sample code.
    Example:
    existing column name :
                Name   |  Date (mm/dd/yyyy) | Amount
    required column name:
                Name   |    Date               | Amount
    (mm/dd/yyyy)
    Thanks
    Ketan

    Displaying header in multiple lines is not possible in alv
    Regards
    Tamil

  • Finding column count with dynamic columns and dynamic tables

    I've done some PL/SQL for awhile now but was trying to devise a solution for the following problem:
    I wish to find the number of times a specific value for a column exists in all the tables that contain the field and I have access to see with the current user. The column name and value will be passed in via parameters.
    I was hoping to use something like
    select table_name from all_tab_columns where column_name = <variable table name>;
    then use the results from this to create a select statment based off the tables from the select above. I know the difference between dba_tab_columns and all_tab_columns - I want to make sure that I only retrieve the values i have access to.
    Can anyone point me to some guide / website / reference material I can read to catch up on the idea of creating this statment?
    Thank you.

    Hi,
    it's a test version.
    You can naturally tune it, but it seemed to work:
    declare
    pi_column VARCHAR2(30) := 'DEPTNO';
    pi_value VARCHAR2(4000) := '20';
    v_count NUMBER := 0;
    v_count_tab NUMBER;
    BEGIN
    FOR I IN (select owner, table_name from dba_tab_columns
              where column_name = pi_column
    LOOP
        EXECUTE IMMEDIATE 'SELECT count(*) FROM '||i.owner||'.'||i.table_name||
                          ' WHERE '||pi_column||' = :pi_value'  INTO v_count_tab USING pi_value; 
        v_count := v_count + v_count_tab;
    END LOOP;                   
    dbms_output.put_line(v_count);
    END;Regards

  • How to replace the string of column value with other column value in same table

      
    I have a temp table  which contains 
    Id  Name CTC   Address                      Content
    1    Ross  $200   6th block                  Dear #Name your  CTC  is #CTC and your address is  #address
    2   Jhon   $300   1oth cross                 Dear #Name your  CTC  is #CTC and your address is  #address
    Now i want to  select content    so that it should get  replace with  the respective  columns  and final output should come like this 
     Dear Ross your  CTC  is 200 and your address is    6th block  
      Dear Jhon your  CTC  is 300 and your address is   10th cross  
    Kindly suggest

    I think RSingh suggestion is ok ... what do you mean by another way? ...maybe something more generic?
    maybe build a table whith the list of col you need to "replace" and dinamically build the replace query ...
    declare @colList table(colName varchar(100))
    insert into @colList
    select 'name'
    union all select 'ctc'
    union all select 'address'
    declare @cmd varchar(2000)
    select @cmd='select '+ (select 'replace(' from @colList for xml path('') +' content '+
    (select ',''#'+ colName +''', '+ colName +')' from @colList for xml path(''))
    +' from YOURTABLENAME '
    exec (@cmd)
    or your request was different ?

  • How can I save a table with column headers?

    Hi
    I want to save the content in table to a text file. I used Write file.vi for doing that but the column headers didn't be saved. My column headers are changed depends on my testing result so that the column number is not fixed. Any suggestions?
    Bill.

    You can retrieve column headers with the ColHdrs[] table property and save them to disk before the table contents.
    Roberto
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • Getting column headers dynamically from input parameters in alv.

    Hi all,
    I am new to abap, can any one help me in getting column header dynamically through parameters in alv ?
    Eg:-
    i Have parametars for days field ,
    user inputs days as 10 20 30 40.
    Now I want to display in alv column headers as:-
    1st column-  'FROM 0 TO 10'
    2nd column- 'FROM 10 TO 20 '
    3rd column- 'FROM 20 TO 30'
    4th column- 'FROM 30 TO 40'
    5th column- 'FROM 40 TO 50'
    6th column- 'FROM 50 TO 60'
    thanks in advance........

    Check this code snippet:
    Step 1: Create a dynamic table based on the input in the selection screen.
    TYPE-POOLS: abap.
    DATA:
      lr_structdescr    TYPE REF TO cl_abap_structdescr,
      lr_tabledescr     TYPE REF TO cl_abap_tabledescr,
      lr_datadescr      TYPE REF TO cl_abap_datadescr,
      lt_components     TYPE abap_component_tab,
      ls_component      TYPE abap_componentdescr,
      lr_wa             TYPE REF TO data,
      lr_tab            TYPE REF TO data.
    DATA: lv_index TYPE sy-index.
    DATA: lv_index_num(5) TYPE n.
    DATA: lv_index_char(5) TYPE c,
          lv_iter TYPE i,
          lv_low TYPE numc2 VALUE 0,
          lv_high TYPE numc2 VALUE 10.
    DATA: lr_alv TYPE REF TO cl_salv_table.
    FIELD-SYMBOLS: <fs_field> TYPE ANY.
    FIELD-SYMBOLS: <fs_wa> TYPE ANY.
    FIELD-SYMBOLS: <fs_tab> TYPE table.
    PARAMETERS p_numcol(2) TYPE n DEFAULT 50.
    START-OF-SELECTION.
      lv_iter = p_numcol DIV 10.
      DO lv_iter TIMES.
        IF sy-index > 1.
          lv_low = lv_low + 10.
          lv_high = lv_high + 10.
        ENDIF.
        lv_index_num = sy-index.
        lv_index_char = lv_index_num.
        CONCATENATE 'FROM' lv_low 'TO' lv_high INTO ls_component-name
        SEPARATED BY '_'.
        ls_component-type =
        cl_abap_elemdescr=>get_p( p_length = 10 p_decimals = 2 ).
        INSERT ls_component INTO TABLE lt_components.
      ENDDO.
    * get structure descriptor -> lr_STRUCTDESCR
      lr_structdescr
      = cl_abap_structdescr=>create( p_components = lt_components
                                     p_strict = space ).
    * create work area of structure lr_STRUCTDESCR -> lr_WA
      CREATE DATA lr_wa TYPE HANDLE lr_structdescr.
      ASSIGN lr_wa->* TO <fs_wa>.
      lr_datadescr = lr_structdescr.
      lr_tabledescr
      = cl_abap_tabledescr=>create( lr_datadescr ).
    * Create dynamic internal table
      CREATE DATA lr_tab TYPE HANDLE lr_tabledescr.
      ASSIGN lr_tab->* TO <fs_tab>.
    * Populate the internal table
      DO 10 TIMES.
        DO.
          lv_index = sy-index.
          ASSIGN COMPONENT  lv_index  OF STRUCTURE <fs_wa> TO <fs_field>.
          IF sy-subrc <> 0.
            EXIT.
          ENDIF.
          <fs_field> = sy-index.
        ENDDO.
        APPEND <fs_wa> TO <fs_tab>.
      ENDDO.

  • JTable column headers not displaying using custom table model

    Hi,
    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
            etc
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
            fields=f;
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.
    Cheers,
    garsher

  • Remove Column Headers from a JTable in a JScrollPane

    Hi,
    I'm just wondering how to remove the column headers from a JTable in a JScrollPane.

    Here are two ways to do it, with different visual outcomes...
    import javax.swing.*;
    public class Test {
        public static void main(String[] args) {
            Object[][] rowData = {{"A", "B"}, {"C", "D"}};
            Object[] columnNames = {"col 1", "col 2"};
            JTable table1 = new JTable(rowData, columnNames);
            table1.getTableHeader().setVisible(false);
            JScrollPane sp1 = new JScrollPane(table1);
            JTable table2 = new JTable(rowData, columnNames);
            final JScrollPane sp2 = new JScrollPane(table2);
            JPanel contentPane = new JPanel();
            contentPane.add(sp1);
            contentPane.add(sp2);
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(contentPane);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    sp2.setColumnHeader(null);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • Almost invisible JTable column headers

    I'm writing an applet which contains a JTable within a JScrollPane. For a while the column headings (text) were visible, but recently the column headings have become very small in height. There is barely enough there so that the mouse can be used to sort, or resize or reorder the columns, but the text can not be seen. It doesn't seem to be related to the number of rows in the table. The getColumnName() method is being called and returning the correct strings, but they don't show up on the screen. As I said, this was working ok until recently, and I don't know what I changed that might have caused it.
    Any ideas? Thanks ... John Lawrence

    I am trying to have a JTable with variable height header. I give the headers a renderer that parses the text into a vector (breaking it into lines), and then returns a JList populated with the vector.
    ex: if the text is "Line1\nLine2", the header will have double height, with two lines:
    Line1
    Line2
    The problem is the same that you encountered: Swing only looks at the header of the 1st column to determine the height of all! So if there are headers with more lines than the 1st one, they get chopped!
    Does anybody know a workaround?

  • Cant see jtable column headers

    I have my jtable in a container and i am displaying that container in a jframe. I cant see the table column headers. I cant use a jscrollpane and need to make the table headers visible. I can see the table fine with all its information in it. When I do a System.out.println(TableModel.getColumnName(int)); i get the correct column header name so I know that the column headers are existing. I would appreciate any help that you can give

    the last answer did not help me out. I reposted this with more information, such as i am placing my table in a container and not in a scrollpane. I added the code below and it still did not work
    content.add(jt.getTableHeader(), BorderLayout.NORTH);
    content.add(jt, BorderLayout.CENTER);
    I can still only see the table. I pasted code below where I create my table and repaint it. I have it set up where my table is in a JPanel. I have is set up so that I can move it around and resize it with the mouse. This all works and I can see the table but there are no headers.
    public FigTable(DefaultTableModel inTableModel, LEditor inLEditor)
              super(50, 50, 350, 200);
              setLineColor(Color.blue);
              setFillColor(ColorMenu.kColorOfNoFill);
              fEditor = inLEditor;
              content = fEditor.getGEFPanel().getDrawingPanel();
              importTable(inTableModel);
              fEditor.init();
              fEditor.inval();
    public void importTable(DefaultTableModel inTableModel)
              jt = new JTable(inTableModel);
              tRows = jt.getRowCount();
              tColumns = jt.getColumnCount();
              content.add(jt, BorderLayout.CENTER);
              content.add(jt.getTableHeader(), BorderLayout.NORTH);
    public void paint(Graphics g)
              jt.setBounds(_x, y, w, _h);
              if (_h >= tRows && tRows != 0)
              jt.setRowHeight(_h / tRows);
              if (isSelected())
                   drawHandles(g);
              if (_filled && (getFillColor() != null))
                   jt.setBackground(getFillColor());
              if (getLineColor() != null)
                   jt.setGridColor(getLineColor());
                   jt.setBorder(BorderFactory.createLineBorder(getLineColor()));
         }

  • 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

Maybe you are looking for

  • Date vs. Day of the week

    Maybe I am dense, but I can't figure out a way to set my calendar for a meeting the first MONDAY of each month without doing it manually 12 times. Suggestions? Thanks!

  • A Simple problem I`m sure BUT ITS DRIViNG ME CRAAAZY!

    Hello, I hope someone can help. I published a site with the first podcst episode using iweb.It went through onto iTunes bo problem so all`s good... so today I put together the 2nd episode, submit it to itunes as before...up comes the `..please provid

  • My windows xp will not reboot,

    I have my mac dual core boot camped with windows xp. My computer's power shut off in the windows mode. I can get the mac system to operate, but the windows xp side will not boot up. It gives me these options; We apologize for the inconvenience, but W

  • JSF backing bean accessibility from external class

    I am using JSF in my application. Consider i am assigning a value of the inputtext field to a string in my managed bean. This bean has the getters and setters for the string. Now my requirement is to get the value of the string i.e. the string value

  • .clearfix css doesnt render in DW Design View

    I have used the css .clearfix code in my site to enable two divs to clear a floated element. It works fine in browsers like IE6, IE7, FF, Safari, etc. But the clearfix code doesnt make the divs clear when I am designing in Dreamweavers Design View. T