JTable in JPanel last Column resize clips JTable doesnt repaint JPanel

I have a JTable in a JPanel, when I drag the last column of the JTableHeader (u can see the column resizing as the text of the Table HeaderColumn moves with the drag) the JTable is outside the JPanel. Only when u click on another component and then click back on the JTableHeader does it repaint.
I have tried jPanel.revalidate(); in the mouseDragged event of MouseMotionListener on the JTableHeader and all manner or repaints and fireTableStructureChanged. But I dont understand the order of events.
The last bug to fix!!!
NB I dont want to use scrollpane as its not necessary and as many tables are synchronized with one table it makes repaints less smooth
Thanks Paul

Well, I didn't find an answer but I did find a solution.
The JPanel is the problem. I use it to help with layout which is not obvious in this example.
As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
I would still like to know why?
////////KBS
JTabbedPane myTP = new JTabbedPane();
Box myOne = Box.createHorizontalBox();
Box myTwo = Box.createHorizontalBox();
myOne.add(pane);
myTP.add("One", myOne);
myTP.add("Two", myTwo);
////////KBS

Similar Messages

  • Last column in JTable detaches from edge of JScroll Pane

    i have a JTable in a JScrollPane which is in half of a JSplitPane.
    The table has autoResizeMode set to AUTO_RESIZE_OFF to make the horizontal scrollbar appear.
    However, when i resize the split pane to make the table bigger, the edge of the last column no longer runs to the edge of the JScrollPane, it detaches.
    What i need is for the last column to be able to expand infinitely, but when the split pane size is being reduced, for the columns to disapear off the edge of the scroll pane and the scroll bar to appear. This is a mix of AUTO_RESIZE_OFF and AUTO_RESIZE_LAST_COLUMN.

    I too had this problem. I had a method that would set the minimum size of columns based on the data within the table, etc. It seems that when you do anything to set the pref or min size of a column the horizontal scrolling gets all messed up. How I solved the problem is to basically swap the autosize method on the table back and forth whenever the parent component of the table is resized. Some example code follows.
    First, add a inner class ComponentListener on the parent component the table is in (a frame in my case, I guess this could be the scroll pane too?):
    _myFrame.addComponentListener( new ComponentAdapter()
        public void componentResized(ComponentEvent e)
            _parentResized();
    });Now the _parentResized() method that is called by the inner class looks like this:
    * Our parent container component was resized, so update how the table's
    * columns are layed out.
    private void _parentResized()
        TableColumnModel tcm = _table.getColumnModel();
        int colWidth = 0;
        for( int j = 0; j < tcm.getColumnCount(); j++ )
            colWidth += tcm.getColumn( j ).getPreferredWidth();
        // Have to check scroll for width > 0, because the first time this gets
        // called, it is 0, and that will cause the viewport to scale to fit the
        // entire table (which could be bad).  Note that this will get updated
        // if the window is resized as well.
        if( _tableScroll.getWidth() > 0 && colWidth < _tableScroll.getWidth() )
            _table.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
        else
            _table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    }What that does is whenever the table's parent component is resized it evaluates the pref width of the whole table, if it's greater than the scrollpane's width, it turns autosizing of columns off (which will make the horiz scrollbar work properly), if it is less than the scrollpane's width, it turns autosizing on. Hackish I know.
    You need to make sure to call the _parentResized() method as well whenver you do something else that might cause the pref width of the table to be resized (like you repopulate and calc pref widths, etc.)
    Hope this is of some use to you.

  • JTable:  resizing all columns as 1 column resizes

    I have a JTable with 480 columns inside of a JScrollPane (AUTO_RESIZE_ALL_COLUMNS needs to be off for the JTABLE to display correctly in the JScrollPane). When the user resizes one column I would like the rest of the columns to resize too, so that the column widths of each column are equal.
    Thank you in advance,
    Brent

    [...] I
    I have the JScrollPane listening to a histogram of the
    balances so the user can click on a month in the
    histogram and the JScrollPane (actually JViewport)
    will move to display the appropriate column in the
    JTable. If the column sizes are not uniform then I
    cannot be sure that I'm moving the JViewport to
    display the correct JTable column(s).
    I thing the GUI is a great design for what must be
    done. And thank you for your help and comments.That still sounds pretty klunky. I don't see any user navigating around a 480 column table. They click in your histogram to go to a column, they click somewhere or do keyboard navigation and the display scrolls them a few columns/rows away... they are now lost in a sea of cells and have to go back to the histogram again to try and get back, etc. Having delt with similar situations, there are better ways. Read the last two days dilbert cartoons carefully. :-)
    But anyway...
    You don't have to have all the columns the same width to make a column visible in the viewport. You can just get the appropriate column's rect by either of these methods:Rectangle r = myTable.getTableHeader().getHeaderRect( col );
    Rectangle r = myTable.getCellRect( row, col, true );And then tell the viewport to make sure that rect is visible:myViewport.scrollRectToVisible( r );Much easier than hacking around with custom column resizing logic.

  • Mapping of JTable Rows and columns and paint it to the JPanel

    Hi,
    I am using JTable and graphics object to draw the JTable on JPanel. But due to some lack of measurement I am not able to draw table cells correctly.
    Apart from this on changing the fontSize I have to redraw it according to the requirement. But when the data size increases it draws absurdly.
    I am using jTable.getCellRect() api to get the row width and height. Please help to redraw a JTable cell row and height on JPanel.
    I am also attaching a sample code with this mail.
    Thanks,
    Ajay
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.table.*;
    import java.util.*;
    import java.awt.*;
    public class SimpleTableDemo extends JPanel {
        private boolean DEBUG = false;
           private int spacing = 6;
           private Map columnSizes = new HashMap();
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
             {"Kathy", "Smith",
              "SnowboardingXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", new Integer(5), new Boolean(false)},
             {"John", "Doe",
              "Rowing", new Integer(3), new Boolean(true)},
             {"Sue", "Black",
              "Knitting", new Integer(2), new Boolean(false)},
             {"Jane", "White",
              "Speed reading", new Integer(20), new Boolean(true)},
             {"Joe", "Brown",
              "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
              Panel1 panel;
        public SimpleTableDemo() {
            super(new GridLayout(3,0));
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //table.setFillsViewportHeight(true);
            if (DEBUG) {
                table.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                        printDebugData(table);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            panel = new Panel1();
            Rectangle rect = table.getCellRect(0,0,true);
              panel.setX(table.getWidth());
              panel.setY(0);
            panel.setWidth(rect.width);
              panel.setHeight(rect.height);
            panel.setStr(table.getModel().getValueAt(0,0).toString());
              panel.setModel(table);
              add(panel);
            final JComboBox jNumberComboBoxSize = new JComboBox();
              jNumberComboBoxSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "11", "12", "14", "16", "18", "20", "24", "30", "36", "48", "72" }));
            jNumberComboBoxSize.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                   jNumberComboBoxSizeActionPerformed(jNumberComboBoxSize);
              JPanel panel2 = new JPanel();
              panel2.add(jNumberComboBoxSize);
              add(panel2);
              adjustColumns();
         private void jNumberComboBoxSizeActionPerformed(JComboBox jNumberComboBoxSize)
            int fontSize = Integer.parseInt(jNumberComboBoxSize.getSelectedItem().toString());
              table.setRowHeight(fontSize);
              table.setFont(new Font("Serif", Font.BOLD, fontSize));
              Rectangle rect = table.getCellRect(0,0,true);
              panel.setX(0);
              panel.setY(0);
           // panel.setWidth(rect.width);
              panel.setHeight(rect.height);
            panel.setStr(table.getModel().getValueAt(0,0).toString());
              panel.setModel(table);
              panel.repaint();
              table.revalidate();
        private void printDebugData(JTable table) {
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            System.out.println("Value of data: ");
            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
                System.out.println();
            System.out.println("--------------------------");
          *  Adjust the widths of all the columns in the table
         public void adjustColumns()
              TableColumnModel tcm = table.getColumnModel();
              for (int i = 0; i < tcm.getColumnCount(); i++)
                   adjustColumn(i);
          *  Adjust the width of the specified column in the table
         public void adjustColumn(final int column)
              TableColumn tableColumn = table.getColumnModel().getColumn(column);
              if (! tableColumn.getResizable()) return;
              int columnHeaderWidth = getColumnHeaderWidth( column );
              int columnDataWidth   = getColumnDataWidth( column );
              int preferredWidth    = Math.max(columnHeaderWidth, columnDataWidth);
            panel.setWidth(preferredWidth);
              updateTableColumn(column, preferredWidth);
          *  Calculated the width based on the column name
         private int getColumnHeaderWidth(int column)
              TableColumn tableColumn = table.getColumnModel().getColumn(column);
              Object value = tableColumn.getHeaderValue();
              TableCellRenderer renderer = tableColumn.getHeaderRenderer();
              if (renderer == null)
                   renderer = table.getTableHeader().getDefaultRenderer();
              Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, column);
              return c.getPreferredSize().width;
          *  Calculate the width based on the widest cell renderer for the
          *  given column.
         private int getColumnDataWidth(int column)
              int preferredWidth = 0;
              int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();
              for (int row = 0; row < table.getRowCount(); row++)
                  preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));
                   //  We've exceeded the maximum width, no need to check other rows
                   if (preferredWidth >= maxWidth)
                       break;
              return preferredWidth;
          *  Get the preferred width for the specified cell
         private int getCellDataWidth(int row, int column)
              //  Inovke the renderer for the cell to calculate the preferred width
              TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
              Component c = table.prepareRenderer(cellRenderer, row, column);
              int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
              return width;
          *  Update the TableColumn with the newly calculated width
         private void updateTableColumn(int column, int width)
              final TableColumn tableColumn = table.getColumnModel().getColumn(column);
              if (! tableColumn.getResizable()) return;
              width += spacing;
              //  Don't shrink the column width
              width = Math.max(width, tableColumn.getPreferredWidth());
              columnSizes.put(tableColumn, new Integer(tableColumn.getWidth()));
              table.getTableHeader().setResizingColumn(tableColumn);
              tableColumn.setWidth(width);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("SimpleTableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            SimpleTableDemo newContentPane = new SimpleTableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    class Panel1 extends JPanel
        int x;
         int y;
         int width;
         int height;
         String str;
         JTable model;
        public void setModel(JTable model)
           this.model = model;
         public void setX(int x)
              this.x = x;
        public void setY(int y)
              this.y = y;
         public void setWidth(int w)
              this.width = w;
        public void setHeight(int h)
              this.height = h;
         public void setStr(String s)
              this.str = s;
        public void paint(Graphics g)
             super.paint(g);
              int initX= 0;
              for(int row=0;row < 5; ++row)
                   initX = x;
                   for (int col=0;col < 5;++col)
                        g.drawRect(x,y,width,height);
                        g.drawString(model.getModel().getValueAt(row,col).toString(),x + 10,y + 10);
                        x = x + width;
                x = initX;
                   y = y + height;
    };

    an easy way would be to use setSize()

  • Resize column width for JTable without column headers?

    Hi,
    I find that for me to resize columns of a JTable by using
    mouse dragging, I MUST have column headers and then drag
    column headers to resize them. Is my understanding correct?
    Actually, I need to have a table without header columns.
    How can I use mouse to resize column width by dragging?
    The background for this request is that I am putting a
    complex table as another table's column header and I hope to
    be able to resizing the complex table by mouse dragging.
    Thanks very much,
    David

    Hi,
    I think you have mistake there. Try
    <style type="text/css">
    table.apexir_WORKSHEET_DATA td {
    white-space:nowrap !important;
    td[headers="DESCR"] {
    width:300px !important;
    max-width:300px !important;
    #apexir_DESCR {
    width:10px;
    max-width:300px !important;
    </style>And you can try add
    table.apexir_WORKSHEET_DATA {
    width: 100% !important;
    table-layout: fixed !important;
    }Regards,
    Jari
    My Blog: http://dbswh.webhop.net/htmldb/f?p=BLOG:HOME:0
    Twitter: http://www.twitter.com/jariolai

  • How to listen for resizing of JTable column

    Is there anyway to tell when the columns in a JTable are being resized by the user? I couldn't find any listeners or anything that will tell you when the user is dragging the column width with the mouse.
    Thanks.

    Use ColumnModelListener as shown below:-
              table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
                   public void columnAdded(TableColumnModelEvent e) {
                   public void columnMoved(TableColumnModelEvent e) {
                   public void columnRemoved(TableColumnModelEvent e) {
                   public void columnMarginChanged(ChangeEvent e) {
                   public void columnSelectionChanged(ListSelectionEvent e) {
              });

  • Giving names to the columns in a JTable

    Hi,
    I am using JTable(int numRows, int numColumns) constructor to create a JTable. After I built my application I came to knw that I cannot change the column names. The JTable in my GUI will keep on changing and the no. of rows,columns and even the column names may also change. I just wanted to know what constructor I should shift to.
    Thanks,
    Adhiraj

    I would use something like the following:
    DefaultTableModel model = new DefaultTableModel(columnNames, rowCount);
    JTable table = new JTable( model );
    The following code gives some examples on using the DefaultTableModel to add rows and columns:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              //  Create table
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              String[] columnNames = {"Number","Letter"};
              model = new DefaultTableModel(data, columnNames);
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Insert Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.insertRow( 0, createRow() );
                        table.changeSelection(0, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Empty Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.setRowCount( model.getRowCount() + 1 );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Add Column" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String header = "Col" + (table.getColumnCount() + 1);
                        model.addColumn( header );
                        table.requestFocusInWindow();
              button = new JButton( "Add Column & Data" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String header = "Col" + (table.getColumnCount() + 1);
                        int rows = table.getRowCount();
                        String[] values = new String[rows];
                        for (int j = 0; j < rows; j++)
                             values[j] = Integer.toString(j);
                        model.addColumn( header, values );
                        table.requestFocusInWindow();
              button = new JButton( "Add Column - No Reordering" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        //  Use this method when you don't want existing columns
                        //  to be rebuilt from the model.
                        //  (ie. moved columns will not be reordered)
                        table.setAutoCreateColumnsFromModel( false );
                        String header = "Col" + (table.getColumnCount() + 1);
                        model.addColumn( header );
                        //  AutoCreate is turned off so create table column here
                        TableColumn column = new TableColumn( table.getColumnCount() );
                        column.setHeaderValue( header );
                        table.addColumn( column );
                        // These won't work once setAutoCreate... has been set to false
                        buttonPanel.getComponent(3).setEnabled( false );
                        buttonPanel.getComponent(4).setEnabled( false );
                        table.requestFocusInWindow();
              button = new JButton( "Remove Last Column" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        int columns = model.getColumnCount();
                        if (columns > 0)
                             if (!table.getAutoCreateColumnsFromModel())
                                  int view =
                                       table.convertColumnIndexToView(columns - 1);
                                  TableColumn column =
                                       table.getColumnModel().getColumn(view);
                                  table.getColumnModel().removeColumn( column );
                             model.setColumnCount(columns - 1);
                        table.requestFocusInWindow();
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

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

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

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

  • Hide a column in a JTable

    Hi All, hope you can help,
    I want to hide the last column of my table, but still access its data. Inside the last column certain information is present, the cell tooltips.
    In my extended JTable class my method getToolTipText looks like this:
            // implement table cell tool tip.
            public String getToolTipText(MouseEvent e) {
                String tip             = null;
                Point  p               = e.getPoint();
                int    rowIndex        = rowAtPoint(p);
                int    colIndex        = columnAtPoint(p);
                int    realColumnIndex = convertColumnIndexToModel(colIndex);
                if(rowIndex>=0 && rowIndex<=lastRow) {
                    if(realColumnIndex==0) {
                        MiniModel mml = (MiniModel)getValueAt(rowIndex, 5); // exception here
                        tip = "<html>" + replaceCRLFtoBR(mml.getComment()) + "</html>"; // replaceCRLFtoBR = custom method to replace \n by <br>
                    } else {
                        tip = columnTips[realColumnIndex]; // constant
                return tip;
            }As you can see at column 5 an object MiniModel is present containing the tooltip for column 0.
    When I use the method removeColumn on column 5 on my extended JTable variable, I get an java.lang.ArrayIndexOutOfBoundsException at the marked position and in more detail on getValueAt.
    As I read everywhere the actual data is not removed (only from the view) I wonder what I'm doing wrong...
    Michiel

    Thanks for the advice, I will prepare better next time, here is my sscce :
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    public class TableHide extends JFrame {
        private static final String[] colNames    = {"Column 1", "Column 2", "Column 3"};
        private static final String[] colHeadTips = {"Header tip 1", "Header tip 2", "Header tip 3"};
        private ExtTableModel    myTableModel;
        private ExtTable         myTable;
        private JScrollPane      myScrollPane;
        private int              lastRow = 0;
        // for example
        private MiniModel mmlRow1 = new MiniModel(1, "cell comment");
        private MiniModel mmlRow2 = new MiniModel(2, "other cell comment");
        // constructor
        public TableHide() {
            this.setTitle("Table column hide test");
            this.setResizable(true);
            this.setLayout(new BorderLayout());
            // build table containing all extended Model's id and name
            myTableModel = new ExtTableModel(null, colNames);
            myTable      = new ExtTable(myTableModel);
            myTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            myTable.setPreferredScrollableViewportSize(new Dimension(500, 130));
            myTable.setFillsViewportHeight(true);
            myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            myTable.getTableHeader().setReorderingAllowed(false);
            myScrollPane = new JScrollPane(myTable);
            this.add(myScrollPane, BorderLayout.CENTER);
            // add some rows, in real application this is more complex
            myTableModel.insertRow(0, new Object[]{ "Basic string", new Boolean(false), mmlRow1 }); lastRow++;
            myTableModel.insertRow(0, new Object[]{ "Other string", new Boolean(true) , mmlRow2 }); lastRow++;
            myTable.setAutoCreateRowSorter(true);
            myTable.getRowSorter().toggleSortOrder(0);
            // this causes the exception
            myTable.removeColumn(myTable.getColumnModel().getColumn(2));
            this.setSize(new Dimension(500,200));
        // inner class to provide an own table model for the extended Models showed on screen. used for booleans
        class ExtTableModel extends DefaultTableModel {
            public ExtTableModel(Object[][] tableData, String[] columnNames) {
                super(tableData, columnNames);
            public boolean isCellEditable(int row, int col) {
                return false;
            public Class getColumnClass(int column){
                Object value=this.getValueAt(0,column);
                return (value==null?Object.class:value.getClass());
        // inner class to privide column header tooltips and cell tooltips
        class ExtTable extends JTable {
            public ExtTable(ExtTableModel extModel) {
                super(extModel);
            // implement table cell tool tip.
            public String getToolTipText(MouseEvent e) {
                String tip             = null;
                Point  p               = e.getPoint();
                int    rowIndex        = rowAtPoint(p);
                int    colIndex        = columnAtPoint(p);
                int    realColumnIndex = convertColumnIndexToModel(colIndex);
                if(rowIndex>=0 && rowIndex<=lastRow) {
                    if(realColumnIndex==0) {
                        MiniModel mml = (MiniModel)getValueAt(rowIndex, 2);
                        tip = mml.getMml_comment();
                    } else {
                        tip = "Some other tooltip function";
                return tip;
            // implement table header tool tip.
            protected JTableHeader createDefaultTableHeader() {
                return new JTableHeader(columnModel) {
                    public String getToolTipText(MouseEvent e) {
                        Point  p         = e.getPoint();
                        int    index     = columnModel.getColumnIndexAtX(p.x);
                        int    realIndex = columnModel.getColumn(index).getModelIndex();
                        return colHeadTips[realIndex];
        // simplified class for usage inside a cell
        public class MiniModel {
            private int        mml_id;
            private String     mml_comment;
            public MiniModel(int mml_id, String mml_comment) {
                this.mml_id      = mml_id;
                this.mml_comment = mml_comment;
            public String getMml_comment() {
                return mml_comment;
            public String toString() {
                return Integer.toString(mml_id); // called when object is displayed
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    new TableHide().setVisible(true);
    }When you show the last column the program works fine. Goal is to have the last column available since it contains extra information about the row, but not to show it.

  • Setting the Size of a Column in a JTable

    Hi there,
    does anybody knows a way how to set the size of a specified column in a JTable without changinge the size of the other columns?
    thx anyway
    Errraddicator

    You've got to change the JTable's column resizing policy to prevent the other columns resizing:
    JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)Otherwise all the columns will be adjusted to fit into the width of the table - changing one column would have to result in at least one other column changing!
    Hope this helps.

  • JTable when scroll horiz column cells dont align with header

    Hi,
    I'm having a problem with my JTable. Everything was working correctly until i introduced checkboxes into a column on teh table. I have a table which has a horizontal scrollbar to scroll across all the columns. when i set one column to boolean values (instead of the strings 'true' and 'false' which were there before) when i scroll across the table the headers of each column no longer align with the data.
    Some columns resize when i scroll and the headings always stay the same width.
    I'm getting an error:
    java.lang.ClassCastException
         at javax.swing.JTable$BooleanRenderer.getTableCellRendererComponent(Unknown Source)The database stores int 0/1 for the boolean value so in the getValueAt method of my table model i return a boolean for this column.
    Any help would be greatly appreciated!
    Thanks,
    Saz

    Thanks for replying. Neither solution worked.
    The problem is definately with the boolean value because i'm getting a classcast exception: at javax.swing.JTable$BooleanRenderer.getTableCellRendererComponent(Unknown Source)
    I've a feeling this could be caused by some values being empty strings in the same column with booleans?
    Does anyone know what causes this error?
    Thanks,
    Sarah

  • Horizontal scrolling in a JTable with fixed-size columns

    Hello,
    I have come to a roadblock concerning the following issue. Perhaps someone can share their ideas...
    I have a JTable with three fixed-size columns. I implemented a JScrollPane with vertical and horizontal scrolling. However, the text inserted into the last column is too long to fit in the specified column width. I would like to be able to scroll the table so that I can view all of the text in the last column. Right now, the text cuts off and ends with three dots (...). Is there a way in which a horizontal scroll bar can be implemented to view all the text in the last column?
    Here is a portion of my code:
    num_of_rows_Table2 = (int) Math.pow(3, num_of_vars);
    String[] colunmNames_Table2 = {"Decimal Identifier", "Ternary Identifier", "Cancellation of nonimplicants"};
    dataModel2 = new DefaultTableModel(colunmNames_Table2, num_of_rows_Table2);
    SpaceOfTermsTable = new JTable(dataModel2);
    for (int z = 0; z < num_of_rows_Table2; z++)
    SpaceOfTermsTable.setRowHeight(z, row_height);
    SpaceOfTermsTable.setBounds(new Rectangle(x1_Table2, y1_Table2, width_of_pane2, height_pane2));
    SpaceOfTermsTable.getTableHeader().setReorderingAllowed(false);
    for (int i = 0; i < 2; i++)
    TableColumn col = SpaceOfTermsTable.getColumnModel().getColumn(i);
    col.setMinWidth(colwidth_Table2);
    col.setMaxWidth(colwidth_Table2);
    col.setPreferredWidth(colwidth_Table2);
    TableColumn lastcol = SpaceOfTermsTable.getColumnModel().getColumn(2); lastcol.setMinWidth(lastcol_Table2);
    lastcol.setMaxWidth(lastcol_Table2);
    lastcol.setPreferredWidth(lastcol_Table2);
    SpaceOfTermsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    scrollPanel2 = new JScrollPane(SpaceOfTermsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPanel2.setAutoscrolls(true);
    scrollPanel2.setBounds(new Rectangle(x1_Table2, y1_Table2, width_of_pane2, height_pane2));
    Thanks in advance for all of the help!

    Hi, I hava a similar problem than yours - can you tell me how you sorted out yer's?

  • Set column width in JTable

    I have two columns in a JTable and I am trying to set the column width for the first.
    I am trying to this by
    getDataTbl().getColumnModel().getColumn(0).setHeaderValue("Index");
    getDataTbl().getColumnModel().getColumn(1).setHeaderValue(" Data ");
    int width = ((String)getDataTbl().getColumnModel().getColumn(0).getHeaderValue()).length();
    getDataTbl().getColumnModel().getColumn(0).setPreferredWidth(width);
    but it doesn't reset the width. I want the first column width to be smaller than the second which should be much larger width.
    Any suggessions to this?
    Thanks.

    Hi there
    Use this JTable method
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);This should solve your resize problem
    ICE

  • Retarded Column Heading of JTable

    I have a JTable where I allow automatic resizing of the columns because the user may choose between things of varying lengths to add to the table from a list. I have disabled reordering and resizing in the Table Header. However, the first column heading, "Response Variable", always shows up as "Response.." until you select at least one item from the list. It is driving me crazy. Why won't the entire column name show up all the time, regardless of how many rows the table has?

    try setting the TableColumn minWidth to the minimum size of the column heading. use the method setMinWidth(int minWidth) located in the TableColumn class. This should fix the problem. Let me know

  • Resizing the JTable Cell horizontal width

    Sir/Madam,
    How can i resize the JTable cell's horizontal width. I know the JTable's column width can be resized. I dont want to resize the entire JTable column. But i need to resize individual JTable cell's horizontal width. Thanks in advance.

    I think that's not possible. What kind of results are you expecting ? If the cells of a column are different widths, what are you going to do with the extra space of the narrower cells ?
    What are you displaying in the cells ? Maybe you can narrow the contents of the cells, and not the cells.

Maybe you are looking for

  • Documents needed for Report

    Hi Experts,                 To build a report  what are the documents that you are needed or prepared from Functional spec to UAT (User Acceptance Test) like busines Blue print..we had 4 only .Can u share your experience with me.. Thanks & Regards, S

  • Analyze the Field Mapping in a Query Transform

    My client is running Data Services 3.1 SP1 on WIndows Server 2003.  They have the following scenario: A data flow has muliple flat file source transforms of different file formats, each of which is connected to a query transform.  On the output side

  • How to read Business Rule

    Hello Experts, Could you please help me in reading the Business rule: Here, how the values are getting calculated and getting flowed in FXImpact_AVG_P1 flow member? Please help. Regards, Apoorva

  • Making Photo Slideshows along with movies

    Does FCE HD or FCP HD make good quality slideshows. iMovie seems to lose a lot of quality wihen making slideshows with photos. I am looking to make a DVD with movies as well as photos, and I am wondering what would app would give me the best quality.

  • Address data pop up in Email Header

    Hi Experts, While creating a new Email in inteaction center, when we give some name in TO field and click on CHECK button then a pop up opens with all possible names. When we click on any one of these names, again a new pop up for ADDRESS DATA comes