Problem of JTable's column setPreferredWidth.

Hi All,
I have a problem about JTable,I want to set the preferredwidth for every column when the table is first established,but it is always failed.
Could someone tell me the root?Thanks!
import java.awt.*;
import javax.swing.*;
public class MixerTest2 extends JFrame {
public MixerTest2() {
super("Customer Editor Test");
setSize(600,160);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTable typeTable=new JTable();
typeTable=new JTable(new String [][] {
{"312fs", "33232", "32", "32"},
{"3212fsdfa12", "3322", "32", "32"},
{"3212fa12", "321212", "321212", "321212"},
{"3212gsds12", "321212", "321212", "321212"}
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
typeTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
typeTable.getColumnModel().getColumn(0).setPreferredWidth(10);
typeTable.getColumnModel().getColumn(1).setPreferredWidth(30);
JScrollPane typeTableScrollPane=new JScrollPane(typeTable);
getContentPane().add(typeTableScrollPane);
public static void main(String args[]) {
MixerTest2 mt = new MixerTest2();
mt.setVisible(true);
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
The problem is that the size of the frame is greater than the size of the table so the widths of all the columns get adjusted after you specify the original default size.
Your code should be something like:
typeTable.setPreferredScrollableViewportSize(typeTable.getPreferredSize());
JScrollPane typeTableScrollPane=new JScrollPane(typeTable);
mt.pack();
mt.setVisible(true);Or you might be able to use my [Table Column Adjuster|http://www.camick.com/java/blog.html?name=table-column-adjuster] which will resize the columns automatically.

Similar Messages

  • Problem while inserting new Column in JTable

    Hi,
    I am facing Problem while inserting new Column in JTable.
    I have a JTable with one inherited ColumnModel class.
    When I am adding the column and moving towards the corresponding location, it moves successfully.
    but if I am adding another column or making any changes to table column structure the table retains the defualtcolumn structure.
    please help me to solve this..
    Regards
    Ranjith.........

    Maybe this example will help:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=579527

  • Problem faced when the column is moved in Jtable

    Say , in a JTable 3 columns are present. the cells under the 2nd column is editable and 3rd is not editable. when i move the rd column to the second column position, the cells which were under second column becomes non editable. How to overcome this??

    when i move the rd column to the second column position, the cells which
    were under second column becomes non editable.Why do they become non editable?
    If I understand correctly when you call a TableModel's isCellEditable(int
    rowIndex, int columnIndex) the columnIndex argument has nothing to
    do with with where on the displayed JTable the column is being displayed.

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • Problem with JTable in a JScrollPane

    Hello all,
    I have a problem using JTable, that the number of columns is very big,
    and the JScrollPane shows only vertical ScrollBar, isn't there any way to show a horizontal ScrollBar, to show the other columns without being bunched.
    Thanks in advance.

    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • Scrollbar problem with JTable.

    Hi,
    I have 45 columns in a JTable. Please remember this is customize, we can change the number of columns dynamically, at max they can be 2 columns.
    i was having a problem with display the columns names in my Frame. I posted at http://forum.java.sun.com/thread.jspa?threadID=5167358&messageID=9641265#9641265
    I got the solution. Thanks for that.
    But as i said these columns are customized.
    when i am having 2 columns in my JTable, table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); is behaving differently, it's not occupying the complete JFrame. Lots of space is left out beside these 2 columns.
    When i comment this line, then those 2 columns are occupying my complete Frame.
    these two colmns should occupy my complete Frame and if i select 45 columns i should get scroll bar at botton with complete column NAMES.
    Hope i am clear.
    My Snippet
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    public class SimpleTable extends JPanel {
        private boolean DEBUG = false;
        public SimpleTable() {
            super(new BorderLayout());
                        String[][] values = new String[10][];
            String[] columnNames = {
                                                                                    "First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian"
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
                        DefaultTableModel defaulttablemodel = new DefaultTableModel(data,columnNames);
            final JTable table = new JTable(defaulttablemodel)
                 public boolean isCellEditable(int row,int column)
                                  return false;
                        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                        //table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
                        JScrollPane scrollPane = new JScrollPane(table);
                        add(scrollPane);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("SimpleTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            SimpleTable newContentPane = new SimpleTable();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thank You camickr, it's serving my purpose.
    Just for a clarrification :
    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    table.setAutoscrolls(false);without using these lines also my purpose is serving.....then y do we need above two lines of code. r they necessary
    i mean, this snippet is sufficient.
    public boolean getScrollableTracksViewportWidth()
         return getPreferredSize().width < getParent().getWidth();
    }

  • Colum Resizing problem in JTable

    HI All,
    I am facing a problem with JTable while resizing the colum. when user clicks and drags to resize a column, the column width increases continuously till the mouse button is released. I am sure this sounds like a vague description,
    (eg)
    when I click on a column boundary and drag, the column width is getting increase beyond where the cursor of the mouse is. In a normal table, when I click and drag, the column resizes to the size that I have the mouse position at, and gets set to the width when I release the mouse. But right now, when I click the mouse and drag to say a width of 50 from 10, it is still increasing beyond 50 and stops when I release the mouse at about 100 or higher. I hope this is a clearer explanation.
    In Java 1.2, it works fine. but in java 1.4...
    If Anyone knows, please let me know
    Advance thanks for any comments and suggestion..
    Best Regards,
    Muthu

    I solved this problem... Problem is getPreferredSize() method. I override this method
    Thank u for ur suggestion..
    Best Regards,
    Muthu

  • JTable (dynamic columns)

    Well guys, voil� my problem...
    I've a Person class, who has some methods to get the person information, like getName(), getAge(), getAdresse(), etc... I would display the information of all the persons in the diary in a JTable... Ok, it's all right, i made a class who extends AbstractModelTable, overriding the getValueAt(int, int) with a switch:
    // private static final int COLUMN_NAME = 0;
    // private static final int COLUMN_NAME = 1;
    switch (column) {
            case COLUMN_NAME:
                  return cols[rowIndex].getName();
             case COLUMN_AGE:
                   return cols[rowIndex].getAge();
              default:
                    return;
    }The code it's something like that... I'm sorry i don't show the code, i've not the source here!
    It works very fine!... But now, i want to let the user choose witch columns to display...
    I made a lot of tries, but i could not get the solution... The only one thing I could, was to eliminate the columns with zero value in the conf file, but the headers were not in the correct order!... And there's another problem too, when I switch the columnIndex, if it equals to COLUMN_EMAIL = 15 means that JTree is getting the value of the 15th column, but if the user had removed the 2 column for example, the 15th column is not more the email column, it's the 15+1 columns :S... is it clair? I think it's a little difficult to explain, and as you see, i don't speak english very well :P...
    Summary: I would create a class extending JTable with columns configurables, i mean, let the user choose witch columns should be showed... Any idea ?... I can avoid the JTable component, so If you've another solution, it will be ok...
    Greetings and thank you guys...

    Your requirement is very general so we can't give you an exact solution, but I can try explaining how JTable works.
    The TableModel is used to store the data. The JTable is used to display the data. When a table is first created using a TableModel a TableColumnModel is created. Each TableColumn in the TableColumnModel maps directly to a column in the TableModel.
    Now what happens if the user moves column 15 to the first column in the table? The data hasn't changed, only the view of the data has changed. So even though the column is in column 0 of the table, the data must still come from column 15 in the TableModel. The TableColumns of the TableColumnModel do the mapping for you so you don't need to worry about the reordering of columns.
    However, if you have some code in your program that accesses the data directly, then you need to be aware of this situation. Fortunately JTable has some methods to make this mapping easy.
    table.getValueAt(...) will get data from the requested column in the view of the table
    table.getModel().getValueAt(...) will get data form the requested column in the TableModel.
    You can also do the mapping between "view" and "model" columns using the methods:
    table.convertColumnIndexToModel(...)
    table.convertColumnIndexToView(...) So what does this mean with dynamic columns? Well, you would build your table normally, then you would remove the TableColumns from the TableColumnModel that the user does not want to see.
    The following example is so code I wrote a while ago that will help in manipulating the TableColumnModel. Right click on the TableHeader to see the visible/hidden status of each column:
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableColumnManager implements MouseListener, ActionListener
         private static final String HIDDEN_COLUMN = "HiddenColumn:";
         //  Reference to the Singleton instance of this class
         private static TableColumnManager singleton;
         *  Use a private constructor so we can create a Singleton.
         private TableColumnManager()
         *  Get the Singleton instance of the <code>TableColumnManager</code>.
         *  @return  the Singlton instance of <code>TableColumnManager</code>
         private static TableColumnManager getInstance()
              if (singleton == null)
                   singleton = new TableColumnManager();
              return singleton;
         *  Add support for the management of visible <code>TableColumns</code>
         *  for a given <code>JTable</code>.
         *  @param  table the table to provide support for
         public static void install(JTable table)
              table.getTableHeader().addMouseListener( getInstance() );
         *  Remove support for the management of visible <code>TableColumns</code>
         *  for a given <code>JTable</code>.
         *  @param  table the table to remove support from
         public static void uninstall(JTable table)
              table.getTableHeader().removeMouseListener( getInstance() );
         *  Hide a column from view in the table.
         *  @param  table        the table from which the column is removed
         *  @param  modelColumn  the column index from the TableModel
         *                       of the column to be removed
         public static void hideColumn(JTable table, int modelColumn)
              int viewColumn = table.convertColumnIndexToView( modelColumn );
              if (viewColumn != -1)
                   TableColumn column = table.getColumnModel().getColumn(viewColumn);
                   hideColumn(table, column);
         *  Hide a column from view in the table.
         *  @param  table        the table from which the column is removed
         *  @param  columnName   the column name of the column to be removed
         public static void hideColumn(JTable table, String columnName)
              try
                   TableColumnModel tcm = table.getColumnModel();
                   int index = tcm.getColumnIndex( columnName );
                   TableColumn column = tcm.getColumn( index );
                   hideColumn(table, column);
              catch(IllegalArgumentException e) {}
         *  Hide a column from view in the table.
         *  @param  table   the table from which the column is removed
         *  @param  column  the TableColumn to be removed from the
         *                  TableColumnModel of the specified table
         public static void hideColumn(JTable table, TableColumn column)
              table.getColumnModel().removeColumn( column );
              //  Save the column so it can be redisplayed
              ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
              if (list == null)
                   list = new ArrayList();
                   table.putClientProperty(HIDDEN_COLUMN, list);
              list.add(column);
         *  Show a hidden column in the table.
         *  @param  table        the table to which the column is added
         *  @param  modelColumn  the column index from the <code>TableModel</code>
         *                       of the column to be added
         public static void showColumn(JTable table, int modelColumn)
              ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
              if (list == null) return;
              ListIterator it = list.listIterator();
              while (it.hasNext())
                   TableColumn column = (TableColumn)it.next();
                   if (column.getModelIndex() == modelColumn)
                        table.getColumnModel().addColumn( column );
                        it.remove();
                        break;
         *  Show a hidden column in the table.
         *  @param  table        the table to which the column is added
         *  @param  columnName   the column name from the <code>TableModel</code>
         *                       of the column to be added
         public static void showColumn(JTable table, String columnName)
              ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
              if (list == null) return;
              ListIterator it = list.listIterator();
              while (it.hasNext())
                   TableColumn column = (TableColumn)it.next();
                   if (column.getHeaderValue().equals(columnName))
                        table.getColumnModel().addColumn( column );
                        it.remove();
                        break;
         //  Implement the MouseListener
         public void mousePressed(MouseEvent e)
              checkForPopup( e );
         public void mouseReleased(MouseEvent e)
              checkForPopup( e );
         public void mouseClicked(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         private void checkForPopup(MouseEvent e)
              if (e.isPopupTrigger())
                   JTableHeader header = (JTableHeader)e.getComponent();
                   int column = header.columnAtPoint( e.getPoint() );
                   showPopup(header.getTable(), column);
         *  Show a hidden column in the table.
         *  @param  table        the table to which the column is added
         *  @param  columnName   the column name from the <code>TableModel</code>
         *                       of the column to be added
         public static void showPopup(JTable table, int tableColumn)
              int columns = table.getModel().getColumnCount();
              JCheckBoxMenuItem[] items = new JCheckBoxMenuItem[columns];
              //  Create menu items for hidden columns
                 ArrayList list = (ArrayList)table.getClientProperty(HIDDEN_COLUMN);
                 if (list != null)
                   ListIterator it = list.listIterator();
                   while (it.hasNext())
                        TableColumn column = (TableColumn)it.next();
                        String columnName = column.getHeaderValue().toString();
                        JCheckBoxMenuItem item = new JCheckBoxMenuItem( columnName );
                        item.setSelected( false );
                        item.addActionListener(getInstance());
                        items[column.getModelIndex()] = item;
              //  Create menu items for visible columns
              TableColumnModel columnModel = table.getColumnModel();
              int columnCount = columnModel.getColumnCount();
              for (int i = 0; i < columnCount; i++)
                   TableColumn column = columnModel.getColumn(i);
                   String columnName = column.getHeaderValue().toString();
                   JCheckBoxMenuItem item = new JCheckBoxMenuItem( columnName );
                   item.setSelected( true );
                   item.addActionListener(getInstance());
                   items[column.getModelIndex()] = item;
              //  Create popup menu from array of menu items.
              //  Override the setSelected method to select the
              //  specified menu item. (ie. this is a bug fix)
              JPopupMenu popup = new JPopupMenu()
                   public void setSelected(Component sel)
                        int index = getComponentIndex( sel );
                        getSelectionModel().setSelectedIndex(index);
                        final MenuElement me[] = new MenuElement[2];
                        me[0]=(MenuElement)this;
                        me[1]=getSubElements()[index];
                        SwingUtilities.invokeLater(new Runnable()
                             public void run()
                                  MenuSelectionManager.defaultManager()
                                       .setSelectedPath(me);
              for (int i = 0; i < items.length; i++)
                   if (items[i] != null)
                        popup.add( items[i] );
              //  Display the popup below the TableHeader
              JTableHeader header = table.getTableHeader();
              Rectangle r = header.getHeaderRect( tableColumn );
              popup.show(header, r.x, r.height);
              int modelColumn = table.convertColumnIndexToModel( tableColumn );
              popup.setSelected( items[modelColumn] );
         *  Responsible for processing the ActionEvent. A column will either be
         *  added to the table or removed from the table depending on the state
         *  of the menu item that was clicked.
         * @param event the ActionEvent.
         public void actionPerformed(ActionEvent event)
              JMenuItem item = (JMenuItem)event.getSource();
              JPopupMenu popup = (JPopupMenu)item.getParent();
              JTableHeader header = (JTableHeader)popup.getInvoker();
              JTable table = header.getTable();
              if (item.isSelected())
                   showColumn(table, item.getText());
              else
                   hideColumn(table, item.getText());
         public static void main(String[] args)
              JTable table = new JTable( new DefaultTableModel(5, 10) );
              TableColumnManager.install(table);
              TableColumnManager.hideColumn(table, 2);
              TableColumnManager.hideColumn(table, "E");
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( new JScrollPane(table) );
              frame.pack();
              frame.setVisible( true );
    }Hopefully I've made some sense.

  • Problems with JTable

    Hi All,
    I am facing some problems in JTable :
    1) How to remove all lines between cells, neither i should have column nor row lines....there should not be any lines between any cell at all.
    2) If i select a perticular cell, complete row is getting selected with a blue background, that should not happen at all.....row should not get select....
    3) How to make a cell non editable.
    Regards,
    Ravi

    1) Read the API. Check out the set??? methods until you fine what you want
    2) Read the API. Check out the methods that deal with row and column selection
    3) Override isCellEditable(...) method of JTable or DefaultTableModel

  • JCheckBox clicking problem in JTable

    Hi,
    I have a column of JCheckBox in a JTable. The JTable is only used to layout the controls(for lagecy reason). The JCheckBox has an item change listener attached. The problem is that OCCASIONALLY when the JCheckBox[i] was clicked, the debug in itemStateChanged show the source object was NOT JChechBox, it was JCheckBox[i+1] or JCheckBox[i-1]. In other word, it was the check box in the previous or next row changed state.
    Has anybody experienced similar problems? Is it a problem of JTable dispatching mouse click event?
    How to solve the problem?
    Thanks

    I'm not sure why you get the results you do, but instead of adding a change listener to the JCheckBox you could add a TableModelListener to the TableModel. This will fire an event whenever any data is changed. This thread shows a simple example:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=425540

  • JTable Selecting Column/Row

    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TableDemo extends JPanel {
        private boolean DEBUG = false;
        public TableDemo() {
             super(new GridLayout(1,0));
             JTable table = new JTable(new MyTableModel());
             table.setPreferredScrollableViewportSize(new Dimension(500, 70));
             JScrollPane scrollPane = new JScrollPane(table); //Set up column sizes.
             initColumnSizes(table); //Fiddle with the Sport column's cell editors/renderers.
             setUpSportColumn(table, table.getColumnModel().getColumn(2)); //Add the scroll pane to this panel.
             add(scrollPane);
        private void initColumnSizes(JTable table) {
             MyTableModel model = (MyTableModel)table.getModel();
             TableColumn column = null;
             Component comp = null;
             int headerWidth = 0;
             int cellWidth = 0;
             Object[] longValues = model.longValues;
             TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
             for (int i = 0; i < 3; i++) {
             column = table.getColumnModel().getColumn(i);
             comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0);
             headerWidth = comp.getPreferredSize().width;
             comp = table.getDefaultRenderer(model.getColumnClass(i)). getTableCellRendererComponent( table, longValues, false, false, 0, i);
         cellWidth = comp.getPreferredSize().width;
         if (DEBUG) {
         System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
         column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
         JComboBox comboBox = new JComboBox();
         comboBox.addItem("SnowBoarding");
         comboBox.addItem("Rowing");
         comboBox.addItem("Knitting");
         comboBox.addItem("Speed reading");
         comboBox.addItem("Pool");
         comboBox.addItem("None of the above");
         sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
         DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
         renderer.setToolTipText("Click for combo box");
         sportColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
         private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
         private Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)} };
         public final Object[] longValues = {"Sharon", "Campione", "None of the above", new Integer(20), Boolean.TRUE};
         public int getColumnCount() {
                   return columnNames.length;
    public int getRowCount() {
         return data.length;
    public String getColumnName(int col) {
         return columnNames[col];
    public Object getValueAt(int row, int col) {
         return data[row][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) {
         if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
         data[row][col] = value; fireTableCellUpdated(row, col);
         if (DEBUG) {
         System.out.println("New value of data:");
         printDebugData();
    private void printDebugData() {
         int numRows = getRowCount();
         int numCols = getColumnCount();
         for (int i=0; i < numRows; i++) {
         System.out.print(" row " + i + ":");
         for (int j=0; j < numCols; j++) {
              System.out.print(" " + data[i][j]);
         System.out.println();
         } System.out.println("--------------------------");
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("TableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TableDemo newContentPane = new TableDemo();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() { createAndShowGUI();
    According to this Application the rendering and cell editing is done based on the column. And it displays the same column values for each row.
    I want to use the same application but want to change the[b] set of column values for each row.
    ex:
                    [u] Column values[/u]
    Row 0 =  { Snowboarding ,Rowing, Knitting.......}
    Row 2 = {  A,B,C,..........}
    Row 3 = {1,2,3}
    Help PLEASE!!!!
    thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    This posting shows one way:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=446022

  • Another problem with JTable

    Hi,
    I have encountered a problem with JTable, i am trying to display some 15 columns and their values , one of the columns value is null, then the JTable is not displaying its value from this column(which is with null value) onwards.
    Can anybody assiss me in this matter.
    Regards
    khiz_eng

    I don't know If I can fix your problem, but
    I know just that it works on my PC.... It's very very
    slow... I don't know how to insert PageSetUp option... I have to study the problem.....
    However I don't think it's a hard problem....
    I want ask to you if you have found some problems when you are in Editing mode in a cell.....
    in the jdk1.2 version I could save while was in editing mode using the editingStopped method.
    It permit to update all data .... also the data in the cell I was editing.
    in the jdk 1.3 if I use this method It doesn't work properly... It maybe destroy the content object in the Cell..... because I'm able to print all the table except the editing cell (it throw an exception...)
    What's changed????
    I don't know...
    Can u help me?

  • A problem with JTable

    Hi !
    I have a problem with JTable - would like to use this component as a simple list of rows taken from a database : don't want to be able select or set a focus to a column - want only to be able select and set focus to a row ( just like in the menus). How to disable "focusability" for a cell with JTable ? Could You help me ?
    thnx in advance

    The Border is changed by the renderer, depending on whether the cell has focus or not. So you will need to create custom renderers without a Border. Something like:
    class NoBorderRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent(
              JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
              super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              setBorder(null);
              return this;
    }

  • Facing problem with a date column in select query

    Hi,
    I am facing problem with a date column. Below is my query and its fainling with " invalid number format model" .
    Query: SELECT *
    FROM EMP
    WHERE trunc(LAST_UPDATED) >= to_date(to_char(22-05-2009,'dd-mm-yyyy'),'dd-mm-yyyy')
    LAST_UPDATED column is "DATE" data type.
    Please help me Thanks

    Radhakrishna Sarma wrote:
    SeánMacGC wrote:
    WHERE LAST_UPDATED >= to_date('22-05-2009','dd-mm-yyyy');
    You do not need the TRUNC here in any case.
    I don't think so. What if the user wants only data for 22nd May and the table has records with date later than 22nd also? In that case your query willl not work. In order for the Index to work, I think the query can be written like this I think Sean is right though. Use of TRUNC Function is quiet useless based on the condition given here, since the to_date Function used by OP will always point to midnight of the specified date, in this case 22-05-2009 00:00:00.
    Regards,
    Jo
    Edit: I think Sean proved his point... ;)

Maybe you are looking for

  • Error in running file

    I write a program to convert a plain message into a scrambled message. During the compliation, nothing happened. When I run the program, it says ArrayIndexOutOfBondsException: 26. I have no idea how to solve the problem. I have highlighted the line w

  • Runtime Errors         ASSIGN_LENGTH_0

    Hello Experts, This is the problem which has occurred during upgrade from 4.6 to ecc 6.0. Runtime Errors         ASSIGN_LENGTH_0                                                              Date and Time    03/05/200                                  

  • Cd stuck in superdrive

    I have an cd stuck in the superdrive. It gets out only partial but something still got hold of it inside the drive. So I can not force it out. the only solution seems to be to lay the mac flat on it's face (display) and then eject the cd. It comes ou

  • When i try to update i recieve an error Error Code: U43M1D219

    Tried downloading Premier and AE updates today .. keeps saying failed .. Loaded Media Encoder no problem ..

  • Issue with serial number - cs6

    i have a windows 8 hp computer have been running  adobe cs6 master suite for almost a year, no problem. i have a legitimate serial number, obtained through my design college. around the time windows 8 updated to 8.1, my issue with the serial number b