JTable Column Headers are Squashed!

Hi there,
I'm using JBuilder, and have created a simple enough JTable that I place inside a JScrollPane. I am using my own implementation of the AbstractTable model.
When I run the code, the Column headers are only about 5 pixels high! I have hunted around the JBuilder code (which if you have used JBuilder you will know is extensive!), but it doesn't seem to be doing anything extraordinary.
So has anyone else had this problem? If so, what did you do to rectify.
Yours hopefully
Richard

Hello there, my abstract implementation looks a little like this:
  public static final String columns[] = { "", "Request Id", "Date", "Component Name", "Version", "Type" };
  public String getColumnName(int columnIndex) {
    return columns[columnIndex];
  public Class getColumnClass(int columnIndex) {
    if (columnIndex == 0) {
      return Boolean.class;
    } else if (columnIndex == 1) {
      return Integer.class;
    } else {
      return String.class;
  }Thanks
Richard

Similar Messages

  • Cant see jtable column headers

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

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

  • JTable column headers missing..kindly help...

    Hello there!
    I have written a program that ultimately deals with database connectivity, but my problem is got more to do with JTable. that's why i decided to post my doubt here.
    my program displays a JTable by reading fields form a database.
    But you see, the column headers are missing!!
    I have used the concept of DefaultTableModel, i first searched google and came upon a website: www.exampledepot.com and studied the sample codes on how insert fields into a JTable using the above....
    i swear to god i have done the exact same things..
    Could you please help me out??
    Thankyou very much and have a great day!
    :-)

    done that alreadyThen your problem is solved?
    Or does that mean that you had already done it and no headings showed up? In that case there's something wrong with your code.
    And Swing questions should be posted in the Swing forum.

  • Column Headers are Jumbled when exporting to 'Excel Data only'

    Hi,
    When I am exporting a report to 'Excel Data only' the column headers are jumbled in the output,where as the data field are exported in the same order as it is in the report .
    They are being exported as
    Header:F3   F2    F1
    Detail   :F1   F2    F3
    Instead of
    Header:F1   F2    F3
    Detail   :F1   F2    F3
    Is there a way I can over come this issue.

    Can you explain how exactly the report was designed? Is it happening for every report or only for this report?
    Regards,
    Raghavendra

  • JTable column headers not displaying using custom table model

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

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

  • Autofit JTable column headers

    I have a problem. I am using eclipse. What i want to do is that in a Jtable, i want such a mechanism that no matter what the table headers are(any font, size), the jtable adjusts the column width to show the whole table header. The headers and the fonts are read from a file.
    presently i m doing this:
    //used to set the column widths
    FontMetrics metrics = tbl.getFontMetrics(tbl.getFont());
    // Set column widths
    int tempWidth;
    for (int i=0; i<columnNames.length ; i++)
    tempWidth = metrics.stringWidth(tbl.getColumnName(i))+ (2 * tbl.getColumnModel().getColumnMargin());
    tcm.getColumn(i).setPreferredWidth(tempWidth);
    tcm.getColumn(i).setPreferredWidth(columnNames.length()*7);
    The problem is that this does not work for all fonts.
    Can ne 1 plz provide sample code???

    Here's the full code I posted before to do this.
    It resizes the entire JTable to fit the column size, no matter what font properties, and
    optionally includes using the column header as well.
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=606240
    regards,
    Owen

  • Export JTable Column headers to Excel document

    Hello all!!! I am having a small problem while trying to export some data from a jTable to an excel document.
    I have a jTable and I use a custom TableModel with this:
    private String[] columnNames = {"First", "Second", "Third", "Forth"};as names for each column of the table.
    The thing I am trying to do is to export exactly the same "headers" from the columns of the jTable to the excel spreadsheet using Jakarta POI. Unfortunately I don't know how to do it and I haven't found anything yet on this forum. Can anyone help me with this?
    In simple words I want to know how I can have the same headers from my jTable columns, with the headers from the excel doument I will create.
    Many thanks in advanve!!!
    Kostas

    Thank you for your reply first of all. The problem is how to get the heading text and how to put it to the excel's first row OR to excels "headings" (if it is possible...). [in other words replace A,B,C,D from the excel document with the headers I get from the jTable...] .
    I hope now you can see what I am looking for... If there is no solution to this please tell me what are the alternatives. (B) could be a good example.
    Thanks you very much!!
    Kostas

  • JTable column headers missing

    I created a JTable using:
    JTable table = new JTable(v,cN);
    where v is my vector that holds the data and cN is a vector to hold the column names as below:
    Vector cN = new Vector();
         cN.add("Registry Keys");
         cN.add("Program Name");
         cN.add("Key Type");
         cN.add("Drive");
         cN.add("Location");
         cN.add("Leave");It displays the table fine with the data and as I add or remove entries in the cN vector it adds and removes columns - but doesn't display column headers? Any help appreciated.

    Are you using a scrollpane? If not, you have to get the Table Header component and place it appropriately.

  • JTable column headers not showing up

    I have a JTable inside a JScrollPane which, in turn, is inside a JTabbedPane.
    I created a TableModel which extends AbstractTableModel as per the java Swing Tutorial examples.
    In that model is an Object[][] object for the data called rowData, and all the data displays in the table perfectly.
    I also have a String[] object called columnNames to define the column headers. ..the column names are coded directly into the object.
    i.e.: String[] columnNames = {"John", "Janet", "Jamie", "Jennifer"};But the column names don't display at all.....all I get in the column headers is 'A', 'B', 'C', etc.
    I need to know either
    1)how to set this up correctly in the first place or
    2)how I can reset the columns manually.
    I have tried adding the table 2 ways..as follows...but neither one gets the headers right:
    JScrollPane jScrollPane = new javax.swing.JScrollPane(getTable());or
    JScrollPane jScrollPane.setViewportView(getTable());Note: getTable()..is where the new javax.swing.JTabel(new TableModel())stuff is done.
    thx, ESW

    You mentioned the you columnNames array. I suggest you declare it as static and accessible from within your custom table modelprivate static final String[] COLUMN_NAMES = {"John", "Janet", "Jamie", "Jennifer"};Then you override/implement the following methods in your TableModel :public String getColumnName(int column) {
         return COLUMN_NAMES[column];
    public int getColumnCount() {
         return COLUMN_NAMES.length;
    }That should do the trick.

  • JTable Column Headers

    I want to create a JTable so that the table doesn't have any column headers. Right now I am using my own implementation of the AbstractTableModel Class for use with the tables, but if I leave out the public String getColumnName(int col) method, it makes the headers A, B, C, ... and if I set the column headers up with a blank String, it leaves an obvious thin empty header at the top. Any suggestions on how I can completely leave the column headers off?

    call the method on JTable
    table.setTableHeader(null);
    that will do the trick;
    cheers
    krishna

  • Fixed jtable column headers

    Does anyone have an example of fixing column headers for a JTable. Basically I want the column headers to be displayed when scrolling down the table.

    check the examples provided in "How to use table" -
    "http://java.sun.com/docs/books/tutorial/uiswing/components/table.html"
    The tables have fixed column header when u scroll down..

  • APD - Column Headers are not displaying properly when downloaded

    Hi All,
    I am trying to download a simple query as a comma delimited file on my desktop using APD.
    When I execute the APD, the all the data getting properly downloaded as required but I am facing the following problems.
    1) The column heading are coming as  garbage characters particularly for keyfigures
    2) The keyfigures are getting displayed first and then characters, I expect them similarly the query display
    3) I don't want to display the UNITS of the keyfigures to be displayed.
    Please let me know if anybody has idea on this.
    Regards,.
    Tapan

    Hi Tapan,
    Try using "Hide or Rename Columns(projection)".
    This allows you to rearrange the order of columns in file and also to rename the descriptions as needed.
    Regards,
    Vidya Sagar

  • Almost invisible JTable column headers

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

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

  • Saving JTable column headers

    I an writing a program in which I am trying to save a table. I can save all of the data from in the table by sending the TableModel to a file, but I cannot get the headers to save. I have tried saving the JTableHeader and am currently trying it by saving the TableColumnModel.
    This is the code for the saving and loading of the headers:
      * Save Header
      * @param pathname The relative path and filename
      * @return Returns true if successful, false if not
      public boolean saveHeader(String pathname){
        //if(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()).equals(null))
          //table.getModel().setValueAt("",table.getSelectedRow(), table.getSelectedColumn());
        if(!(table.getSelectedColumn() == 0)) table.setColumnSelectionInterval(0,0);
        /*try{
          if (table.isEditing()) { //To keep last value while saving
            TableCellEditor tc = table.getCellEditor();
            // To cancel the editing
            //tc.cancelCellEditing();
            // Or to keep the editor's current value
            if(tc != null)tc.stopCellEditing();
        catch(Exception d){
          d.printStackTrace();
        try{
          FileOutputStream fos2 = new FileOutputStream(pathname + "/attendanceheader.dat");
          ObjectOutputStream oos2 = new ObjectOutputStream(fos2);
          TableColumnModel tcm = (TableColumnModel)table.getColumnModel();
          oos2.writeObject(tcm);
            //oos.writeObject(tm);
          oos2.close();
          fos2.close();
          table.setFocusable(true);
        catch(Exception e){
          System.out.println(e.getMessage());
          return false;
        return true;
       * Load a file header
       * @param pathname The relative path and filename
       * @return Returns true if successful, false if not
      public boolean loadHeader(String pathname){
        //create a JTableHeader to hold the model of the header
        TableColumnModel tcm = null;
        try{
          //create FileInputStream and ObjectInputStream go get the table header
          FileInputStream fis2 = new FileInputStream(pathname +
                                                     "/attendanceheader.dat");
          ObjectInputStream ois2 = new ObjectInputStream(fis2);
          //get the JTableHeader from the file
          tcm = (TableColumnModel) (ois2.readObject());
          //set the JTableHeader and close the input streams
          table.setColumnModel(tcm);
          ois2.close();
          fis2.close();
        catch(Exception e){
          try{
            //try to make the file if it didnt exist
            File outputFile2 = new File(pathname + "/attendanceheader.dat");
            if(outputFile2.exists()) throw e;
            else{
              JTable temp = new JTable(table.getRowCount(), table.getColumnCount());
              table.setColumnModel(temp.getColumnModel());
              table.getColumnModel().getColumn(0).setHeaderValue("Last Name, First Name");
              saveHeader(pathname);
          catch(Exception f){
            System.out.println(e.getMessage());
            System.out.println(f.getMessage());
            return false;
        return true;
      }This is the exception I get:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:939)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:541)
         at javax.swing.JComponent.paint(JComponent.java:808)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JViewport.paint(JViewport.java:707)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JLayeredPane.paint(JLayeredPane.java:552)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4778)
         at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)
         at javax.swing.JComponent.paint(JComponent.java:798)
         at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
         at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
         at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
         at java.awt.Container.paint(Container.java:1309)
         at javax.swing.JFrame.update(JFrame.java:385)
         at sun.awt.RepaintArea.paint(RepaintArea.java:169)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:260)
         at java.awt.Component.dispatchEventImpl(Component.java:3699)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:140)
         at java.awt.Dialog.show(Dialog.java:538)
         at javax.swing.JOptionPane.showOptionDialog(JOptionPane.java:822)
         at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:624)
         at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:595)
         at EGA.UseGroup.actionPerformed(UseGroup.java:414)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.AbstractButton.doClick(AbstractButton.java:289)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1113)
         at javax.swing.plaf.basic.BasicMenuItemUI$MenuDragMouseHandler.menuDragMouseReleased(BasicMenuItemUI.java:1006)
         at javax.swing.JMenuItem.fireMenuDragMouseReleased(JMenuItem.java:585)
         at javax.swing.JMenuItem.processMenuDragMouseEvent(JMenuItem.java:482)
         at javax.swing.JMenuItem.processMouseEvent(JMenuItem.java:429)
         at javax.swing.MenuSelectionManager.processMouseEvent(MenuSelectionManager.java:274)
         at javax.swing.plaf.basic.BasicMenuUI$MouseInputHandler.mouseReleased(BasicMenuUI.java:344)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:227)
         at java.awt.Component.processMouseEvent(Component.java:5134)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    javax.swing.JTable$CellEditorRemover
    I could really use some help here...this is frustrating as all get out
    Thanks!

    wow!!!! I guess posting to this forum really got my brain going and I think it's working just great now!
    I figured out i was throwing some wrong exceptions, so i made exceptions that threw the message "Fine" to know when an exception was good. I used the finction table.removeEditor() to get rid of the TableEditorRemover error. I'll post the updated code for you all!
      * Attendance Save Header
      * @param pathname The relative path and filename
      * @return Returns true if successful, false if not
      public boolean saveHeader(String pathname){
        //if(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()).equals(null))
          //table.getModel().setValueAt("",table.getSelectedRow(), table.getSelectedColumn());
        //if(!(table.getSelectedColumn() == 0)) table.setColumnSelectionInterval(0,0);
        /*try{
          if (table.isEditing()) { //To keep last value while saving
            TableCellEditor tc = table.getCellEditor();
            // To cancel the editing
            //tc.cancelCellEditing();
            // Or to keep the editor's current value
            if(tc != null)tc.stopCellEditing();
        catch(Exception d){
          d.printStackTrace();
        try{
          FileOutputStream fos2 = new FileOutputStream(pathname + "/attendanceheader.dat");
          ObjectOutputStream oos2 = new ObjectOutputStream(fos2);
          table.removeEditor();
          TableColumnModel tcm = (TableColumnModel)table.getColumnModel();
          oos2.writeObject(tcm);
            //oos.writeObject(tm);
          oos2.close();
          fos2.close();
          table.setFocusable(true);
        catch(Exception e){
          System.out.println(e.getMessage());
          e.printStackTrace();
          return false;
        return true;
       * Load a file header
       * @param pathname The relative path and filename
       * @return Returns true if successful, false if not
      public boolean loadHeader(String pathname){
        //create a JTableHeader to hold the model of the header
        TableColumnModel tcm = null;
        try{
          //create FileInputStream and ObjectInputStream go get the table header
          FileInputStream fis2 = new FileInputStream(pathname +
                                                     "/attendanceheader.dat");
          ObjectInputStream ois2 = new ObjectInputStream(fis2);
          //get the JTableHeader from the file
          tcm = (TableColumnModel) (ois2.readObject());
          //set the JTableHeader and close the input streams
          table.setColumnModel(tcm);
          ois2.close();
          fis2.close();
        catch(Exception e){
          try{
            //try to make the file if it didnt exist
            File outputFile2 = new File(pathname + "/attendanceheader.dat");
            if(outputFile2.exists()) throw new Exception("Fine");
            else{
              JTable temp = new JTable(table.getRowCount(), table.getColumnCount());
              table.setColumnModel(temp.getColumnModel());
              table.getColumnModel().getColumn(0).setHeaderValue("Last Name, First Name");
              saveHeader(pathname);
          catch(Exception f){
            System.out.println(e.getMessage());
            System.out.println(f.getMessage());
            if(f.getMessage().equals("Fine")) return true;
            return false;
        return true;
      }

  • JTable update, column headers

    I am trying to write my own tablemodel which does not change the specified
    column widths when updating. So far everthing works fine, only the column
    headers are not repainted. Does anybody know what is missing?
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class UpdateTable
    { static String headers[]= {"Baum", "Blatt", "Frucht","H�usigkeit"};;
      static String data[][]= {
         {"Eiche", "gez�hnt","Eichel","ein"},
         {"Buche", "glatt", "Buchecker","ein"},
         {"Tanne", "Nadel", "Zapfen","ein"},
         {"Pappel", "wechselst�ndig","Kapsel","zwei"},
      static MyTableModel tblModel;
      static JTable table;
      public UpdateTable()
      { JFrame frame = new JFrame("UpdateTable");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        tblModel = new MyTableModel(data, headers)
        { // Make read-only
          public boolean isCellEditable(int x, int y)
          { return false;
        table = new JTable(tblModel);
        table.getColumnModel().getColumn(1).setPreferredWidth(200);
        table.getColumnModel().getColumn(3).setPreferredWidth(20);
          // Set selection to first row
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectionModel.addListSelectionListener (new ListSelectionListener()
        { public void valueChanged(javax.swing.event.ListSelectionEvent e)
            if (e.getValueIsAdjusting()) return;
                System.out.println(table.getSelectedRow());
          // Add to screen so scrollable
        JScrollPane scrollPane = new JScrollPane (table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 100);
        frame.setVisible(true);
      public static void main(String args[])
      { new UpdateTable();
        try
        { Thread.sleep(3000);
        catch (InterruptedException e)
        { System.out.println ("Fehler: "+ e.toString());
        String headers_neu[] = {"Arbre", "Feuille", "Fruit", "Maisonette"};
        headers = headers_neu;
        data[0][0]= "Eberesche";
        tblModel.setDataVector(data, headers);
    //    table.revalidate(); // is of no use.
        table.repaint();
    // The table model
    class MyTableModel extends AbstractTableModel
      private int cols, rows;
      private String[] columnNames;
      private String[][] data;
      public MyTableModel(int cols, int rows)
      { this.cols = cols;
        this.rows = rows;
      public MyTableModel(String[][] data, String[] columnNames)
      { setDataVector(data, columnNames);
      public String getColumnName(int col)
      { return columnNames[col].toString();
      public int getColumnCount()
      { return cols;
      public int getRowCount()
      { return rows;
      public Object getValueAt(int row, int col)
      { return data[row][col];
      public void setDataVector(String[][] data, String[] columnNames)
      { this.cols = data[0].length;
        this.rows = data.length;
        this.data= data;
        this.columnNames= columnNames;
    //    Firing the event will change column widths as usual.
    //    fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    }

    // fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    You have to fire a table changed event.
    The table neverasks the model if things have changed. The model always notifys the table of changes.
    No event fired no table repaint.
    Instead of fireTableChanged(...) you have the option of fireTableDataChanged() (if only the data has changed, not the nomber of columns or the type of columns) and fireTableStructureChanged() (if there have been columns changed).
    If fireTableStructureChanged happens (and HEADER_ROW event is the same thing), the table removes the columns and creates new onew. That's why column sizes are lost.
    If you really want the table not to manage columns, you have to do it yourself:
    Implement your own TableColumnModel and pass it to the table constructor. When adding/removing columns you can ask what was the size of the previous columns where and set the new columns to that size.
    Call setAutoCreateColumnsFromModel(false) in your table constructor so that the table will not remove/create new columns itself when a tableStructureChanged event happens.

Maybe you are looking for

  • Is there a video editing app for ipad that will allow the adjustment of the speed of a clip?

    I'm trying to speed up/slow down clips in a project on iPad, which, I have found, iMovie does not allow you to do. Is there another app that will allow me to do so?

  • How to disable player controls when embedding mp4 video?

    I am trying to embed a mp4 video in a web page. Is there a tag for hiding the player's controls? I want my video to loop without any display of the player controls. Also, if anyone knows of some sample code for embedding .mp4 with all available tags

  • CGI install under 6.1 on Solaris

              Have configured WL6.1 to use cgi from it's default web app -           I get the following error when I attempt to execute a script           Error 500--Internal Server Error           From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:

  • A Important problem about CMS Transport Studio Test Tab

    Hi experts:     I am use NWDI and modify ESS source code, when i check in my  modified project like esstratre and release  it .  In CMS  transport studio i consolidation , assembly it then test it .but i make a  fatal mistake,there is some mistake in

  • Email link through a flash movie

    I made a website in flash so I want to put my email address there also so if they want to contact me they can just click on it and the default email app will open up. I know how to do that in Dreamweaver (it's that mailto: command) so how do you do i