JTable - column move and column spacing

Hi,
Can someone please show me how to prevent users from being able to move columns. I am not finding any code to do this.
Also, how do I set fixed width for columns. I am using vectors to populate the data
Much appreciated

Hi,
This is a beginner level question and you should have been able to figure this out yourself.
Have an array with size equal to the number of columns you have and store in each element of the array the size you want for the column. Then your code should be easy.
// For a table with 4 columns
double [] columnWidths = { 100.0, 109.0, 120.0, 95.0 };
TableColumnModel columnModel = jTable.getColumnModel();
               for ( int k = 0, count = columnModel.getColumnCount(); k < count; k++ ) {
                   TableColumn column = columnModel.getColumn( k );
                   // Do you mean this?
                  column.setResizable( true );
                   // or this ?
                                                                               column.setMinWidth( columnWidths[k] );
                   column.setMaxWidth( columnWidths[k] );
               cheers,
vidyut
http://www.bonanzasoft.com

Similar Messages

  • Check flat file column list and column types

    Hi guys!
    Is there any "easy" way to check if the source flat file column names and column types correspond to target datastore column name and types ?
    Regards,
    PsmakR

    Hi,
    There is a way that I already used some time to validate if the data is the one expected into target.
    Conditions:
    1) The file source must have all columns as "String"
    2) All mapping for the analysed columns must be done at "staging area"
    How I do it: (oracle way)
    1) create a database function (by ODI procedure) like:
    create or replace function F$_DATATYPE (pData in varchar2, pDatatype in varchar2, pFormat in varchar2)
    return varchar2 as
    vDate date;
    vNumber number;
    BEGIN
    if pDatatype = 'D' then /* Date */
    vDate := to_date(pData, pFormat);
    elsif pDatatype = 'N' then /* Number */
    if pFormat is null then
    vNumber := to_number(pData);
    else
    vNumber := to_number(pData, pFormat);
    end if;
    end if;
    return 'OK';
    EXCEPTION
    When OTHERS then
    return 'KO';
    end F$_DATATYPE ;
    3) Now you can create a constraint to each source column that you wish to validate data like:
    'OK' = F$_DATATYPE(my_source_column, 'D', 'ddmmyyyy hh24:mi:ss' ) /* to a date column as example */
    4) drag and drop the source datasource (table from model) into package and a E$ table with all errors will be created.
    Does it help you?

  • JTable fixed Row and Column in the same window

    Hi
    Could anyone tip me how to make fixed row and column in the same table(s).
    I know how to make column fixed and row, tried to combine them but it didnt look pretty.
    Can anyone give me a tip?
    Thanks! :)

    Got it to work!
    heres the kod.. nothing beautiful, didnt clean it up.
    * NewClass.java
    * Created on den 29 november 2007, 12:51
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package tablevectortest;
    * @author Sockan
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class FixedRowCol extends JFrame {
      Object[][] data;
      Object[] column;
      JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
      private int FIXED_NUM = 16;
      public FixedRowCol() {
        super( "Fixed Row Example" );
        data =  new Object[][]{
            {      "","A","A","A","",""},
            {      "a","b","","","",""},
            {      "a","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "I","","W","G","A",""}};
        column = new Object[]{"A","B","C","D","E","F"};
        AbstractTableModel fixedColModel = new AbstractTableModel() {
          public int getColumnCount() {
            return 1;
          public int getRowCount() {
            return data.length;
          public String getColumnName(int col) {
            return (String) column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel    model = new AbstractTableModel() {
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col+1];
          public Object getValueAt(int row, int col) {
            return data[row][col+1];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col+1] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedTopModel = new AbstractTableModel() {
          public int getColumnCount() { return 1; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedModel = new AbstractTableModel() {     
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return FIXED_NUM; }
          public Object getValueAt(int row, int col) {
            return data[row + (data.length - FIXED_NUM)][col+1];
        table = new JTable( model );
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTable = new JTable( fixedModel );
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedColTable= new JTable(fixedColModel);
        fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTopmodelTable = new JTable(fixedTopModel);
        fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);   
        JScrollPane scroll      = new JScrollPane( table );
         scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
          public void setColumnHeaderView(Component view) {}
        fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollBar bar = scroll.getVerticalScrollBar();
        JScrollBar dummyBar = new JScrollBar() {
          public void paint(Graphics g) {}
        dummyBar.setPreferredSize(bar.getPreferredSize());
        scroll.setVerticalScrollBar(dummyBar);
        final JScrollBar bar1 = scroll.getHorizontalScrollBar();
        JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
        bar2.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent e) {
            bar1.setValue(e.getValue());
        JViewport viewport = new JViewport();
        viewport.setView(fixedColTable);
        viewport.setPreferredSize(fixedColTable.getPreferredSize());
        fixedScroll.setRowHeaderView(viewport);
        fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
            .getTableHeader());   
        JViewport viewport2 = new JViewport();
        viewport2.setView(fixedTopmodelTable);
        viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
        scroll.setRowHeaderView(viewport2);
        scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
            .getTableHeader()); 
        scroll.setPreferredSize(new Dimension(600, 19));
        fixedScroll.setPreferredSize(new Dimension(600, 100)); 
        getContentPane().add(     scroll, BorderLayout.NORTH);
        getContentPane().add(fixedScroll, BorderLayout.CENTER);   
      public static void main(String[] args) {
        FixedRowCol frame = new FixedRowCol();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
        frame.pack();
        frame.setVisible(true);
    }

  • Refreshing JTable contents (rows and columns) handling.

    Hi,
    I have a general question related to refreshing the contents of JTable and handling some application specific requirements.In our application we are planning to refresh the contents of JTable automatically after certain period of time by fetching data from database and update the JTable contents or user has clicked refresh button.
    But following scenarios we are planning to handle when refresh is called automatically or user has clicked refresh button.
    1) User is working with data of JTable. Like rows of JTable has checkBoxes and user selects them and doing operation like viewing the details of selected rows in new details dialog. So if refreshing is done then the selection will be lost if I update the whole data in JTable.
    a)Will it be possible to append the data at the end of JTable rows without disturbing the existing JTable contents.
    b) Is it feasible to compare the data of existing rows and newly fetched rows and update only the rows whose values are changed in database or update specifically updated columns. But this comparision for finding changed values will result in performance problems.So are there any other alternatives of doing this, ideas are most welcome.
    c) Simple way is to alert the user that data will be updated and everything will be refreshed will be the choice in worst case.
    I guess many may have encountered such problems and may have solved it depending on the product requirements.
    Ideas and suggestions are most welcome.
    Regards.

    Hi,
    Here are my views and my assumptions.
    Assumptions :
    1) Your JTable is populated with list of Objects.
    2) Your tables in database is having columns like created date, created time, updated date updated time
    3) Order by clause for all the time will remain same.
    If these assumptions are correct then I think you can achieve your goal.
    Here how it is.
    Your application session will maintain last db hit time and will maintain for every hit that applicate made to fetch data from db.
    When object is created on the server side once it fetch data from table it will compare the created date/time or update date/time with the session varibale that holds last visit date/time. Based on this flag need to be set to indicate if this item is added/updated/deleted since last visit.
    And when all these object is returned to your client, the table model will iterate through the list and based on object index in the list and and if object is changed will update only that perticular row.
    Hope this is what you want to achieve.
    Regards

  • How to save data from JTable multiple rows and columns

    Hi Y_Not thanks for your help before...
    But what should I do if I want to get/save many data from many column and rows??

    i don't quite understand your (repeated) question. what is the problem with "multiple rows and columns". Y_NOT and i have shown you ways to access them.
    all you need are 2 loops: one around your number of rows and one around the number of columns or vice versa depending in which order you want to save things:
    for (int col = 0; col < data.size(); col++) {
        for (int row = 0 ; row < data[col].size(); row++) {
            // save your data
            saveData(data[col].getElementAt(row));
            // or use yourtable.getValueAt(row, col);
    }this is not a problem of Swing/Java but of simple algorithm...
    thomas

  • JTable column movement and scroll bar

    Hello:
    I have a JTable with about 30-40 columns. Sometimes I would like to drag the column from rightmost to closer to the left end. I am not able to do that in one shot. and instead have to do it in multiple steps. Is there a way for the scroll bar to sort of move alongside the column as I drag it along?

    i dont know if there is way off hand. But you can put your own mouseListener of the JScrollPane and i am sure there is some method to check if you are dragging the JTable and if you are move the JScrollBar in the direction.
    I think that you are going to have to make you own implementation of this.
    David

  • Using PL/SQL to retrieve column names and column values

    If I have a table as follows
    Table A(
    meal varchar2(32),
    beverage varchar2(32),
    desert varchar2(32));
    and the table contains a row
    meal beverage desert
    pork chops iced tea apple crisp
    Is there a way in pl/sql to retrieve the column names along with the values. I have an object type
    DATA_DEFINITION_T AS OBJECT (
              "FIELD_NAME"          VARCHAR2(32),
              "FIELD_VALUE" VARCHAR2(32)
    I need to store the column name in field_name and the column value in field_value.
    So the result would be:
    FIELD_NAME = meal
    FIELD_VALUE = pork_chops
    FIELD_NAME = beverage
    FIELD_VALUE = iced tea
    FIELD_NAME = desert
    FIELD_VALUE = apple crisp
    Thanks in advance.

    Hi,
    try this procedure ....just create it and give the table name..the object M_DATA_TAB has the required data
    procedure l_fill_data_dict(p_table_name varchar2) is
    connection_id EXEC_SQL.CONNTYPE;
    bIsConnected BOOLEAN;
    cursorID EXEC_SQL.CURSTYPE;
    nIgn PLS_INTEGER;
    m_val VARCHAR2(40);
    m_col_name varchar2(40);
    m_col_val varchar2(240);
    m_cnt number;
    m_id number := 0;
    m_incr number := 0;
    p_sqlstr varchar2(4000);
    p_sql_cnt varchar2(4000) ;
    p_org_sql varchar2(4000);
    TYPE DATA_DEFINITION_TABS IS RECORD (
    FIELD_NAME VARCHAR2(32),
    FIELD_VALUE VARCHAR2(240));
    TYPE DATA_DEFINITION_TAB IS TABLE OF DATA_DEFINITION_TABS;
    M_DATA_TAB DATA_DEFINITION_TAB := DATA_DEFINITION_TAB();
    --m_file text_io.file_type;
    Begin
    --     m_file := text_io.fopen('c:\eg.txt','w');
         --Set default connection
    connection_id := EXEC_SQL.DEFAULT_CONNECTION;
    bIsConnected := EXEC_SQL.IS_CONNECTED;
    IF bIsConnected = FALSE THEN
         message('Connection Failed');
    RETURN;
    END IF;
    --Find the total no.of columns in the given table
    p_sql_cnt := 'Select COUNT(column_name) from user_tab_columns where table_name='''||p_table_name||''' order by column_id';
    cursorID := EXEC_SQL.OPEN_CURSOR;
    EXEC_SQL.PARSE(cursorID, p_sql_cnt, exec_sql.V7);
    EXEC_SQL.DEFINE_COLUMN(cursorID, 1, m_val,40);
    nIgn := EXEC_SQL.EXECUTE(cursorID);
    IF (EXEC_SQL.FETCH_ROWS(cursorID) > 0) THEN
         EXEC_SQL.COLUMN_VALUE(cursorID, 1, m_val);
    end if;
    EXEC_SQL.CLOSE_CURSOR(cursorID);
    --EXEC_SQL.CLOSE_CONNECTION;
    m_cnt := m_val;---column count
    ---get the column names from the user_Tab_columns and fetch the values from the given table for that column...
    For i in 1..m_cnt loop
         m_id := m_id+1;
    p_sqlstr := 'Select column_name from user_tab_columns where table_name='''||p_table_name||''' and column_id ='||m_id||' order by column_id';
    cursorID := EXEC_SQL.OPEN_CURSOR;
    EXEC_SQL.PARSE(cursorID, p_sqlstr, exec_sql.V7);
    EXEC_SQL.DEFINE_COLUMN(cursorID, 1, m_col_name,40);
    nIgn := EXEC_SQL.EXECUTE(cursorID);
    IF (EXEC_SQL.FETCH_ROWS(cursorID) > 0) THEN
         EXEC_SQL.COLUMN_VALUE(cursorID, 1, m_col_name);
    end if;
    EXEC_SQL.CLOSE_CURSOR(cursorID);
    --fetch the column value from the given table
         p_org_sql := 'select DISTINCT '||m_col_name||' from '||p_table_name;
         cursorID := EXEC_SQL.OPEN_CURSOR;
    EXEC_SQL.PARSE(cursorID, p_org_sql, exec_sql.V7);
    EXEC_SQL.DEFINE_COLUMN(cursorID, 1, m_col_val,240);
         nIgn := EXEC_SQL.EXECUTE(cursorID);
         Loop      
         nIgn := EXEC_SQL.FETCH_ROWS(cursorID);
              IF (nIgn > 0) THEN
                   EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 1, m_col_val);
    M_DATA_TAB.extend();
                   M_DATA_TAB(M_DATA_TAB.last).field_name := m_col_name;
                   M_DATA_TAB(M_DATA_TAB.last).FIELD_VALUE := m_col_val;
                   m_incr := m_incr+1;
                   -- text_io.put_line(m_file,m_col_name||'##'||m_col_val);
              else
                   exit;
              End if;
         End loop;--loop of records in the table for the given column
    EXEC_SQL.CLOSE_CURSOR(cursorID);
    End loop; ---loop of columns in the table
    --text_io.fclose(m_file);
    message('Total no. of items in the object='||m_incr);
    EXEC_SQL.CLOSE_CONNECTION;
    EXCEPTION
    When EXEC_SQL.Invalid_Connection then
         message('invalid connection');
         when EXEC_SQL.Package_Error     then
         message('pkg err');
         when EXEC_SQL.Invalid_Column_Number          then
         message('invalid col num defined');
         when others then
              MESSAGE(SQLERRM);
    End;
    Regards
    Dora
    Edited by: Dora on Sep 27, 2009 3:13 PM

  • How to input id data in jtable column 1 and load the detail in other column

    Dear all,
    I am new to java, I am writing a POS using Java. I want to scan goods barcode into column 1 of a jtable, then the program will load the product's name and price in
    column 2 and column 3 from database. And also I want to have another row available where the barcode is scanned in previous row, i.e. I can add multiple products. And then I need to write the good's barcode to database. Please suggest any related article or code example. Thanks.

    Peter-Hon wrote:
    Dear all,
    I am new to java, I am writing a POS using Java. I want to scan goods barcode into column 1 of a jtable, then the program will load the product's name and price in
    column 2 and column 3 from database. And also I want to have another row available where the barcode is scanned in previous row, i.e. I can add multiple products. And then I need to write the good's barcode to database. Please suggest any related article or code example. Thanks.Your scanner will probably be a keyboard wedge, so any input from it will be equivalent to typing on the keyboard. You may be able to set it up to send a character, or sequence of characters that you can interpret as "move focus to the input cell, and input the remainder of the input there", if you can't do that, then you will have to just deal with the fact that people will end up scanning the bar codes into the quantity field.

  • JTable blankspace between 2 columns for readability

    I want to have some 'blank space' between 2 columns for 'readability'.
    How can I do this?
    I can use an column without any data but maybe there are better sollutions?

    The gridspacing is ok, but at a specific point I need 'extra' space.
    i.e.: JTable with 10 columns
    want to split up in the middle, so I need extra space between column(4) and column(5)

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Move multiple columns in jtable

    I have multiple tab and each tab have a table with multiple columns. I move like this for example-
    col1 col2 col3 col4 col5 col6 col7 col8 col9
    after columns move
    col2 col1 col3 col5 col4 col6 col8 col7 col9
    I save table and get it, it works fine. But when i move columns like this-
    col4 col3 col5 col1 col6 col2 col7 col8 col9
    it never work as i save and get table. please tell what's wrong in below code.
    here are the codes-
    Table save code-
    try {
      Map<String, Map<String, Vector<Object>>> tableMap = new HashMap<String, Map<String, Vector<Object>>>();
      private static Map<String, Object> tables = new HashMap<String, Object>();
      Set<String> tabNames = tables.keySet();
      for (String tabName : tabNames) {
      JTable tab = (JTable) tables.get(tabName);
      Map<String, Vector<Object>> colNameValues = new HashMap<String, Vector<Object>>();
      Enumeration<TableColumn> tabCols = tab.getColumnModel()
      .getColumns();
      while (tabCols.hasMoreElements()) {
      Vector<Object> colums = new Vector<Object>();
      TableColumn col = tabCols.nextElement();
      int modelIndex = col.getModelIndex();
      int viewIndex = tab.convertColumnIndexToView(modelIndex);
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();
      if (isTableSelected) {
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      colums.add(visible); // pos 0 visible
      colums.add(field); // pos 1 field
      colums.add(width); // pos 2 width
      colums.add(modelIndex); // pos 3 model index
      colums.add(tab.convertColumnIndexToView(modelIndex)); // pos
      // 4
      // view
      // index
      colNameValues.put(field, colums);
      tableMap.put(tabName, colNameValues);
      if (dataStore.isColumnsSelected()) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> mapOld = personalizedDataStore
      .getInstructionTable();
      if (mapOld != null) {
      if (mapOld.size() > 0) {
      Set<String> oldTabNames = mapOld.keySet();
      for (String oldTabName : oldTabNames) {
      if (!tableMap.containsKey(oldTabName)) {
      tableMap.put(oldTabName,
      mapOld.get(oldTabName));
      dataStore.setInstructionTable(tableMap);
    code for get Table-
    private void applyPesonalizeSettings(String tabName, JTable tab) {
      if (!" ".equals(tabName)) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> oldTables = personalizedDataStore
      .getInstructionTable();
      for (int viewIndex = 0, count = tab.getRowCount(); viewIndex < count; viewIndex++) {
      if (oldTables != null) {
      Map<String, Vector<Object>> oldTabCols = oldTables
      .get(tabName);
      Enumeration<TableColumn> tableColumns = tab
      .getColumnModel().getColumns();
      while (tableColumns.hasMoreElements()) {
      TableColumn col = tableColumns.nextElement();
      String field = Utils.toString(col.getIdentifier());
      if (oldTabCols != null) {
      if (oldTabCols.containsKey(field)) {
      boolean vis = (Boolean) oldTabCols.get(field)
      .get(0);
      int prefWidth = (Integer) oldTabCols.get(field)
      .get(2);
      int modelInd = (Integer) oldTabCols.get(field)
      .get(3);
      int viewInd = (Integer) oldTabCols.get(field)
      .get(4);
      // setting visible
      if (!vis) {
      tab.getColumn(field).setMinWidth(0);
      tab.getColumn(field).setMaxWidth(0);
      tab.getColumn(field).setPreferredWidth(0);
      } else {
      // setting column width
      tab.getColumn(field).setPreferredWidth(
      prefWidth);
      // setting index
      if (modelInd != viewInd) {
      tab.moveColumn(
      tab.convertColumnIndexToView(modelInd),
      viewInd);
    here is the code for set table change property with popup-
    @Override
      protected void doOK() {
      Map<String, Vector<Object>> labelAndRow = new HashMap<String, Vector<Object>>();  //req 22
      for (int viewIndex = 0, count = super.getRowCount(); viewIndex < count; viewIndex++) {
      Vector<Object> row = super.getRow(viewIndex);
      boolean visible = (Boolean) row.get(0);
      String label = (String) row.get(1);
      String field = (String) row.get(2);
      labelAndRow.put(field,row); //req 22
      Integer modelIndex = (Integer) row.get(3);
      Integer width = (Integer) row.get(4);                              
      TableColumn col = jxtable.getColumn(field);
      if (visible) {
      if (width <= 0) {
      width = 75;
      if (width != col.getWidth()) {
      col.setMinWidth(15);
      col.setMaxWidth(1000);
      col.setPreferredWidth(width);
      } else {
      col.setMinWidth(0);
      col.setMaxWidth(0);
      col.setWidth(0);
      col.setPreferredWidth(0);
      col.setHeaderValue(label);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      super.dispose();
      for (TableColumn col : (List<TableColumn>) jxtable.getColumns()) {
      int modelIndex = col.getModelIndex();
      int viewIndex = jxtable.convertColumnIndexToView(modelIndex);
      String label = Utils.toString(col.getHeaderValue());
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();                       
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      dialog.getTableModel().addRow(new Object[]{visible, label, field, modelIndex, width});
      dialog.setVisible(true);

    I have multiple tab and each tab have a table with multiple columns. I move like this for example-
    col1 col2 col3 col4 col5 col6 col7 col8 col9
    after columns move
    col2 col1 col3 col5 col4 col6 col8 col7 col9
    I save table and get it, it works fine. But when i move columns like this-
    col4 col3 col5 col1 col6 col2 col7 col8 col9
    it never work as i save and get table. please tell what's wrong in below code.
    here are the codes-
    Table save code-
    try {
      Map<String, Map<String, Vector<Object>>> tableMap = new HashMap<String, Map<String, Vector<Object>>>();
      private static Map<String, Object> tables = new HashMap<String, Object>();
      Set<String> tabNames = tables.keySet();
      for (String tabName : tabNames) {
      JTable tab = (JTable) tables.get(tabName);
      Map<String, Vector<Object>> colNameValues = new HashMap<String, Vector<Object>>();
      Enumeration<TableColumn> tabCols = tab.getColumnModel()
      .getColumns();
      while (tabCols.hasMoreElements()) {
      Vector<Object> colums = new Vector<Object>();
      TableColumn col = tabCols.nextElement();
      int modelIndex = col.getModelIndex();
      int viewIndex = tab.convertColumnIndexToView(modelIndex);
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();
      if (isTableSelected) {
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      colums.add(visible); // pos 0 visible
      colums.add(field); // pos 1 field
      colums.add(width); // pos 2 width
      colums.add(modelIndex); // pos 3 model index
      colums.add(tab.convertColumnIndexToView(modelIndex)); // pos
      // 4
      // view
      // index
      colNameValues.put(field, colums);
      tableMap.put(tabName, colNameValues);
      if (dataStore.isColumnsSelected()) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> mapOld = personalizedDataStore
      .getInstructionTable();
      if (mapOld != null) {
      if (mapOld.size() > 0) {
      Set<String> oldTabNames = mapOld.keySet();
      for (String oldTabName : oldTabNames) {
      if (!tableMap.containsKey(oldTabName)) {
      tableMap.put(oldTabName,
      mapOld.get(oldTabName));
      dataStore.setInstructionTable(tableMap);
    code for get Table-
    private void applyPesonalizeSettings(String tabName, JTable tab) {
      if (!" ".equals(tabName)) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> oldTables = personalizedDataStore
      .getInstructionTable();
      for (int viewIndex = 0, count = tab.getRowCount(); viewIndex < count; viewIndex++) {
      if (oldTables != null) {
      Map<String, Vector<Object>> oldTabCols = oldTables
      .get(tabName);
      Enumeration<TableColumn> tableColumns = tab
      .getColumnModel().getColumns();
      while (tableColumns.hasMoreElements()) {
      TableColumn col = tableColumns.nextElement();
      String field = Utils.toString(col.getIdentifier());
      if (oldTabCols != null) {
      if (oldTabCols.containsKey(field)) {
      boolean vis = (Boolean) oldTabCols.get(field)
      .get(0);
      int prefWidth = (Integer) oldTabCols.get(field)
      .get(2);
      int modelInd = (Integer) oldTabCols.get(field)
      .get(3);
      int viewInd = (Integer) oldTabCols.get(field)
      .get(4);
      // setting visible
      if (!vis) {
      tab.getColumn(field).setMinWidth(0);
      tab.getColumn(field).setMaxWidth(0);
      tab.getColumn(field).setPreferredWidth(0);
      } else {
      // setting column width
      tab.getColumn(field).setPreferredWidth(
      prefWidth);
      // setting index
      if (modelInd != viewInd) {
      tab.moveColumn(
      tab.convertColumnIndexToView(modelInd),
      viewInd);
    here is the code for set table change property with popup-
    @Override
      protected void doOK() {
      Map<String, Vector<Object>> labelAndRow = new HashMap<String, Vector<Object>>();  //req 22
      for (int viewIndex = 0, count = super.getRowCount(); viewIndex < count; viewIndex++) {
      Vector<Object> row = super.getRow(viewIndex);
      boolean visible = (Boolean) row.get(0);
      String label = (String) row.get(1);
      String field = (String) row.get(2);
      labelAndRow.put(field,row); //req 22
      Integer modelIndex = (Integer) row.get(3);
      Integer width = (Integer) row.get(4);                              
      TableColumn col = jxtable.getColumn(field);
      if (visible) {
      if (width <= 0) {
      width = 75;
      if (width != col.getWidth()) {
      col.setMinWidth(15);
      col.setMaxWidth(1000);
      col.setPreferredWidth(width);
      } else {
      col.setMinWidth(0);
      col.setMaxWidth(0);
      col.setWidth(0);
      col.setPreferredWidth(0);
      col.setHeaderValue(label);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      super.dispose();
      for (TableColumn col : (List<TableColumn>) jxtable.getColumns()) {
      int modelIndex = col.getModelIndex();
      int viewIndex = jxtable.convertColumnIndexToView(modelIndex);
      String label = Utils.toString(col.getHeaderValue());
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();                       
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      dialog.getTableModel().addRow(new Object[]{visible, label, field, modelIndex, width});
      dialog.setVisible(true);

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

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

    an easy way would be to use setSize()

  • How can I save JTable column order and widths?

    Hello,
    I'm trying to find a way to save the current column order and widths in a JTable, so that the next time the same user runs the app I can use these same settings. Ideally I'd like to save this locally on the user's PC. I think it could probably be done with serialization, but hopefully there's a simple solution. Anyone else already tackled this?

    The JTableHeader class can give you all the information you through the various TableColumns.
    I simply save all this information to a properties file which looks somthing like this
    # Column Information
    total=3
    column0=Names,120
    column1=Dates,140
    column2=Status,110This can then be read back using a java.util..Properties object. With this information you'll need to manually set the properties of each TableColumn and use the column model to move the columns to the right position ie
    cmodel.moveColumn(0,2); // move column 0 to positon 2This requires a little bit more coding to properly do the comparism of the column names with those in the properties object.
    Tip: it is always easier to use the above format, ie column0, column1, column2, etc, so that you can easily use a loop to access the information form the properties object ie
    int total  = Integer.parseInt( prop.getProperty("total") );
    for(int i = 0; i < total; i++) {
       String cname = prop.getProperty("column" + i);
        /// the rest of the TableColumn formatting could go here
    }All the best.
    ICE

  • How to set the Selected row and Column in JTable

    Hi,
    i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
    Praveen K Saxena

    Is that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
    myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);

  • Updating the particular row and column in a JTable

    Hi,
    I have a JTable which is having fixed number of columns. When i am trying to update a particular cell in the table
    during programm execution i am not able to do it.
    I am getting the row number and column number correctly. But when i am going to set the data it is not setting at the same row. It is setting some other row according to the m_index (according to the sorting).
    i am doing :
    JTableModel model = (JTableModel) m_TablePan.getTableModel();
    model.setValueAt(savedData, row, column);

    See the convertXxxIndexToView and convertXxxIndexToModel methods.
    db
    Edited by: Darryl.Burke -- wrong methods suggested
    Edit2: Evidently lipumama doesn't follow up on many questions posted.
    One for the blacklist.

Maybe you are looking for

  • How can we retrieve the Group name from oid?

    Hi: In following request object, we can get all the user related information from oid except group name where a particular user belongs to. For instance user id, first name, last name and email etc but we could not get the group name. PortletRenderRe

  • Can I set up a corporate or business iTunes account?

    I see a few questions about Apple iTunes corporate accounts, but can't find a definitive answer. If I want to set up one iTunes account for my business to use on around 4 devices, how do I do this so it's not set up under my personal name? Does Apple

  • DBMS_XMLSave.insertXML

    Hi All, I am using DBMS_XMLSave.insertXML to read a XMl file and store it in a table. But the maximum record I am able to insert into the oracle table is limited around 80... I have tried using DBMS_XMLSave.setBatchSize but it is not helping me. let

  • No import from Canon Rebel XT camera to iPhoto

    iPhoto 6 fails to import from my Canon Rebel XT. Nothing happens. I've tried every suggestion I can find on the Apple and Canon sites, and I'm stymied. Canon's said to reinstall their Solution Disk, so I did that. Also needed a EOS Utility upgrade do

  • What version of Itunes is the best one for m4a encoding?

    What version of Itunes is the best one for m4a encoding?