JTable in JLayeredPane - resize table header cursor

Hey everybody, I have searched all over this forum and the net for an answer to this problem. I have a class that adds a JComponent to a JLayeredPane in the default layer. In another layer above the default layer is a JComponent that exists only to provide a 'pretty' image border with round corners that overlap the component below it. It works and looks very good. The only problem I have found is that if the JComponent that is added (in the default layer) is a JTable the cursor no longer changes to the resize cursor (<->) when mousing over the table header column edges. I can still resize the columns but I need to have the cursor change to indicate that the colums can be resized for user friendliness. I assume that the mouse events are getting trapped by the upper layer in the JLayeredPane and aren't reaching the JTable in the lower layer as they need to.
I have tried swapping the two layers but when I do that the corners of the component that I want to add the border to overlap over the nice round corners of the border which defeats the purpose.
If anyone has any suggestions, or even better a solution, that would be great!
Thanks,
Erik

table.getTableHeader().setVisible(false); will
help.This is necessary, but probably not quite sufficient for picky users. You may also want to set the min, max, and preferred dimensions of the table header to 0,0, otherwise you get what looks like a top-only border.
Michael Bushe

Similar Messages

  • Resizing table header of diffrent table

    hi all,
    i have 3 tables, the first table having the table header.
    if resize the first table header than all other 2 should be resized accordingly.
    i have done this demo, i want to know is this correct way.
    or ony other suggestion.
    the problem with this i am setting the tablecellrender for the first table header, it will cause the problem, because i am setting table header column model for other 2 tables as a column model.
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableCellRenderer;
    public class TableHeaderCellRenderr extends JFrame
        JTable table1 = new JTable(5, 5);
        JTable table2 = new JTable(5, 5);
        JTable table3 = new JTable(5, 5);
        public TableHeaderCellRenderr()
            JPanel pnl = new JPanel();
            pnl.setLayout(new BoxLayout(pnl, BoxLayout.Y_AXIS));
            pnl.add(new JScrollPane(table1));
            pnl.add(Box.createVerticalStrut(10));
            pnl.add(table2);
            pnl.add(Box.createVerticalStrut(10));
            pnl.add(table3);
             table2.setTableHeader(table1.getTableHeader()); // this is what it doing the resizing width of the other tables
             table3.setTableHeader(table1.getTableHeader());
             table2.setColumnModel(table1.getTableHeader().getColumnModel());
             table3.setColumnModel(table1.getTableHeader().getColumnModel());
            cellrenderer leftRenderer = new cellrenderer();
            table1.getTableHeader().setDefaultRenderer(leftRenderer);
            getContentPane().add(pnl);
            setSize(new Dimension(400,400));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public class cellrenderer extends DefaultTableCellRenderer
            public cellrenderer()
                super();
                setOpaque(false);
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus,
                                                           int row, int col)
                JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected,
                                                                          hasFocus, row, col);
                lbl.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
                lbl.setFont(table.getTableHeader().getFont());
                return lbl;
        public static void main(String[] args)
            new TableHeaderCellRenderr();
    }thanks
    dayananda b v

    if i reload or refresh whole GUI the table header is moving from first table to the next table,
    i know this is because of same table header i am setting for the other table header,
    how can i achive this Functionality some other way, any suggestions.
    thanks
    daya

  • Custom table header

    Hi all!
    Actually it seems pretty easy but I cannot find an answer in my mind. The problem is simply controlling column widths of multiple JTables with only one table header (consider we add lots of tables with same number of columns in boxlayout (and glued to borders of same container), well handling dragging thing is relatively easy since we may override columnMoved(TableColumnModelEvent e) in JTableHeader but there is nothing like something for resizing column widths or just I cannot see). Is there a way to reach column widths(I dunno maybe some kind of array or get function)?
    do I have to create an custom Event for resizing widths?
    I'm open to any abstract ideas, well do not try to explain things as a source code(If you want you definitely can do but it's kind of burden and it's not the best way to ask for "help" also this way is better for my programming skills, just tell me function or things to extend or implement)
    Anyway, it would be pretty good to learn how to detect a change in a table's column widths(which event, etc...)
    thanks for your helps:))

    to be more precise if there is someone just like me, lookin for this:
    package ComponentDisplayer;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableColumnTest extends JFrame
         public TableColumnTest()
              JTable north = new JTable(5, 10);
              //north.setPreferredScrollableViewportSize(north.getPreferredSize());
              JTable south = new JTable(5, 10);
              //south.setPreferredScrollableViewportSize(south.getPreferredSize());
              south.setColumnModel( north.getColumnModel() );
              south.setTableHeader(north.getTableHeader());
              JPanel jp=new JPanel();
              jp.setLayout(new BoxLayout(jp, BoxLayout.PAGE_AXIS));
              jp.add(north.getTableHeader());
              jp.add(north);
              jp.add(south);
              jp.remove(north);
              /*JScrollPane spsouth=new JScrollPane(south);
              spsouth.setSize(south.getColumnModel().getTotalColumnWidth(),south.getRowCount()*south.getRowHeight());
              spsouth.setMaximumSize(new Dimension(south.getColumnModel().getTotalColumnWidth(),south.getRowCount()*south.getRowHeight()));
              JScrollPane spnorth=new JScrollPane(north);
              spnorth.setSize(north.getColumnModel().getTotalColumnWidth(),north.getRowCount()*north.getRowHeight());
              spnorth.setMaximumSize(new Dimension(north.getColumnModel().getTotalColumnWidth(),north.getRowCount()*north.getRowHeight()));
              jp.add( spnorth);
              jp.add( spsouth);
              north.setValueAt(new String("north"), 0, 0);
              south.setValueAt(new String("south"), 0, 0);
              getContentPane().add(jp);
         public static void main(String[] args)
              TableColumnTest frame = new TableColumnTest();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • JTable have no resize cursor under a JLayeredPane

    Hi,
    i have over my JScrollPane a JLayeredPane to show infotext.
    When the JLayeredPane is over the JScrollpane you can resize the column but the JTable show no resize Cursor.
    Does anybody know why?
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    public class NoResizeCursorDemo extends JFrame
      public NoResizeCursorDemo()
        JTable table = new JTable( new DefaultTableModel( new String[]{ "aaa", "bbb" }, 10 ) );
        JScrollPane scrollPane = new JScrollPane( table );
        InfoLayer layer = new InfoLayer( scrollPane );
        add( layer );
      public static void main( String[] args )
        NoResizeCursorDemo frame = new NoResizeCursorDemo();
        frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
      class InfoLayer extends JLayeredPane
        private final JComponent wrappedComponent;
        public InfoLayer( JComponent wrappedComponent )
          this.wrappedComponent = wrappedComponent;
          setLayout( null );
          add( wrappedComponent, JLayeredPane.DEFAULT_LAYER );
          setInfoText();
        private void setInfoText()
          add( new JLabel( "Info......" ), JLayeredPane.POPUP_LAYER );
          revalidate();
        @Override
        public Dimension getPreferredSize()
          return wrappedComponent.getPreferredSize();
        @Override
        public void doLayout()
          Dimension size = getSize();
          Component layers[] = getComponents();
          for ( Component layer : layers )
            layer.setBounds( 0, 0, size.width, size.height );
    }Thanks

    Hi,
    I had almost the same problem with JTable and JSplitPane, the components worked fine, but cursor did not change when require.
    I already had in place mouse events dispatching in my top layer. It passed all events to the components underneath (see example in [Glass Pane Demo Project|http://java.sun.com/docs/books/tutorial/uiswing/examples/components/GlassPaneDemoProject/src/components/GlassPaneDemo.java]; in my case the listener was the content panel of the top layer).
    And now here is the trick around the cursor. Within the custom dispatch method I've called the following:
    this.setCursor(comp.getCursor());
    where "this" is the content panel of the layer and comp is the component where mouse event passed to.
    Hope that helps!
    Regards,
    Sergey

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Resizing row header of jtable

    hi,
    Is there any way to resize row header column of a jtable just as other columns of jtable. i searched in forums and google but couldnt find any article with resizing row header.
    thanx

    If you want help in the future I suggest you remain a little more patient. It's the weekend. People don't hang around waiting for you to post a question. We answer questions if and when we have time and we know the answer.
    The general answer is yes, of course, it can be done. But we can't give you a specifice answer since you question is so general.
    For example, take a look at my code in this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=639189
    I made the following changes:
    //          addColumn( new TableColumn() );
              TableColumn column = new TableColumn();
              column.setHeaderValue(" ");
              addColumn( column );And then I overrode the following method of the table:
    public void columnMarginChanged(ChangeEvent e)
         super.columnMarginChanged(e);
         TableColumn resizingColumn = getTableHeader().getResizingColumn();
         if (resizingColumn != null)
              Dimension d = getPreferredSize();
              d.width = resizingColumn.getWidth();
              setPreferredScrollableViewportSize(d);
    }and finally
    scrollPane.setRowHeaderView( lineTable );
    scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, lineTable.getTableHeader()); // newOf course we have no idea what component you are using for your row header so we can't give a detailed solution, but I suspect you would need to do something like the following:
    a) add a mouseListener to your component
    b) calculate the change in size of the component using the mouse location changes
    c) set the preferred size of your component
    d) notify the scroll pane of the change in size. I would look at the setPreferredScrollableViewportSize method of JTable to see what it does.

  • JTable does not display table column header

    I create a JFrame with a JScrollPane in which I place a mainPanel (=JPanel ) consisting of a leftPanel (=JPanel ) and a rightPanel (=JPanel ). I add to the rightPanel a JTable using constructor JTable(tableModel dm). I overrode method dm.getColumnName(int coulmnIndex) and verified that this method is being invoked. The JTable is being placed in the rightPanel but without column header.

            // Using BorderLayout
            JTable table = new JTable(tableData, tableHeaders);
            add(table, BorderLayout.CENTER);
            add(table.getTableHeader(), BorderLayout.NORTH);

  • Changing the table header's cursor on roll over

    Hi,
    I would like to change the cursor when the user rolls the mouse pointer over the table header.
    I have tried with header.setCursor(new Cursor(Cursor.HAND_CURSOR)); but it didn't work out.
    Thanks.

    Hi, problem is causing this method in BasicTableHeaderUI:
    public void mouseMoved(MouseEvent e) {
    &nbsp&nbspif (canResize(getResizingColumn(e.getPoint()))) {
    &nbsp&nbsp&nbsp&nbspsetCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
    &nbsp&nbsp} else {
    &nbsp&nbsp&nbsp&nbspsetCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    &nbsp&nbsp}

  • JTable - Clicking table header

    How do I call a JOptionPane or even a JFrame when clicking the table header?

    Thanks Sergio, it helped me but still I can't make event recognize which column was clicked. It seems to be a hard task since I can click a header column without having a column selected, otherwise I could get the column by getColumnName(getSelectedColumn()).
    Do you hv any idea about solving this problem?

  • JCheckBox in table header

    Hi,
    I have a JTable, and I would like to put a JCheckBox in one of the columns table headers. I have searched the forums, and I believe I need to have an editor and renderer (i think)...and I have seen links that ref. examples (such as http://www2.gol.com/users/tame/swing/examples/JTableExamples9.html but they don't work anymore.
    can someone help explain how I would put a checkbox in the header? I understand the renderers and editors (for the most part)...but how do i put them on table header??
    thanks

    Here is what I have now....but if i click semi-quickly on the column header...its like it doesn't catch the event in time. I can click on a regular checkbox as fast as I want, and it obviously catches my clicks..b/c i can see it check/uncheck over and over. Is there some way to make this work better, act smoother?
    public class MyCheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
        private boolean mouseClicked;
        private int currentColumn;
        public MyCheckBoxHeader(JTable table) {
            setHorizontalAlignment(SwingConstants.CENTER);
            JTableHeader tableHeader = table.getTableHeader();
            setBackground(tableHeader.getBackground());
            setForeground(tableHeader.getForeground());
            tableHeader.addMouseListener(this);
        /* (non-Javadoc)
         * @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
        public Component getTableCellRendererComponent(
                JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
            currentColumn = column;
            return this;
         * Had to implement this so the cell would have the same border
         * as the rest of the JTableHeader cells
        /* (non-Javadoc)
         * @see javax.swing.JComponent#paintBorder(java.awt.Graphics)
        protected void paintBorder(Graphics g) {
            g.setColor(Color.WHITE);
            // top
            g.drawLine(0, 0, getWidth(), 0);
            // left
            g.drawLine(0, 0, 0, getHeight());
            g.setColor(Color.BLACK);
            // right
            g.fillRect(getWidth() - 1, 0, 2, getHeight());
            // bottom
            g.fillRect(0, getHeight() - 1, getWidth(), getHeight());
         * Calls doClick(), because the CheckBox doesn't receive any
         * mouseevents itself. (because it is in a CellRendererPane).
       protected void handleClickEvent(MouseEvent e) {
           JTableHeader header = (JTableHeader)(e.getSource());
           JTable tableView = header.getTable();
           TableColumnModel columnModel = tableView.getColumnModel();
           int viewColumn = columnModel.getColumnIndexAtX(e.getX());
           int column = tableView.convertColumnIndexToModel(viewColumn);
           if (viewColumn == currentColumn && e.getClickCount() == 1) {
               doClick();
               repaint();
               int rowCount = tableView.getRowCount();
               for (int i = 0; i < rowCount; i++) {
                   tableView.getModel().setValueAt(new Boolean(isSelected()), i, 0);
       public void mouseClicked(MouseEvent e) {
           handleClickEvent(e);
           // repaint the header to make sure the check is shown in the checkbox
           ((JTableHeader)e.getSource()).revalidate();
       public void mousePressed(MouseEvent e) {
       public void mouseReleased(MouseEvent e) {
       public void mouseEntered(MouseEvent e) {
           setCursor(Cursor.getDefaultCursor());
       public void mouseExited(MouseEvent e) {
    }any suggestions would be helpful...thanks

  • Groupable + multiline table header paint problem

    hi, i try to make a groupable + multiline table header
    based on Nobuo Tamesama's code...
    there are some problems which i considered tolerable except one...
    the header didn't paint correctly when i set the autoResizeMode into autoresizemode_off
    and resize the columns pass the scrollpane width...
    thx in advance
    here's the complete code :
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class GroupableHeaderExample extends JFrame {
        GroupableHeaderExample() {
            super("Groupable Header Example");
            JScrollPane sp = new JScrollPane();
            Object[][] data = {{"b1k1", "b1k2", "b1k3", "b1k4", "b1k5"}, {"b2k1", "b2k2", "b2k3", "b2k4", "b2k5"}};
            JTable table = new JTable(new DefaultTableModel(data, new Object[]{"Kol1", "Kol2\nmmm", "Kol3", "kol4\nmmm\nnnn", " \n \nKol5\nmmm"})) {
                protected JTableHeader createDefaultTableHeader() {
                    return new GroupableTableHeader(columnModel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            ColumnGroup cg = new ColumnGroup("CG", 0, 3);
            ColumnGroup cg2 = new ColumnGroup("CG2\nmmm", 1, 3);
            ColumnGroup cg3 = new ColumnGroup("CG3", 1, 2);
            GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
            header.addColumnGroup(cg3);
            header.addColumnGroup(cg);
            header.addColumnGroup(cg2);
            header.fitHeight();
            sp.setViewportView(table);
            getContentPane().add(sp);
            setSize(400, 300);  
        public static void main(String[] args) {
            GroupableHeaderExample frame = new GroupableHeaderExample();
            frame.addWindowListener( new WindowAdapter() {
                public void windowClosing( WindowEvent e ) {
                    System.exit(0);
            frame.setVisible(true);
    class GroupableTableHeader extends JTableHeader {
        private Vector<ColumnGroup> columnGroups = new Vector<ColumnGroup>(1, 1);
        public GroupableTableHeader(TableColumnModel model) {
            super(model);
            setUI(new GroupableTableHeaderUI());
            setReorderingAllowed(false);
        public void addColumnGroup(ColumnGroup cg) {
            if(columnGroups.size() == 0) {
                columnGroups.addElement(cg);
                return;
            int size = columnGroups.size();
            for(int i = 0; i < size; i++) {
                if(cg.getLength() > ((ColumnGroup)columnGroups.elementAt(i)).getLength())
                    columnGroups.insertElementAt(cg, i);
                else {
                    if(i == size - 1)
                        columnGroups.addElement(cg);           
        public void fitHeight() {
            int[] counter = new int[getTable().getColumnCount()];
            for(int i = 0; i < getTable().getColumnCount(); i++) {
                int level = 0;
                for(int j = 0; j < columnGroups.size(); j++) {
                    if(i >= ((ColumnGroup)columnGroups.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)columnGroups.elementAt(j)).getEndIndex())
                        level = level + getNewLineCount(((ColumnGroup)columnGroups.elementAt(j)).getText());
                counter[i] = level + getNewLineCount(table.getColumnModel().getColumn(i).getHeaderValue().toString());
            int maxCounter = counter[0];
            for(int i = 0; i < counter.length; i++) {
                if(counter[i] > maxCounter)
                    maxCounter = counter;
    setPreferredSize(new Dimension(100, (maxCounter) * 20));
    public Vector getColumnGroups() {
    return columnGroups;
    public int getNewLineCount(String str) {
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    int i = 0;
    boolean b = false;
    for(i = 0; i < v.size(); i++) {
    for(int j = 0; j < v.elementAt(i).length(); j++) {
    if(v.elementAt(i).charAt(j) != ' ') {
    b = true;
    break;
    if(b)
    break;
    if(i == v.size())
    i = 0;
    return v.size() - i;
    public void updateUI(){
    setUI(new GroupableTableHeaderUI());
    class GroupableTableHeaderUI extends BasicTableHeaderUI {     
    public void paint(Graphics g, JComponent c) {
    TableCellRenderer renderer = new MultiLineHeaderRendererEx();
    Component[] cmp = new Component[header.getColumnModel().getColumnCount()];
    Vector cg = ((GroupableTableHeader)header).getColumnGroups();
    Component[] cmpGroup = new Component[cg.size()];
    TableColumnModel tcm = header.getTable().getColumnModel();
    for(int i = 0; i < cmpGroup.length; i++) {
    cmpGroup[i] = renderer.getTableCellRendererComponent(header.getTable(), ((ColumnGroup)cg.elementAt(i)).getText(), false, false, -1, i);
    rendererPane.add(cmpGroup[i]);
    int x = 0;
    int y = 0;
    int height = 20 * ((GroupableTableHeader)header).getNewLineCount(((ColumnGroup)cg.elementAt(i)).getText());
    for(int j = 0; j < ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i == j)
    continue;
    if(((ColumnGroup)cg.elementAt(i)).getStartIndex() >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && ((ColumnGroup)cg.elementAt(i)).getEndIndex() <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    ((ColumnGroup)cg.elementAt(i)).setY(y);
    ((ColumnGroup)cg.elementAt(i)).setHeight(height);
    int width = 0;
    for(int j = ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j <= ((ColumnGroup)cg.elementAt(i)).getEndIndex(); j++)
    width += tcm.getColumn(j).getWidth();
    rendererPane.add(cmpGroup[i]);
    rendererPane.paintComponent(g, cmpGroup[i], header, x, y, width, height, true);
    for(int i = 0; i < cmp.length; i++) {
    cmp[i] = renderer.getTableCellRendererComponent(header.getTable(), header.getColumnModel().getColumn(i).getHeaderValue(), false, false, -1, i);
    rendererPane.add(cmp[i]);
    int x = 0;
    int y = 0;
    for(int j = 0; j < i; j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    rendererPane.add(cmp[i]);
    rendererPane.paintComponent(g, cmp[i], header, x, y, tcm.getColumn(i).getWidth(), (header.getPreferredSize().height - y), true);
    class MultiLineHeaderRendererEx extends JList implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    if(((GroupableTableHeader)table.getTableHeader()).getNewLineCount(value.toString()) == 1) {
    JLabel header = new JLabel();
    header.setForeground(table.getTableHeader().getForeground());
    header.setBackground(table.getTableHeader().getBackground());
    header.setFont(table.getTableHeader().getFont());
    header.setHorizontalAlignment(JLabel.CENTER);
    header.setText(value.toString());
    header.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return header;
    else {
    setOpaque(true);
    setForeground(UIManager.getColor("TableHeader.foreground"));
    setBackground(UIManager.getColor("TableHeader.background"));
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setFont(UIManager.getFont("TableHeader.font"));
    ListCellRenderer renderer = getCellRenderer();
    ((JLabel)renderer).setHorizontalAlignment(SwingConstants.CENTER);
    setCellRenderer(renderer);
    String str = value.toString();
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    setListData(v);
    return this;

    OMG ! the code i posted before is incomplete
    sorry...
    here's the complete one, pls help :
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.border.*;
    import javax.swing.plaf.basic.*;
    public class GroupableHeaderExample extends JFrame {
        GroupableHeaderExample() {
            super("Groupable Header Example");
            JScrollPane sp = new JScrollPane();
            Object[][] data = {{"b1k1", "b1k2", "b1k3", "b1k4", "b1k5"}, {"b2k1", "b2k2", "b2k3", "b2k4", "b2k5"}};
            JTable table = new JTable(new DefaultTableModel(data, new Object[]{"Kol1", "Kol2\nmmm", "Kol3", "kol4\nmmm\nnnn", "Kol5\nmmm"})) {
                protected JTableHeader createDefaultTableHeader() {
                    return new GroupableTableHeader(columnModel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            ColumnGroup cg = new ColumnGroup("CG", 0, 4);
            ColumnGroup cg2 = new ColumnGroup("CG2\nmmm", 1, 4);
            ColumnGroup cg3 = new ColumnGroup("CG3", 1, 2);
            ColumnGroup cg4 = new ColumnGroup("CG4", 3, 4);
            GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
            header.addColumnGroup(cg4);
            header.addColumnGroup(cg2);
            header.addColumnGroup(cg3);
            header.addColumnGroup(cg);
            header.fitHeight();
            sp.setViewportView(table);
            getContentPane().add(sp);
            setSize(400, 300);  
        public static void main(String[] args) {
            GroupableHeaderExample frame = new GroupableHeaderExample();
            frame.addWindowListener( new WindowAdapter() {
                public void windowClosing( WindowEvent e ) {
                    System.exit(0);
            frame.setVisible(true);
    class GroupableTableHeader extends JTableHeader {
        private Vector<ColumnGroup> columnGroups = new Vector<ColumnGroup>(1, 1);
        public GroupableTableHeader(TableColumnModel model) {
            super(model);
            setUI(new GroupableTableHeaderUI());
            setReorderingAllowed(false);
        public void addColumnGroup(ColumnGroup cg) {
            if(columnGroups.size() == 0) {
                columnGroups.addElement(cg);
                return;
            int size = columnGroups.size();
            for(int i = 0; i < size; i++) {
                if(cg.getLength() > ((ColumnGroup)columnGroups.elementAt(i)).getLength()) {
                    columnGroups.insertElementAt(cg, i);
                    break;
                else {
                    if(i == size - 1)
                        columnGroups.addElement(cg);           
        public void fitHeight() {
            int[] counter = new int[getTable().getColumnCount()];
            for(int i = 0; i < getTable().getColumnCount(); i++) {
                int level = 0;
                for(int j = 0; j < columnGroups.size(); j++) {
                    if(i >= ((ColumnGroup)columnGroups.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)columnGroups.elementAt(j)).getEndIndex())
                        level = level + getNewLineCount(((ColumnGroup)columnGroups.elementAt(j)).getText());
                counter[i] = level + getNewLineCount(table.getColumnModel().getColumn(i).getHeaderValue().toString());
            int maxCounter = counter[0];
            for(int i = 0; i < counter.length; i++) {
                if(counter[i] > maxCounter)
                    maxCounter = counter;
    setPreferredSize(new Dimension(100, (maxCounter) * 20));
    public Vector getColumnGroups() {
    return columnGroups;
    public int getNewLineCount(String str) {
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    int i = 0;
    boolean b = false;
    for(i = 0; i < v.size(); i++) {
    for(int j = 0; j < v.elementAt(i).length(); j++) {
    if(v.elementAt(i).charAt(j) != ' ') {
    b = true;
    break;
    if(b)
    break;
    if(i == v.size())
    i = 0;
    return v.size() - i;
    public void updateUI(){
    setUI(new GroupableTableHeaderUI());
    class GroupableTableHeaderUI extends BasicTableHeaderUI {     
    public void paint(Graphics g, JComponent c) {
    TableCellRenderer renderer = new MultiLineHeaderRendererEx();
    Component[] cmp = new Component[header.getColumnModel().getColumnCount()];
    Vector cg = ((GroupableTableHeader)header).getColumnGroups();
    Component[] cmpGroup = new Component[cg.size()];
    TableColumnModel tcm = header.getTable().getColumnModel();
    for(int i = 0; i < cmpGroup.length; i++) {
    cmpGroup[i] = renderer.getTableCellRendererComponent(header.getTable(), ((ColumnGroup)cg.elementAt(i)).getText(), false, false, -1, i);
    int x = 0;
    int y = 0;
    int height = 20 * ((GroupableTableHeader)header).getNewLineCount(((ColumnGroup)cg.elementAt(i)).getText());
    for(int j = 0; j < ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i == j)
    continue;
    if(((ColumnGroup)cg.elementAt(i)).getStartIndex() >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && ((ColumnGroup)cg.elementAt(i)).getEndIndex() <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    ((ColumnGroup)cg.elementAt(i)).setY(y);
    ((ColumnGroup)cg.elementAt(i)).setHeight(height);
    int width = 0;
    for(int j = ((ColumnGroup)cg.elementAt(i)).getStartIndex(); j <= ((ColumnGroup)cg.elementAt(i)).getEndIndex(); j++)
    width += tcm.getColumn(j).getWidth();
    rendererPane.add(cmpGroup[i]);
    rendererPane.paintComponent(g, cmpGroup[i], header, x, y, width, height, true);
    for(int i = 0; i < cmp.length; i++) {
    cmp[i] = renderer.getTableCellRendererComponent(header.getTable(), header.getColumnModel().getColumn(i).getHeaderValue(), false, false, -1, i);
    int x = 0;
    int y = 0;
    for(int j = 0; j < i; j++)
    x += tcm.getColumn(j).getWidth();
    for(int j = 0; j < cmpGroup.length; j++) {
    if(i >= ((ColumnGroup)cg.elementAt(j)).getStartIndex() && i <= ((ColumnGroup)cg.elementAt(j)).getEndIndex())
    y = ((ColumnGroup)cg.elementAt(j)).getY() + ((ColumnGroup)cg.elementAt(j)).getHeight();
    rendererPane.add(cmp[i]);
    rendererPane.paintComponent(g, cmp[i], header, x, y, tcm.getColumn(i).getWidth(), (header.getPreferredSize().height - y), true);
    class MultiLineHeaderRendererEx extends JList implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    if(((GroupableTableHeader)table.getTableHeader()).getNewLineCount(value.toString()) == 1) {
    JLabel header = new JLabel();
    header.setForeground(table.getTableHeader().getForeground());
    header.setBackground(table.getTableHeader().getBackground());
    header.setFont(table.getTableHeader().getFont());
    header.setHorizontalAlignment(JLabel.CENTER);
    header.setText(value.toString());
    header.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return header;
    else {
    setOpaque(true);
    setForeground(UIManager.getColor("TableHeader.foreground"));
    setBackground(UIManager.getColor("TableHeader.background"));
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setFont(UIManager.getFont("TableHeader.font"));
    ListCellRenderer renderer = getCellRenderer();
    ((JLabel)renderer).setHorizontalAlignment(SwingConstants.CENTER);
    setCellRenderer(renderer);
    String str = value.toString();
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector<String> v = new Vector<String>(1, 1);
    try {           
    while((line = br.readLine()) != null) {
    v.addElement(line);
    catch(IOException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage(), "Informasi", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
    setListData(v);
    return this;
    class ColumnGroup {
    private String text;
    private int startIndex, endIndex, y, height;
    public ColumnGroup(String text, int startIndex, int endIndex) {
    this.text = text;
    this.startIndex = startIndex;
    this.endIndex = endIndex;
    public int getEndIndex() {
    return endIndex;
    public int getHeight() {
    return height;
    public int getLength() {
    return endIndex - startIndex;
    public int getStartIndex() {
    return startIndex;
    public String getText() {
    return text;
    public int getY() {
    return y;
    public void setHeight(int height) {
    this.height = height;
    public void setY(int y) {
    this.y = y;

  • How can I right-align a table header?

    Does anyone know a way to right-align a table header?
    For example, in the table below I want the word 'Price' to be right-aligned. I could set the table's 'header renderer' to be a right-aligned DefaultTableCellRenderer, but then the header would look like a cell, not a header. Why can't swing be simple, like table.getColumn(1).setAlignment(Column.RIGHT) ????
    public class TestTableHeader {
         public static void main(String[] args) throws Exception {
              JFrame frame = new JFrame("Test");
              Object[][] rowData = new Object[][] { { "General Electric", "$100.60" },
                        { "IBM", "$5.20" }, { "Wal-mart", "$17.00" } };
              JTable table = new JTable(rowData, new Object[] { "Name", "Price" });
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);
              table.getColumnModel().getColumn(1).setCellRenderer(renderer);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(400, 300);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
    }

    I modified your code an came up with a solution to the problem.
    import java.awt.Component;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    public class TestTableHeader {     
         public static void main(String[] args) throws Exception {
              JFrame frame = new JFrame("Test");
              Object[][] rowData = new Object[][] {
                        { "General Electric", "$100.60" }, { "IBM", "$5.20" },
                        { "Wal-mart", "$17.00" } };
              JTable table = new JTable(rowData, new Object[] { "Name", "Price" });
              RightAlignRender right = new TestTableHeader().new RightAlignRender();
              table.getColumnModel().getColumn(0).setHeaderRenderer(right);
              table.getColumnModel().getColumn(1).setHeaderRenderer(right);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(400, 300);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
         public class RightAlignRender extends DefaultTableCellRenderer {
              public Component getTableCellRendererComponent(JTable table,
                        Object arg1, boolean arg2, boolean arg3, int arg4, int column) {
                   Component toReturn = table.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(table,
                             arg1, arg2, arg3, arg4, column);
                   switch (column) {
                   case 0:
                        ((JLabel) toReturn).setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
                        break;
                   case 1:
                        ((JLabel) toReturn).setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);
                        break;
                   return toReturn;
    }

  • af:table header shows link pointer?

    Hi all,
    I have an <af:table> with no selection, sorting, etc. abilities (I've got a CommandButton in the footer, but other than that it's for display purposes only).
    For some reason, hovering over the table header turns the curser into a "link"-style cursor (default in IE is a hand; you know the one I mean). The facet just contains an outputText; there's no link in sight (and indeed, clicking on the header does nothing). I've been looking at the skinning selectors, but I'm not quite sure how to fix this.
    Thoughts?
    Thanks much,
    Avrom

    Hi Frank,
    It may have something to do with the fact that my table has no column headers. The following code (against a standard HR BC project) produces a table in 10.1.3.2 (and 10.1.3.0; don't have 10.1.3.1) that shows this effect:
    <af:table value="#{bindings.DepartmentsView1.collectionModel}"
                  var="row" rows="#{bindings.DepartmentsView1.rangeSize}"
                  first="#{bindings.DepartmentsView1.rangeStart}"
                  emptyText="#{bindings.DepartmentsView1.viewable ? 'No rows yet.' : 'Access Denied.'}">
        <af:column >
            <af:outputText value="#{row.DepartmentId}">
                <f:convertNumber groupingUsed="false"
                                     pattern="#{bindings.DepartmentsView1.formats.DepartmentId}"/>
            </af:outputText>
        </af:column>
        <af:column >
            <af:outputText value="#{row.DepartmentName}"/>
        </af:column>
        <f:facet name="header">
            <af:outputText value="Departments" />
        </f:facet>
    </af:table>[Edit: Any further word on this? Column headers aren't supposed to be a required part of a table, are they?]
    Message was edited by:
    Avrom

  • XP Table Header on 1.4.2_06

    Hi there
    I have a JTable with five columns. On the first two columns, I have made custom renderers to show a picture in the table header. The rest of the columns are normal.
    There is a screenshot of what I mean at the site below.
    http://www.geocities.com/rezrovs/tableheader.JPG
    Please could someone tell me how to get the border that is applied to these normal columns so that I can apply the border to the custom headers.
    Many thanks,
    Rachel

    Have you tried something like:
    public Component getTableCellRendererComponent(javax.swing.JTable table,
                                                             Object  value,
                                                             boolean isSelected,
                                                             boolean hasFocus,
                                                             int     row,
                                                             int     column) {
         Component comp = super.getTableCellRendererComponent(table, value, isSelected,
                                                                 hasFocus, row, column);
         if (comp != null && comp instanceof JLabel) {
              JLabel returnLabel = (JLabel)comp;
              ImageIcon icon = null;
              int hAlign = returnLabel.getHorizontalAlignment();
              String text = null;
              switch(column){
                   case(0): { icon = Utils.GRIDPRIORITYICON; hAlign = JLabel.CENTER; break; }
                   case(1): { icon = Utils.GRIDATTACHICON;   hAlign = JLabel.CENTER; break; }
                   default:  { text = (value == null) ? "" : value.toString();  }
                    if (icon != null) returnLabel.setIcon(icon);
                    if (text != null) returnLabel.setText(text);
                    returnLabel.setHorizontalAlignment(hAlign);
            return comp;
    }

  • Missing Table Header

    Hi,
    Can someone tell my why I can't see my table headers. I have placed the table inside the JScrollPane but it still doesn't work.
    package tablepractice;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class TableFrame
        private JScrollPane scrollPane;
        private TableData tableData;
        private JTable table;
        private JPanel tablePanel;
        public TableFrame()
            tablePanel = new JPanel();
            tableData = new TableData();
            table = new JTable(tableData);
            TableColumnModel tcm = table.getColumnModel();
            TableColumn tc = tcm.getColumn(TableData.DOB);
            MultiLineHeaderRenderer mlhr = new MultiLineHeaderRenderer();
            tc.setHeaderRenderer(mlhr);
            scrollPane = new JScrollPane(table);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            tablePanel.add(scrollPane);
            createAndShowGUI();
        public void addComponentsToPane(Container pane)
            pane.setLayout(new GridBagLayout());
            GridBagConstraints constraints = new GridBagConstraints();
            constraints.fill = GridBagConstraints.HORIZONTAL;
            constraints.gridx              = 0;
            constraints.gridy              = 0;
            constraints.gridheight         = 4;
            constraints.gridwidth          = 5;
            pane.add(tablePanel, constraints);
        private void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame frame = new JFrame("");
            frame.setDefaultLookAndFeelDecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set up the content pane.
            addComponentsToPane(frame.getContentPane());
            //Display the window.
            frame.pack();
            frame.setResizable(true);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    new TableFrame();
    ["code"]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Well the basics of displaying a table is straight forward:
    JTable table = new JTable(5, 10);
    JScrollPane scrollPane = new JScrollPane( table );
    getContentPane().add( scrollPane );
    So start with simply displaying a table and then add in you customizations to see where the problem is. For example:
    1) Why do you create a 'tablePanel' and add the scroll pane to the tablePanel which you add to the contentPane. This is unnecessary.
    2) Try your code without the GridBagLayout
    3) You are using a custom header renderer. Try you code without the renderer.
    4) You are overriding the viewport size.
    Start simple add complexity and determine where the problem is rather than asking a generic 'whats wrong" question.

Maybe you are looking for

  • How do I copy my own movies from a DVD to my imac so I can edit? them.

    I have made  a number of VCR to DVD coversions and also DV camcorder imprints on DVD+R discs. I now would like to load these onto my iMac for further editing before i either reburn to another DVD the finished product to send to my children. These are

  • Text not appearing in Variable selection screen

    Hi When I select a value for an info object (say Plant) in the selection screen and click on "Check" in BEX usually text of the chosen plant appears on the right. But in case of some info objects it doesn't appear. Can someone please guide as to what

  • Time offset is not set properly when db is in Eire timezone

    Hi, We are using oracle 10g database (10.2.0.4) on Solaris box (sparc) for an enterprise product in Eire timezone. we see Oracle time offset set as "+01:00" for one of the db column whose data type is TIMESTAMP(6) WITH TIMEZONE. As per the Eire timez

  • Adding BO System in SLD

    Hi,       For ABAP systems we add it in SLD through RZ70 & for Java through Visual Admin.How to add BO system(SAP BusinessObjects Enterprise XI 3.1 ) in SLD?Is there anyway we can add it through CMC?

  • What is the weblogic process or file opened with udp port?

    I'm running weblogic 8.1 on linux AS 3.0, whenever I bring it up, there is a process that listens on udp, although my weblogic runs on default tcp port 7001. What file or process opened with up port (32770)? I'm curious to know whats running with udp