Updates to JTables and resizing of columns

I'm building an application that has many tables that all use table models that I have created. All of the table models extend DefaultTableModel. Before entering any data in the tables i set the size of the columns. Below is an example of how I do this...
      //tcm = table column model
      tcm.getColumn(0).setPreferredWidth(100);
      tcm.getColumn(1).setPreferredWidth(100);
      tcm.getColumn(2).setPreferredWidth(100);
      tcm.getColumn(3).setPreferredWidth(100);
      tcm.getColumn(4).setPreferredWidth(172);
      tcm.getColumn(5).setPreferredWidth(172);
      My problem is everytime I update the table with new data the columns keep adjusting themselves to the width of the largest piece of data in the particular column. In order to keep the size of the columns I want I've been resizing the columns with the above code everytime I update the table. Can someone tell me how to set the column sizes once and have them remain that way?

I'm sorry to hear that you're having problems customising your Spotify for Mac application. I'm sure Spotify do value your custom and will take your suggestion to return this feature. For now, I think posting your idea in the Ideas forum would be best to get your idea out there and upvoted by fellow community members wishing for the return of this feature. You can submit your idea at: https://community.spotify.com/t5/forums/postpage/board-id/ideas_submissions Take care and let me know how it goes!

Similar Messages

  • Updating a JTable by hiding/displaying columns

    I have a customizable JTable where I display/hide columns according to a users' selection criteria. My code works fine for hiding/displaying columns if the Jtable is opened for the fist time, but doesnot work if I want to hide columns in already displayed table.How do I do it?? Any clue?? I tried
    myTabModel.fireTableDataChanged();
    but this only works for updating the table data...it does not hide columns for me... when I hide column I just remove desired column like this:
    myTable.removeColumn(myTable.getColumn("Column 3"));

    Here is the sample code I tried. It worked without any invalidate or repaint or updateUI(). generated using NetBeans
    check for <==== for the line of code doing this
    * TableTest.java
    * Created on October 9, 2002, 1:42 PM
    * @author  Anki Reddy Nelaturu
    public class TableTest extends javax.swing.JFrame {
        /** Creates new form TableTest */
        public TableTest() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            menuBar = new javax.swing.JMenuBar();
            fileMenu = new javax.swing.JMenu();
            openMenuItem = new javax.swing.JMenuItem();
            saveMenuItem = new javax.swing.JMenuItem();
            saveAsMenuItem = new javax.swing.JMenuItem();
            exitMenuItem = new javax.swing.JMenuItem();
            editMenu = new javax.swing.JMenu();
            cutMenuItem = new javax.swing.JMenuItem();
            copyMenuItem = new javax.swing.JMenuItem();
            pasteMenuItem = new javax.swing.JMenuItem();
            deleteMenuItem = new javax.swing.JMenuItem();
            helpMenu = new javax.swing.JMenu();
            contentsMenuItem = new javax.swing.JMenuItem();
            aboutMenuItem = new javax.swing.JMenuItem();
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(80, 30, 230, 120);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton1.setBounds(170, 180, 81, 26);
            jTextField1.setText("jTextField1");
            getContentPane().add(jTextField1);
            jTextField1.setBounds(60, 190, 63, 20);
            fileMenu.setText("File");
            openMenuItem.setText("Open");
            fileMenu.add(openMenuItem);
            saveMenuItem.setText("Save");
            fileMenu.add(saveMenuItem);
            saveAsMenuItem.setText("Save As ...");
            fileMenu.add(saveAsMenuItem);
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    exitMenuItemActionPerformed(evt);
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            editMenu.setText("Edit");
            cutMenuItem.setText("Cut");
            editMenu.add(cutMenuItem);
            copyMenuItem.setText("Copy");
            editMenu.add(copyMenuItem);
            pasteMenuItem.setText("Paste");
            editMenu.add(pasteMenuItem);
            deleteMenuItem.setText("Delete");
            editMenu.add(deleteMenuItem);
            menuBar.add(editMenu);
            helpMenu.setText("Help");
            contentsMenuItem.setText("Contents");
            helpMenu.add(contentsMenuItem);
            aboutMenuItem.setText("About");
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            pack();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jTable1.removeColumn(jTable1.getColumnModel().getColumn(Integer.parseInt(jTextField1.getText())));        // <========
        private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
            System.exit(0);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new TableTest().show();
        // Variables declaration - do not modify
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JButton jButton1;
        private javax.swing.JMenuItem saveAsMenuItem;
        private javax.swing.JMenuItem saveMenuItem;
        private javax.swing.JMenuItem copyMenuItem;
        private javax.swing.JMenuItem pasteMenuItem;
        private javax.swing.JMenuItem cutMenuItem;
        private javax.swing.JMenuItem openMenuItem;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenu editMenu;
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JMenuItem contentsMenuItem;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JMenuItem deleteMenuItem;
        private javax.swing.JTable jTable1;
        // End of variables declaration
    }

  • Form Resize Affect Column width?

    Hi Folks,
    I have a very strange problem. I try to add a new matrix to Production Order form. The matrix will have 2 columns which are:
    1. No - Non Editable (for numbering)
    2. Description (information).
    My code is like the following:
            oItem = oForm.Items.Add("mxRoute", SAPbouiCOM.BoFormItemTypes.it_MATRIX)
            oItem.Left = 12
            oItem.Width = 532
            oItem.Top = 136
            oItem.Height = 183
            oItem.FromPane = 3
            oItem.ToPane = 3
            oMatrix = oItem.Specific
            oColumns = oMatrix.Columns
            '// Adding Culomn items to the matrix
            oColumn = oColumns.Add("#", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "#"
            oColumn.Width = 20
            oColumn.Editable = False
            oColumn = oColumns.Add("Col1", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "Operations"
            oColumn.Width = 500
            oColumn.Editable = True
    The problem occured when i try to maximize my form. The first Col (#) will resize to a very big size!!! When i try to resize it to smaller form, it still very big column. Anybody has clue what should i do to the form since it is not possible to restrict the form type to Fixed???
    Your help will be very appreciated..
    Rgds,
    Harianto Ng

    Hi Harianto Ng,
    Catch the after resize event and resize both columns by hand.
    1. calculate width of columns 1 + 2
    2 resize the first to 20
    3 resize the second to totalwidth-20
    Regards
    Ad

  • Can i set only 1 column in a jtable to resize?

    Hi,
    I want to set only the columns with "Strings" as content to be resizable inside my jtable. and leave those which are ints, as a fixed size, but I haven't been able to find a way of setting the resizing options for a specific column...
    any ideas?

    You would need to check the column number and the data type in the column being resized and force it back to a set value if it was not a column with a string in it. Remember the user can swap the columns.
    rykk

  • 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.

  • API to Update the DISCOUNT_DATE and DISCOUNT_AMOUNT_AVAILABLE column

    Hi,
    I am doing one inbound interface where I needs to Update the DISCOUNT_DATE and DISCOUNT_AMOUNT_AVAILABLE column in AP_PAYMENT_SCHEDULES_ALL table for each invoice. So that the value will display in Schedule Payments tab of the invoice workbench screen.
    Requesting to suggest any public/private API for this process.
    Any help will be needful for me
    Thanks and Regards

    Hi,
    I have a requirement where in I have to develop a report to display bank balance chart with the following details in the output.They are :
    1. Posting Date
    2. Bill Discount (BD)
    3. Letter of Credit(LC)
    4. Cheque Amount may be cheque issued.
    5. Deposits.
    Above are the information which i have to display based on Posting Date range , Company Code and Bank Key present in the selection-screen.
    Below are my few observations:
    1. To retrieve the Bill Discount, I am first fetching the data from BKPF table by checking the document types 'DZ' ,'KZ', Company code and Posting Date Range. Then using document number,company code present in these entries along with Posting key = 39 and special GL indicator = 'W' retrieving the data like DMBTR,WRBTR from BSEG.
    2. Similarly for Letter of Credit amount retrieving the data in the same way as mentioned above except special GL indicator will be 'Y'.
    Now please correct me if my approach is wrong. Request you all to throw some light as I am Technical Consultant and humbly looking forward to all your help.
    Also, request to let me know the logic or process how one can calculate fourth point as well as Fifth point as mentioned above.
    Edited by Raghavendra Kulkarni.
    I am just looking for flow of data/process flow/standard transactions through which I can see these above mentioned things which can help me in building the logic. At least a general approach to this will be appreciated highly.
    Regards,
    Raghavendra Kulkarni.

  • JTable can't display column names and scroll bar in JDialog !!

    Dear All ,
    My flow of program is JFrame call JDialog.
    dialogCopy = new dialogCopyBay(frame, "Bay Name Define", true, Integer.parseInt(txtSourceBay.getText()) ,proVsl ,300 ,300);
    dialogCopy.setBounds(0, 0, 300, 300);
    dialogCopy.setVisible(true);        Then,I set the datasource of JTable is from a TableModel.
    It's wild that JTable can diplay the data without column names and scroll bar.
    I have no idea what's going wrong.Cause I follow the Sun Tutorial to code.
    Here with the code of my JDialog.
    Thanks & Best Regards
    package com.whl.panel;
    import com.whl.vslEditor.vslDefine;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class dialogCopyBay extends JDialog {
        vslDefine glbVslDefine;
        int lvCnt = -1;
        JTable tableCopyBay;
        int bgnX = 0;
        int bgnY = 30;
        int tableWidth = 100;
        int tableHeight = 100;
        public dialogCopyBay(Frame frame, String title, boolean modal, int sourceBay,
                vslDefine pVslDefine, int ttlWidth, int ttlHeight) {
            super(frame, title, true);
            Container contentPane = getContentPane();
            System.out.println("dialogCopyBay Constructor");
            glbVslDefine = null;
            glbVslDefine = pVslDefine;
            copyBayModel copyBay = new copyBayModel((glbVslDefine.getVslBayStructure().length - 1),sourceBay);
            tableCopyBay = new JTable(copyBay);
            tableCopyBay.setPreferredScrollableViewportSize(new Dimension(tableWidth, tableHeight));
            JScrollPane scrollPane = new JScrollPane(tableCopyBay);
            scrollPane.setViewportView(tableCopyBay) ;
            tableCopyBay.setFillsViewportHeight(true);
            tableCopyBay.setBounds(bgnX, bgnY, tableWidth, tableHeight);
            tableCopyBay.setBounds(10, 10, 100, 200) ;
            contentPane.setLayout(null);
            contentPane.add(scrollPane);
            contentPane.add(tableCopyBay);
        class copyBayModel extends AbstractTableModel {
            String[] columnNames;
            Object[][] dataTarget;
            public copyBayModel(int rowNum ,int pSourceBay) {
                columnNames = new String[]{"Choose", "Bay Name"};
                dataTarget = new Object[rowNum][2];
                for (int i = 0; i <= glbVslDefine.getVslBayStructure().length - 1; i++) {
                    if (pSourceBay != glbVslDefine.getVslBayStructure().getBayName() &&
    glbVslDefine.getVslBayStructure()[i].getIsSuperStructure() == 'N') {
    lvCnt = lvCnt + 1;
    dataTarget[lvCnt][0] = false;
    dataTarget[lvCnt][1] = glbVslDefine.getVslBayStructure()[i].getBayName();
    System.out.println("lvCnt=" + lvCnt + ",BayName=" + glbVslDefine.getVslBayStructure()[i].getBayName());
    public int getRowCount() {
    return dataTarget.length;
    public int getColumnCount() {
    return columnNames.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int rowIndex, int columnIndex) {
    return dataTarget[rowIndex][columnIndex];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
    if (col == 1) {
    // Bay Name Not Allow To modify
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    dataTarget[row][col] = value;
    fireTableCellUpdated(row, col);

    Dear DB ,
    I am not sure what you mean.
    Currently,I don't undestand which code is error.
    And I also saw some example is add JTable and JScrollPane in JDialog.
    Like Below examle in Sun tutorial
    public class ListDialog extends JDialog implements MouseListener, MouseMotionListener{
        private static ListDialog dialog;
        private static String value = "";
        private JList list;
        public static void initialize(Component comp,
                String[] possibleValues,
                String title,
                String labelText) {
            Frame frame = JOptionPane.getFrameForComponent(comp);
            dialog = new ListDialog(frame, possibleValues,
                    title, labelText);
         * Show the initialized dialog. The first argument should
         * be null if you want the dialog to come up in the center
         * of the screen. Otherwise, the argument should be the
         * component on top of which the dialog should appear.
        public static String showDialog(Component comp, String initialValue) {
            if (dialog != null) {
                dialog.setValue(initialValue);
                dialog.setLocationRelativeTo(comp);
                dialog.setVisible(true);
            } else {
                System.err.println("ListDialog requires you to call initialize " + "before calling showDialog.");
            return value;
        private void setValue(String newValue) {
            value = newValue;
            list.setSelectedValue(value, true);
        private ListDialog(Frame frame, Object[] data, String title,
                String labelText) {
            super(frame, title, true);
    //buttons
            JButton cancelButton = new JButton("Cancel");
            final JButton setButton = new JButton("Set");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.dialog.setVisible(false);
            setButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.value = (String) (list.getSelectedValue());
                    ListDialog.dialog.setVisible(false);
            getRootPane().setDefaultButton(setButton);
    //main part of the dialog
            list = new JList(data);
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            list.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        setButton.doClick();
            JScrollPane listScroller = new JScrollPane(list);
            listScroller.setPreferredSize(new Dimension(250, 80));
    //XXX: Must do the following, too, or else the scroller thinks
    //XXX: it's taller than it is:
            listScroller.setMinimumSize(new Dimension(250, 80));
            listScroller.setAlignmentX(LEFT_ALIGNMENT);
    //Create a container so that we can add a title around
    //the scroll pane. Can't add a title directly to the
    //scroll pane because its background would be white.
    //Lay out the label and scroll pane from top to button.
            JPanel listPane = new JPanel();
            listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
            JLabel label = new JLabel(labelText);
            label.setLabelFor(list);
            listPane.add(label);
            listPane.add(Box.createRigidArea(new Dimension(0, 5)));
            listPane.add(listScroller);
            listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    //Lay out the buttons from left to right.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(cancelButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
            buttonPane.add(setButton);
    //Put everything together, using the content pane's BorderLayout.
            Container contentPane = getContentPane();
            contentPane.add(listPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
            pack();
        public void mouseClicked(MouseEvent e) {
            System.out.println("Mouse Click");
        public void mousePressed(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseReleased(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseEntered(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseExited(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseDragged(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseMoved(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
         * This is here so that you can view ListDialog even if you
         * haven't written the code to include it in a program.
    }

  • Disable sorting and resizing columns on table view

    Is there a way to disable sorting and resizing columns on table view?
    Thanks

    Use
    setSortable(false)
    setResizable(false)
    on each TableColumn

  • 1. Resizing of column width. 2. Drag and drop of columns for resequencing

    QUERY : Has anyone some experience in implementation/development of following functionality in a JSP/Tomcat server based application:
    1. Resizing of column width for a result which has multiple columns. .2. Drag and drop of these columns or any other mechanism for re-sequencing the columns?
    I would like to know will JSF would be helpful in it.

    Amit,
    The column resizing and 'drag and drop ' are client side issues. They requires DHTML and Javascript.
    AJAX is what is required. (wiki AJAX for more info)
    I am working on an AJAX grid and combobox component for JSF that will do this and many more functions.
    Let me know if you want more information.
    [email protected]

  • The Firefox plugin page said I needed to install a new plugin for Shockwave Flash, but after doing the installation I checked back to see if the installation took place and the "action" column still says "update now" and potentially vulnerable."

    After downloading the new version of Shockwave
    flash the message in the box said the download was completed; however, the information on the Firefox plugin page keeps saying "potentially vulnerable" and "update now" as though no download took place. I repeated the download 2 more times and got the same results.

    Your plugins list shows outdated plugin(s) with known security and stability risks.
    # Shockwave Flash 10.0 r32
    # Java Plug-in 1.5.0_06 for Netscape Navigator (DLL Helper)
    Update the [[Java]] and [[Flash]] plugin to the latest version.
    See
    http://java.sun.com/javase/downloads/index.jsp#jdk (you need JRE)
    http://www.adobe.com/software/flash/about/
    Start Firefox in [[Safe Mode]] to check if one of your add-ons is causing your problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    See [[Troubleshooting extensions and themes]] and [[Troubleshooting plugins]]

  • JTable and integers

    I have a tablemodel that holds the headers and the amount of rows and then inputted into a Jtable.what im trying to do is gather information in certain columns(ie integers) and add them up with the end result displaying the total at the end of the column.i have tried calling the column but i havent had luck so far.Ive also tried creating a 2d array instead of the tablemodel but no luck

    i cannot input anything into my JTable when ur code is put into it. I think its because the tablemodel is (headers,35) so there are no values to start with in each row.
    Ive tried alternating ur code to make it add floats in a column but still no luck.
    public void BS()
           String[] headers = new String[]{"Assets", "", "Liabilities", "", "Owner's Equity", ""};
            DefaultTableModel model = new DefaultTableModel(headers,35);
            model.addTableModelListener(this);
            bstable = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                   //  The Cost is not editable
                   public boolean isCellEditable(int row, int column)
                        int modelColumn = convertColumnIndexToModel( column );
                        return (modelColumn == 3) ? false : true;
            bstable.getTableHeader().setReorderingAllowed(false);
            bsscrollpane = new JScrollPane(bstable);
            bsscrollpane.setViewportView(bstable);
        public void tableChanged(TableModelEvent e)
              System.out.println(e.getSource());
              if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1)
                        TableModel model = bstable.getModel();
                                    Float     assets = ((Float)model.getValueAt(row, 1)).floatValue();
                        Float value = new Float(assets);
                        model.setValueAt(value, row, 1);
         }I dont know if the calculate column will work. Do i have to loop it so it keeps on adding the rows in the 1st column.?

  • How  to resize the column header according to row data

    Hi,
    How can i resize the column header according to row date .. means if data is small header should be small and vice versa ,...
    Any help is appreciated .. Snippet will be more helpful .
    Thanks,
    Shekhar

    Oxley (binkley) blogged about this: http://binkley.blogspot.com/2006/01/getting-jtable-columns-widths-to-fit.html
    Christian Ullenboom | tutego

  • Strange JTable/JViewport resizing

    Folk'ses,
    i have a strange problem with a JTable and its viewport when i change the data and column model.
    * autoResizeMode is set to AUTO_RESIZE_ALL_COLUMNS.
    * all my columns have a minimum size
    * when i change my data and column model i do not get a scrollbar in the surrounding scrollpane
    in the 1.5 JTable.doLayout() doc i found the following note:
    Note: When a JTable makes adjustments to the widths of the columns it respects their minimum and maximum values absolutely. It is therefore possible that, even after this method is called, the total width of the columns is still not equal to the width of the table. When this happens the JTable does not put itself in AUTO_RESIZE_OFF mode to bring up a scroll bar, or break other commitments of its current auto-resize mode -- instead it allows its bounds to be set larger (or smaller) than the total of the column minimum or maximum, meaning, either that there will not be enough room to display all of the columns, or that the columns will not fill the JTable's bounds. These respectively, result in the clipping of some columns or an area being painted in the JTable's background color during painting.
    has anybody an idea how to get around this problem?
    is it so uncommon?
    why did they implement it like that?
    frustrated,
    thomas

    frustrated,Yes, a verbal description of the problem doesn't always help me. I have no idea what you code is like, what layout manger you are using etc.....
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Updating a JTable when using an AbstractTableModel

    Hi,
    I have tried to create a JTable with an AbstractTableModel but I am obviously missing something in all the tutorials and examples as I cannot get the table to update when using my model.
    My application reads data in from a CSV file that is selectable at run time, but I have written a small app that demonstrates the problem I am having.
    If you uncomment the DefaultTableModel lines of code all is OK, but I need to use my Abstract Class as I intend to colour certain rows and add a Boolean column, that I would like to display as a CheckBox and not just the String representation.
    Any help would be great as I am tearing my hair out here!!
    My Test Class
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class TestTable extends JFrame implements ActionListener
    private JPanel jpTestTable = new JPanel();          
    private Vector vColumnNames = new Vector();
    private Vector vCellValues = new Vector();
    private DefaultTableModel dtmTestTable;
    private CustomTableModel ctmTestTable;
    private JTable jtTestTable;
    private JScrollPane jspTestTable;
    private JButton jbGo = new JButton();
         public TestTable()
         dtmTestTable = new DefaultTableModel();
         ctmTestTable = new CustomTableModel();
         //jtTestTable = new JTable( dtmTestTable );  //using this instead of my CustomModel works fine
         jtTestTable = new JTable( ctmTestTable );
         jtTestTable.setAutoCreateRowSorter(true);
         jtTestTable.setFillsViewportHeight( true );
         jspTestTable = new JScrollPane( jtTestTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         jspTestTable.setBounds( 10, 10, 350, 400 );
         jspTestTable.setBorder( BorderFactory.createLoweredBevelBorder() );
         jbGo.setText( "Go" );
         jbGo.setBorder( BorderFactory.createRaisedBevelBorder() );
         jbGo.setBounds( 125, 430, 100, 25 );
         jbGo.addActionListener(this);
         jpTestTable.setLayout( null );
         jpTestTable.setBounds( 0, 0, 375, 500 );     
         jpTestTable.add( jspTestTable );
         jpTestTable.add( jbGo );
         this.setTitle( "Test Table" );
         this.getContentPane().setLayout( null );
         this.setBounds( 200, 50, 375, 500 );
         this.getContentPane().add( jpTestTable );
         this.setResizable( false );
         public void actionPerformed( ActionEvent e )
         updateTable();
         public void updateTable()
         vColumnNames.add( "Please" );
         vColumnNames.add( "work" );
         vColumnNames.add( "you" );
         vColumnNames.add( "git!" );
         vColumnNames.trimToSize();
         Vector vRow = new Vector();
              for( int i = 0; i < 10; i++ )
                   for( int x = 0; x < vColumnNames.size(); x++ )
                        vRow.add( "" + i + "" + x );
              vCellValues.add( vRow );
         //dtmTestTable.setDataVector( vCellValues, vColumnNames );  //using this instead of my CustomModel works fine
         ctmTestTable.setDataVector( vCellValues, vColumnNames );
         public void processWindowEvent(WindowEvent e)
         super.processWindowEvent(e);
              if(e.getID() == WindowEvent.WINDOW_CLOSING)
              exit();
         public void exit()
         System.exit( 0 );     
         public static void main(String args[])
         TestTable tt = new TestTable();
         tt.setVisible( true );
    }And my CustomTableModel Class
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.util.*;
    public class CustomTableModel extends AbstractTableModel
    protected Vector columnIdentifiers  = new Vector();
    protected Vector dataVector = new Vector();
         public CustomTableModel()
         public CustomTableModel( Vector data, Vector columnNames )
         setDataVector( data, columnNames );
         public int getColumnCount()
         return columnIdentifiers.size();
         public int getRowCount()
         return dataVector.size();
         public String getColumnName( int col )
         return "" + columnIdentifiers.get( col );
         public Object getValueAt( int row, int col )
         Vector vRow = new Vector();
         vRow = (Vector) dataVector.get( row );
         return (Object) vRow.get( col );
         public Class getColumnClass(int c)
         return getValueAt(0, c).getClass();
         public boolean isCellEditable(int row, int col)
              if (col < 2)
                   return false;
              else
                   return true;
         public void setValueAt( Object value, int row, int col )
         Vector vTemp = (Vector) dataVector.get( row );
         Vector<Object> vRow = new Vector<Object>();
              for( int i = 0; i < vTemp.size(); i++ )
                   vRow.add( (Object) vTemp.get( i ) );
         vRow.remove( col );
         vRow.add( col, value );
         vRow.trimToSize();     
         dataVector.remove( row );
         dataVector.add( row, vRow );
         dataVector.trimToSize();
         fireTableCellUpdated(row, col);
         public void setDataVector( Vector data, Vector columnNames )
         columnIdentifiers  = (Vector) columnNames.clone();
         dataVector = (Vector) data.clone();
         fireTableDataChanged();
    }I have just tried adding the following code after reading another example, but same result - arrrrrrrgggggggghhhhhhhhh!!!!
    ctmTestTable = (CustomTableModel) jtTestTable.getModel();
    ctmTestTable.fireTableDataChanged();Edited by: Mr_Bump180 on Jul 28, 2008 2:51 PM

    Hi camickr,
    Well that is good news as my Abstact class is about as much good as an ashtray on a motorbike. I think I must have misread or misunderstood the Table Tutorials as I thought I had to use an Abstrat class to get colurs based on conditions and to get Check Boxes to represent Boolean variables.
    I am clearly struggling with this concept - which I have never used before - do you know of any tutorials, that explain how to update a JTable with file data at runtime, as all the ones I have looked at set it as part of the java code - which is no good to me.
    Also am I overriding the DefaultTableModel Class correctly - I have written a seperate Model class but wounder if I need to include it in with my JTable class. I was trying to make it generic so I didn't have to write one for each JTable - but as I can't get it to work I should perhaps try to walk before I run.
    I'm not asking for the code, but just a guide to how close I am to where I want to be, and some links to tutorials that are closer to what I want to achieve. I will reread the Java Table Tutorial tonight - and you never know the penny may drop all on it's own this time!!!
    Thanks

  • How to Update the JTable Content

    Hi Friends
    In my Program i have a Form having a JTable with shows some content on it. Now when the User Click on the Row it will ask where he wants to Edit that rows content. If the User gives Yes. then the Another JDialog opens with the Selected rows Data.
    Now when the User makes changes in the Data and Clicks on the Edit Button. It Should Show the Entered Data on the JTable immediatly.
    I am Posting my working Code. It works fine. But only the Updating the Newly entered Data to the JTable is not done.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class EditTable extends JDialog implements ActionListener,MouseListener
         private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
         private ButtonGroup bg;
         private JPanel exportpanel;
         private JButton btnExpots;
         JTable table;
         JScrollPane scroll;
         public EditTable()throws Exception
              setSize(550,450);
              setTitle("Export Results");
              this.setLocation(100,100);
              String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
              String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0203","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0204","PRIAM","SELVI","1354"},
                               {"B0205","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0207","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0208","PRIAM","SELVI","1354"}};
              btnExpots= new JButton("Export");
              btnExpots.addActionListener(this);
              btnExpots.setBounds(140,200,60,25);
              table = new JTable();
              table.addMouseListener(this);
              scroll=new JScrollPane(table);
              ((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
              System.out.println(table.getModel());
              exportpanel= new JPanel();
              exportpanel.add(btnExpots,BorderLayout.SOUTH);
              exportpanel.add(scroll);
              getContentPane().add(exportpanel);
              setVisible(true);
          public void actionPerformed(ActionEvent ae)
         public static void main(String arg[]) throws Exception
              EditTable ex= new EditTable();
           public void mouseClicked(MouseEvent me)
              Object obj=me.getSource();
              if(obj==table)
                        JTable source=(JTable)me.getSource();
                        int row = source.rowAtPoint(me.getPoint());
                        int column = source.columnAtPoint(me.getPoint());
                        System.out.println("Working Point"+row+"and"+column);
                        Object value1 = source.getValueAt(row,0);     
                        Object value2 = source.getValueAt(row,1);
                        Object value3 = source.getValueAt(row,2);
                        Object value4 = source.getValueAt(row,3);
                        String bkId=value1.toString();
                        String bkNm=value2.toString();
                        String bkAuthr=value3.toString();
                        String bkAuthrCd=value4.toString();
                        int opt = JOptionPane.showConfirmDialog(this,"Do you Really Want to Edit this Book?","Edit Books",JOptionPane.YES_NO_OPTION);
                        if(opt==JOptionPane.YES_OPTION)
                             try
                                  editForm  editfrm= new editForm ();
                                  editfrm.setVisible(true);
                                  editfrm.setVisible(true);
                                  editfrm.txtbookID.setText(""+bkId);
                                  editfrm.txtbookName.setText(""+bkNm);
                                  editfrm.txtbookAuthorName.setText(""+bkAuthr);
                                  editfrm.txtPrice.setText(""+bkAuthrCd);
                             catch(Exception ex)
                                  ex.printStackTrace();
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
    class editForm extends JDialog implements ActionListener
         JLabel lblbookID,lblbookName,lblbookAuthorName,lblPrice;
         JTextField txtbookID,txtbookName,txtbookAuthorName,txtPrice;
         JButton btnEdit,btnClose;
         JPanel editPanel;
              public editForm()
                   setSize (350,400);
                   this.setTitle("Edit Books");
                   this.setLocation(100,135);
                   lblbookID= new JLabel("Book ID:");
                   lblbookID.setBounds (15, 15, 100, 20);
                   lblbookName= new JLabel("Book Name:");
                   lblbookName.setBounds (15, 45, 100, 20);
                   lblbookAuthorName= new JLabel("Author Name:");
                   lblbookAuthorName.setBounds (15, 75, 100, 20);
                   lblPrice= new JLabel("Price:");
                   lblPrice.setBounds (15, 105, 100, 20);
                   Font fnt = new Font("serif",Font.BOLD,18);
                   txtbookID= new JTextField();
                   txtbookID.setFont(fnt);
                   txtbookID.setEditable(false);
                   txtbookID.setBounds (120, 15, 175, 20);
                   txtbookName= new JTextField();
                   txtbookName.setFont(fnt);
                   txtbookName.setBounds (120, 45, 175, 20);
                   txtbookAuthorName= new JTextField();
                   txtbookAuthorName.setFont(fnt);
                   txtbookAuthorName.setBounds (120, 75, 175, 20);
                   txtPrice= new JTextField();
                   txtPrice.setFont(fnt);
                   txtPrice.setBounds (120, 105, 175, 20);
                   btnEdit = new JButton("Edit");
                   btnEdit.addActionListener(this);
                   btnEdit.setBounds (50, 295, 100, 25);
                   btnEdit.setMnemonic(KeyEvent.VK_E);
                   btnClose= new JButton("Close");
                   btnClose.addActionListener(this);
                   btnClose.setBounds (170, 295, 100, 25);
                   btnClose.setMnemonic(KeyEvent.VK_C);
                   editPanel = new JPanel();
                   editPanel.setLayout(null);
                   editPanel.add(lblbookID);
                   editPanel.add(lblbookName);
                   editPanel.add(lblbookAuthorName);
                   editPanel.add(lblPrice);
                   editPanel.add(txtbookID);
                   editPanel.add(txtbookName);
                   editPanel.add(txtbookAuthorName);
                   editPanel.add(txtPrice);
                   editPanel.add(btnEdit);
                   editPanel.add(btnClose);
                   getContentPane().add(editPanel);
                public void actionPerformed(ActionEvent ae)
    }Could anyone Please Run my code and Help me to Update the JTable Record.
    Thank you for your Help
    Cheers
    Jofin

    Your EditForm needs acces to the TableModel and the current row you are editing. Then when the user clicks the save button you simply use the TableModel.setValueAt(...) method to update the model and the table will be repainted automatically.

Maybe you are looking for

  • Difference between Select *    and Select single     ?

    difference between Select *    and Select single     ?

  • How to get the output of a single command from multiple servers using power shell

    Hi All, I have a requirement in my project, wherein I have to find the database list on each server which has autoshrink option is enabled. Below is the query which I'm using and I want to automate it in such a way that, I can give the input to power

  • How to popup an OAF page in a new window?

    Hi all, I hava a requirement to popup an OAF page in a new window when i touch a image . When i touch the image,popup a new OAF page ,and the orial page become invalid like LOV, there are some messageTextInput items and a 'Confirm' submitButton in th

  • How do I connect my mouse??

    Hello, I am having problems connecting my mouse. I did it once and have never been able to do it again.  I have the HPG72B53NR Notebook and the HP mouse.  I would appreciate any help as I really need to use my mouse with the work i am doing. Thank yo

  • BI Publisher Desktop - Log On menu question

    Hi, When I press Log On button is asking me about username, password and Report Server. Does anybody knows what address should I put in Report Server,? I'm using BI Publisher Desktop 5.6.3 and Oracle Apps.....I'm not using XMLP Enterprise. Regards, M