JTable Header resizing codes ?

Does anyone have reusable codes that can accept the column names then resize the JTable columns automatically. By using the column names width the table headers are automatically computed to column preferred size.

Please refer to http://www2.gol.com/users/tame/swing/examples/SwingExamples.html for a possible solution.

Similar Messages

  • JTable header resizing problame.

    Hi All,
    I am using one JTabl with table header and i want to give resizing to all selected header column when any one one of them getResized by mouse dragging (just like EXCEL sheet)
    is it possible ??
    Any body can suggest some example or any tips on this.
    thanx in advance.
    == Gavin

    Any body can suggest some example or any tips on this.You where given a "tip" 6 days ago when you asked the same question:
    http://forum.java.sun.com/thread.jspa?threadID=582056&messageID=2962393

  • How do i change the cursor on a jtable header when clicked for sorting?

    here is my question, how do i change the cursor on a jtable header when I click the header for sorting?
    I think it is suppose to be in the fragment of code where the header listener is implemented for sorting, but I'm not quite sure what is the exact component that holds everything so that i can change the cursor...
    below is what I've tried, but it doesn't seem to work... thank you
    public void addMouseListenerToHeaderInTable(JTable table) {
    final TableSorter sorter = this;
    final JTable tableView = table;
    tableView.setColumnSelectionAllowed(false);
    MouseAdapter listMouseListener = new
    MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    TableColumnModel columnModel =
    tableView.getColumnModel();
    int viewColumn =
    columnModel.getColumnIndexAtX(e.getX());
    int column =
    tableView.convertColumnIndexToModel
    (viewColumn);
    System.out.println("column = "+column);
    if (e.getClickCount() == 1 && column != -1) {
    System.out.println("Sorting ...");
    Cursor oldCursor =
    tableView.getRootPane().getCursor();
    System.out.println("oldCursor.getType()
    = "+oldCursor.getType());
    if (oldCursor.getType() !=
    Cursor.WAIT_CURSOR){
    JComponent parentPane =
    tableView.getRootPane();
    parentPane.getContentPane().setCursor
    (new Cursor(Cursor.WAIT_CURSOR));
    parentPane.setCursor(new Cursor
    (Cursor.WAIT_CURSOR));
    Cursor newCursor =
    parentPane.getCursor();
    System.out.println("newCursor.getType
    () = "+newCursor.getType());
    int shiftPressed = e.getModifiers(
    &InputEvent.SHIFT_MASK;
    boolean ascending = (shiftPressed == 0);
    //System.out.println("tableView.getRootPane()
    is "+tableView.getRootPane().getRootPane());
    sorter.sortByColumn(column, ascending);
    tableView.getRootPane().setCursor(new Cursor
    (Cursor.DEFAULT_CURSOR));
    //System.out.println("Done sorting");
    JTableHeader th = tableView.getTableHeader();
    th.addMouseListener(listMouseListener);
    }

    Hi,
    Try setting the cursor for the table header.
    table.getHeader().setCursor(Wait_Cursor);
    Bala.

  • Not able to edit the JTextField under the JTable header

    Hi,
    As per my requirement, i need to add the text field in JTable header for filtering the table records.
    i have added the text field but not able to enter any value (it is disabled).
    Can anyone please help me on this?

    Welcome to the forum.
    After reading how to format Code in this forum (SQL and PL/SQL FAQ ),
    please show us the code of your TableHeader implementation.
    bye
    TPD

  • How to make JTable Header to Blink?

    Hi Everybody...
    I need the code to blink the JTable Header in Java Swings..
    Im trying since long time...
    Please help me out...
    Thanks in Advance...

    I have posted it by mistakly...yeh, just like you mistakly cross-posted your other thread/s at javaranch.
    i think u dont think positivly..Oh I positivly know you're a fcukwit
    better for you to toodle off and try to write a Hello World app.

  • Highlight JTable Header

    Hello,
    I want to be able to change the color of a JTable header of a column ie highlight it when a user clicks on the table header. Is there a way to do this? I'vd done a google search but nothing seems to address this. Any help is much appreciated. Thanks.
    vyang

    Try this piece of code on for size. The HeaderRenderer class is far from complete but it should give you something substancial to work with. This renderer also using GradientPainting to give you an extra boost in terms of appearance.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class HeaderRenderer extends DefaultTableCellRenderer implements
                    MouseListener, MouseMotionListener {
        Color bg = new Color(242,242,255), fg = Color.black;
        Rectangle paintingRect = null,
            lpr = null; //last painted rect
        JTableHeader header = null;
        public boolean isOnCol = false, highlightClickedCol = false;
        private int paintingCol = -1, clickedCol = -1, currentCol = -1;
         * Buffer gradient paint.
        GradientPaint gp = null, hoverGradient, columnGradient;
         * The current sorting state of the columns
        SortOrder sortOrder = null;
        public HeaderRenderer() {
            super();
            setFont( getFont().deriveFont(Font.BOLD) );
            //setBackground( bg );
            setForeground( fg );
            setOpaque(false);
            setBorder( BorderFactory.createCompoundBorder (BorderFactory.createMatteBorder(0,0,1,1, new Color(200,200,230) ),
                            BorderFactory.createEmptyBorder(4,7,4,4)) );
            setHighlightClickedColumn(true);
        public void setColumnGradient(GradientPaint gp) {
            this.columnGradient = gp;
        public void setHoverGradient(GradientPaint gp) {
            this.hoverGradient = gp;
        public GradientPaint getColumnGradient() {
            return columnGradient;
        public GradientPaint getHoverGradient() {
            return hoverGradient;
        public void setHighlightClickedColumn(boolean b) {
            highlightClickedCol = b;
        public void paintComponent(Graphics g) {
            Rectangle rect = paintingRect;
            Graphics2D g2 = (Graphics2D)g;
                g2.setPaint(gp);
                g2.fillRect( 0, 0, rect.width, rect.height );
            FontMetrics fm = g.getFontMetrics();
            int strWidth = fm.stringWidth( getText() );
            /*if(currentCol == clickedCol) {
                if( sortOrder == SortOrder.ASCENDING )
                    new ArrowIcon( ArrowIcon.UP ).paintIcon(this, g, strWidth + 15, 8);
                else if(sortOrder == SortOrder.DESCENDING )
                    new ArrowIcon( ArrowIcon.DOWN ).paintIcon(this, g, strWidth + 15, 8);
            sortOrder = null;
            super.paintComponent(g);
        public void attachListener() {
            header.addMouseListener(this);
            header.addMouseMotionListener(this);
        public void mouseEntered(MouseEvent e) {
            isOnCol = true;
        public void mouseExited(MouseEvent e) {
            isOnCol = false;
            paintingCol = -1;
            header.repaint();
        public void mouseReleased(MouseEvent e) {}
        public void mouseClicked(MouseEvent e) {
            clickedCol = header.columnAtPoint( e.getPoint() );
        public void mousePressed(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {
           // isOnRow = true;
            paintingCol = header.columnAtPoint( e.getPoint() );
            paintingRect = header.getHeaderRect( paintingCol );
            header.repaint( paintingRect.x, paintingRect.y, paintingRect.width, paintingRect.height );
            if(lpr != null) {
                header.repaint(lpr.x, lpr.y, lpr.width, lpr.height);
            lpr = paintingRect;
        public void mouseDragged(MouseEvent e) {
            //isOnRow = true;
            paintingCol = header.columnAtPoint( e.getPoint() );
            paintingRect = header.getHeaderRect( paintingCol );
            header.repaint( paintingRect.x, paintingRect.y, paintingRect.width, paintingRect.height );
            if(lpr != null) {
                header.repaint(lpr.x, lpr.y, lpr.width, lpr.height);
            lpr = paintingRect;
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
             boolean hasFocus, int row, int col) {
            currentCol = col;
            if(header == null) {
                header = table.getTableHeader();
                attachListener();
            if(table.getRowSorter() != null && table.getRowSorter().getSortKeys().size() > 0 ) {
                java.util.List<? extends RowSorter.SortKey> keys = table.getRowSorter().getSortKeys();
                for(RowSorter.SortKey key: keys) {
                    if(key.getColumn() == col) {
                        sortOrder = key.getSortOrder();
            Rectangle rect = table.getTableHeader().getHeaderRect(col);
            if( (isOnCol && paintingCol == col) || (clickedCol == col && highlightClickedCol)  ) {
                gp = new GradientPaint( rect.x, rect.y + rect.height, new Color(200,220,235),
                                    rect.x, rect.y, new Color(230,235,250)  );
                setForeground( new Color(50,50,50) );
            } else {
                gp = new GradientPaint( rect.x, rect.y + rect.height, new Color(235,240,245) ,
                                        rect.x, rect.y, new Color(245,250,255) );
                setForeground( new Color(100,120,160) );
            paintingRect = rect;
            //JLabel renderer = new JLabel();
            setText( value == null ? "" : value.toString() );
            //setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
            //   brdr) );
            return this;
        public static void main(String[] args) {
            DefaultTableModel model = new DefaultTableModel(20,5);
            JTable table = new JTable( model );
                table.getTableHeader().setDefaultRenderer( new HeaderRenderer() );
            JFrame frame = new JFrame("Header Renderer Test");
                frame.add( new JScrollPane(table) );
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
    }ICE

  • How to add  ComboBox in Jtable Header

    Hello everyone,
    I want to add a Combox box in JTable Header .Basically it works as central access to whole table e.g. by selecting delete row in combo box then it should delete the current selected row.If somebody has any idea please share it.
    Thanks in advance.

    The individual headers are not Swing components and therefore do not respond to mouse events in the same way as Swing components. Why don't you just have a popup menu that is positioned over the currently selected row? If you want to apply an action to all selected rows then have a set of buttons placed above the table header.

  • JComboBox in the JTable Header - TableCellEditor problem

    Hi,
    I have added JComboBox into the JTableHeader. But I can't Edit that combobox. It is looking like an icon. I have added JPanel into the JTable Header Row. In JPanel i have added one JLable and JComboBox.
    Please any one of you give me the solution.
    Thanks,
    Shrini V.

    The table will display what ever value it has in its model. When you add the row, there is no data in the second column. You'll have to supply it.
    public void insertMyRowCombo (Object [] r,
                                      JComboBox c,
                                      JTable t) {
           // {"rut", "puntaje cas", "beneficio", "fecha inicio", "fecha termino", "monto"};
            DefaultTableModel tm = (DefaultTableModel) t.getModel();
            tm.addRow(r);
            TableColumn col = t.getColumnModel().getColumn(2);
            col.setCellEditor(new DefaultCellEditor(c));
            tm.setValueAt( c.getItemAt(0), 0, 2); //manually supply the value to col 2
        }ICE

  • Multiple Icon on Jtable header

    Hi All:
    Any one had used multiple icons on JTable header ? According to the user's clicking positon under one column, one of these icons should change such as changing from sorting up arrows to sorting down arrows.
    I got the mouse clicking position on the header and column, then depend on the location, I wanted to perfrom different things. But I have not figured out if I should call header renderer to perform the repaint or not ? If I use JTable header render, how should I confine the one column that change should happen? I don't want to have all columns repainted. If I treat each column indivisually, should I reconstruct the JTable ? I used SortableTableModel to create the JTable.
    Any help is appreciated.
    Regards

    Here's the idea. I didn't test thisclass JComponentCellRenderer extends JButton implements TableCellRenderer {
        public JComponentCellRenderer (ImageIcon ii) { super("",ii); }
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            setText(value.toString());
            return this;
    }and thentblChanges.getColumnModel().getColumn(0).setHeaderRenderer(new JComponentCellRenderer(new ImageIcon( "CheckBoxHeaderImage" )));

  • How to set height of JTable Header ?

    How to set height of JTable Header and set the text to another size ?

    You can set the font of the header as you can for any component. The font will dictate the preferred height of the header. If you don't like the preferred height, you can set that as well.
    // add table to a scroll pane or the header will not appear
    JTable table = new JTable(...);
    container.add(new JScrollPane(table));
    // get a reference to the header, set the font
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font(...));
    // set the preferred height of the header to 50 pixels.
    // the width is ignored by the scroll pane.
    header.setPreferredSize(new Dimension(1, 50));Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • Changing jtable header when moving down

    Hi,
    I would need changing Jtable header, when the cursor switches between lines
    How to do this ???
    Best Regards
    S.Ancelot

    1) You could create a second table header and replace the old one using scrollPane.setColumnHeaderView(...)
    2) Or, you could simply change the values in each TableColumn and then repaint the header.

  • Remove JTable header

    i created a small JFrame to test removing the JTable header
    the Sutation : a JTable in JScrollPane in JPannel.
    the Test as well as my program.
    i create Model in both cases. my won.
    the properties of the both components are almost the same.
    the diffrence : in the test JFrame look great.
    in my program it remains a small hieght from the Header about 2pixels. and i can see it.
    any help?
    thx

    i created a small JFrame to test removing the JTable
    header
    the Sutation : a JTable in JScrollPane in JPannel.I can follow you up to this point
    the Test as well as my program.? the test of what? and what did they do? you forgot a verb ...
    i create Model in both cases. my won.two cases ... which are they? and which is your case that won?
    the properties of the both components are almost the
    same.oh, two components ... and which are they?
    >
    the diffrence : in the test JFrame look great.which test?
    in my program it remains a small hieght from thewhere is the difference between a test of your program and your program?
    Header about 2pixels. and i can see it.
    any help?sorry, please explain clearly what your problem is.
    thxRommie.

  • How to remove JTable header from JScrollPane?

    Hi!
    Does anyone know how to remove the JTable header from the JScrollPane the table is placed in? I tried calling
    scrollpane.setColumnHeader( null ) and
    scrollpane.setColumnHeaderView( null )
    but none of the above worked...
    Thanks!
    Fil

    Hi,
    The easiest way to do this is to put an extra layer between the table and the scrollpane as follows:-
    JPanel p = new JPanel(new BorderLayout());
    // Add it to the north rather than center so that the table background color
    // won't cover the empty part of the view port.
    p.add(table, BorderLayout.NORTH);
    JViewport v = tableScroll.getViewport();
    v.setView(p);
    where table is your JTable and tableScroll is your JScrollPane.
    Hope this helps,
    Ian

  • JTable Header Problemm ....code is below

    class MyDisplayTableModel extends AbstractTableModel{
                    HashMap map ;
                   String[] COLUMN_NAMES = {
              "COLUMN_1",
              "COLUMN_2",
              "COLUMN_3"
           public MapDisplayTableModel(String a, String b, HashMap map){
              this.map  = map;
         public int getRowCount() {
              return map.size();
         public int getColumnCount() {
              return COLUMN_NAMES.length;
         public String getColumnName(int col){
              return COLUMN_NAMES[col];
        public boolean isCellEditable(int row, int column) { return true; }
        public void setValueAt(Object value, int row, int col)
    LeftRightColumn existingLeftRightColumn = null;
    for (Iterator it=this.map.entrySet().iterator(); it.hasNext(); ) {
          Map.Entry entry = (Map.Entry)it.next();
          String key = (String)entry.getKey();
          if(key.equals(String.valueOf(row)))
    existingLeftRightColumn = (LeftRightColumn)entry.getValue();
    if(existingLeftRightColumn != null)
                if(col == 0)
                   this.map.put(String.valueOf(row),new LeftRightColumn((String)value,existingLeftRightColumn.leftColumn,existingLeftRightColumn.rightColumn));
                             fireTableCellUpdated(row, 0);
                   if(col == 1)
                        this.map.put(String.valueOf(row),new LeftRightColumn(existingLeftRightColumn.agent,(String)value,existingLeftRightColumn.rightColumn));
         fireTableCellUpdated(row, 1);
         if(col == 2)
                        this.map.put(String.valueOf(row),new LeftRightColumn(existingLeftRightColumn.agent,existingLeftRightColumn.leftColumn,(String)value));
         fireTableCellUpdated(row, 2);
         public Object getValueAt(int row, int col) {
         LeftRightColumn existingLeftRightColumn = null;
         for (Iterator it=this.map.entrySet().iterator(); it.hasNext(); ) {
                       Map.Entry entry = (Map.Entry)it.next();
                       String key = (String)entry.getKey();
                       if(key.equals(String.valueOf(row)))
                            existingLeftRightColumn = (LeftRightColumn)entry.getValue();
              if(existingLeftRightColumn != null)
                   switch(col){
                   case 0:
                                            return existingLeftRightColumn.agent;
                   case 1:
                                            return existingLeftRightColumn.leftColumn;
                   case 2:
                                            return existingLeftRightColumn.rightColumn;
              else
              return null;
    class LeftRightColumn
                   String agent;
                   String leftColumn;
                   String rightColumn;
                   LeftRightColumn(String agent,String left,String right)
                        this.agent = agent;
                        this.leftColumn = left;
                        this.rightColumn = right;
         }THis is the table that I have and I display the table with different names how can I do that an the table is being displayed as follows
    public SampleDiferencesDialog(JDialog owner, MyClass selNode, MyClass cmpNode)
    HashMap hm = new HashMap();
         HashMap selNodeMap = selNode.getAttributes();
         HashMap cmpNodeMap = cmpNode.getAttributes();
    TableModel tm = new MapDisplayTableModel(selNode.getName(), cmpNode.getName(), hm);
    JTable table = new JTable(tm);
    JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
    table.getModel().addTableModelListener(this);
    differencePanel.add(scrollPane);I will have three columns one say "A" and the second sel.getName() and the third cmp.getName()....I am not able to know how to do that Can some one help me out please

    Basic manner on the public forum:
    Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html
    have three columns one say "A" and the second sel.getName() and the third cmp.getName()....Then your column related methods on the MyDisplayTableModel class should be insufficient and wrong. Current code is using hard-coded String literals for column titles.

  • JTable user resize columns with grid?

    Is it possible to allow a user to resize columns not just through the table header, but with the vertical grid lines?

    There is no method that allows you to toggle this
    feature on/off if thats what you are asking.Yes, thats what I was asking.
    If you want to implement this type of functionality
    yourself then take a look at the source code for
    JTableHeader to see how its done.Thanks, I'll look into that - though it would be cool if that was already a feature of JTable.

Maybe you are looking for

  • PDF plugin problem

    Hello everyone, a customer of us is having problems displaying PDF forms in Workspace ES. They are using IE7 with Reader 9.2. Reader is the standard application for PDF files, the "Display PDFs in browser" option has been set, but Workspace is still

  • HT1095 burn my movie to DVD without iDVD

    How do I burn my movie to DVD? I bought a Macpro last November and there's no iDVD.

  • Brand New Samsung s4 Won't Install Apps

    My Samsung S4 (brand new last night) won't install any apps. I click install, and it highlights like it's going to, but then it does nothing.

  • E4X and reserved characters in names

    I'm receiving an RSS feed from a source I can't change. Each item record has the following structure... <item xmlns:media=" http://search.yahoo.com/mrss/"> <title>Sample Title</title> <link> http://sampleURL.com</link> <description>Some text here</de

  • My iphone4 screen wont work is there a way i can upgrade it ?or get a new one?

    my iphone screen went black. Is there a way i can upgrade it?or can i pay money to get a new on ?also my lock button wont work either!? PLEASE HELP!i need to fix it as soon as posible [also need to know were i can replace it]