JTable - Column swap disabling for selected columns

Hi,
In my JTable i want to disable the swapping of selected columns, table.getTableHeader().setReorderingAllowed(false); this disables the whole table swapping.
Is there anyway to disable only selected column swapping?
Thanks in advance.
Yours,
Arun

I was able to disable the column swapping in all the ways, i.e. i've solved the problem that i've said in my previous post.
The following are the scenario'scovered, if the user wants to disable swapping of 1st and 2nd column of a JTable
1. Donot allow dragging of the 1st and 2nd column and
2. If the user drag-drop 3 or 4 th column in place of 1st or 2nd column, then undo the swap operation by re-swapping the columns.
Try the following example
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.MouseInputListener;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
public class FixedTableColumnsExample
    FixedTableColumnsExample()
        String[] columnNames = {"First","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)}
          JTable table = new JTable(data, columnNames);
        TableColumnModel columnModel = table.getColumnModel();
        EditableHeader test = new EditableHeader(columnModel);
        table.setTableHeader(test);  
        JFrame frame = new JFrame("Table Fixed Column Demo");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        JScrollPane scrollPane = new JScrollPane(table);
        frame.getContentPane().add( scrollPane );
        frame.setSize(400, 300);
        frame.setVisible(true);
    public static void main(String[] args)
        new FixedTableColumnsExample();
class EditableHeader extends JTableHeader
    public EditableHeader(TableColumnModel columnModel)
        super(columnModel);
    public void updateUI()
        setUI(new EditableHeaderUI());
class EditableHeaderUI extends BasicTableHeaderUI
    boolean is1and2Swapped  = true;
    protected MouseInputListener createMouseInputListener()
        return new MouseInputHandler((EditableHeader) header);
    class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler
        protected EditableHeader header;
         public MouseInputHandler(EditableHeader header)
             this.header = header;
         public void mouseDragged(MouseEvent e)
             int draggedColumnIndex = ((EditableHeader)e.getSource()).getDraggedColumn().getModelIndex();
             if(draggedColumnIndex != 0 && draggedColumnIndex != 1 )
                 super.mouseDragged(e);
                 is1and2Swapped = true;
             else
                 is1and2Swapped = false;
         public void mouseReleased(MouseEvent e)
             int draggedColumnIndex = ((EditableHeader)e.getSource()).getDraggedColumn().getModelIndex();
             Point p = e.getPoint();
             TableColumnModel columnModel = header.getColumnModel();
             if(p.x < 0)
                 p.x = 0;
             int index = columnModel.getColumnIndexAtX(p.x);
             super.mouseReleased(e);
             if((index == 0 || index == 1) && is1and2Swapped)
               header.getColumnModel().moveColumn(index,draggedColumnIndex);
}Is there anyother better way to do the swap disabling? If so please suggest me.
This solution is having one disadvantage.
Consider the following scenario,
a) 1 and 2 are fixed columns.
b) Move column 4 to 3rd position
c) Move new 3rd column to 1st or 2nd column's position
d) the new 3rd column is moving to position 4(its original position when the model was created) instead of position 3.
This is because the TableColumModel is not updated properly. I'm working on that. Any Suggestions?
Thanks
Arun.

Similar Messages

  • Jtable: set different icons for  selection/deselection

    Hai,
    I have designed a Jtable, I would like to set a column that has to show different icons when selected/deselected that row. To be specific when you click for the first time, it has to show ICON1 and if you click again it has to show ICON2. Any ideas ???
    Thanks,
    Bala.

    I haven't tried this - so take it with a grain of salt. In your table model, you can define the getColumnClass for the column as ImageIcon.class. In the getValue for that column, you would return the icon.
    In order to get the cell to act like a button .. so you can alternate between the icons ... is a little more complex. There is a book on Advanced Swing by Kim Topley that gets into making cells act like buttons. This part works because I have tried it -- but I wasn't displaying icons.
    good luck!

  • How to catch selected text in JTable Column

    Hi there,
    I am learning JTable. Need help for How to get the selected text from the JTable Column which is set to be editable.
    for example in JTextFiled you have method on getSelectedText(), is there any method for tracking the selected text.
    Thanks in advance
    Minal

    Here's an example of the model I used in my JTable. Not the "getValueAt" method & "getRecordAt" method. You will have to have a Record object - but it only contains the attributes of an inserted record (with appropriate getters & setters). Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • Custom JTable column (JCheckBox) not included in row selection.

    I am trying to use JCheckBox (for display only data) as one of my JTable columns. I have written custom cell renderer for the same. Every thing is working fine except that when I select a row, the new custom JCheckBox column is not included in selection. Here is the code that I am using.
        protected class CheckBoxColumnRenderer extends DefaultTableCellRenderer {
            JCheckBox ckb = new JCheckBox();
            public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                if (value instanceof Boolean) { // Boolean
                  ckb.setSelected(((Boolean) value));
                  ckb.setHorizontalAlignment(JLabel.CENTER);
                  ckb.setBackground(super.getBackground());
                  if (isSelected || hasFocus) {
                      ckb.setBackground(table.getSelectionBackground());
                return ckb;
        }How can I include the custom cell in the row selection.
    regards,
    nirvan.

    they have lots of dependencies and it is not always easy to strip out an SSCCE without a considerable effort.Exactly. And is the cause of the problem the dependencies or something else. The only way to know for sure is to strip out the code and simplify the problem, that way you truly understand what the problem is.
    The majority of time this can be done with minimal effort as in this case.
    Some times we are sure that the problem is with certain part of the code Is the problem the code or the way the code is invoked? How do we know the TableModel is created properly or that the column class is overwritten correctly when we can't see it?
    someone having a third look at it may actually find the enhancement required with ease.Exactly, but we need to see the big picture.
    So are you sure that I should post an SSCCE with every possible question where coding is involved ?In the majority of cases a SSCCE is easily created in 5-10 minutes, so if you want the fastest help then yes.
    Just twice this past week I was ready to ask a question on the forum and was preparing a SSCCE to post and sure enough both times the creation of the SSCCE caused me to look at the problem differently and I solved it. I would much rather solve a problem on my own then post a question and wait for hours (days) hoping someone else knows the answer.

  • How To Search For a Text In JTable Column?

    hi there
    i want to search for specific text in a JTable Column
    And If The Text Exists Highlits it?
    any ideas or useful links or tutorials?

    Well, then that would be a Swing related question. Did you search the Swing forum to see how rendering works.

  • What method should be used for resizing the particular JTable Column width

    I have a four table. Only one table which are on top have a table header. I want that when user resize the topmost table with a mouse other table colume also be resized automatically. So I want to know that what method should be used for resizing the particular JTable Column width.
    Thanks
    Lalit

    maybe you can implement a interface ComponentListener as well as ComponentAdapter with your topmost Table.
    for example:
    toptable.addComponentListener(
    new ComponentAdapter(){
    public void componentResized(ComponentEvent e){
    table1.setSize(....);
    table2.setSize(....);
    /*Optionally, you must also call function revalidate
    anywhere;*/
    );

  • Column Header for Select AS kind of query

    Hi,
    I wish to write a csv file by using the odisqlunload function. I have wrote the funtion as :
    OdiSqlUnload "-FILE=#FILE_PATH/#FILE_NAME" "-DRIVER=<%=odiRef.getInfo("SRC_JAVA_DRIVER")%>" "-URL=<%=odiRef.getInfo("SRC_JAVA_URL")%>" "-USER=<%=odiRef.getInfo("SRC_USER_NAME")%>" "-PASS=<%=odiRef.getInfo("SRC_ENCODED_PASS")%>" "-FILE_FORMAT=VARIABLE" "-FIELD_SEP=," "-ROW_SEP=\r\n" "-DATE_FORMAT=yyyy/MM/dd HH:mm:ss" "-CHARSET_ENCODING=ISO8859_1" "-XML_CHARSET_ENCODING=ISO-8859-1" "-FETCH_SIZE=1000" "-QUERY=SELECT RPAD(CI_FT_GL.GL_ACCT, 31, ' '),LPAD(CASE WHEN CI_FT.CURRENCY_CD != CI_FT_GL_EXT.DIVISION_CURCY_CD THEN sum(CI_FT_GL_EXT.DIVISION_AMT) ELSE sum(CI_FT_GL.AMOUNT) END,17,' '),' ',RPAD(CI_DST_CD_CHAR.CHAR_VAL, 25, ' '),RPAD(CI_DST_CD_CHAR.DST_ID, 8, ' '),'RMB ',' ',RPAD(to_char(sysdate, 'YYYYMMDD'), 8, ' ') FROM CI_DST_CD_CHAR CI_DST_CD_CHAR,CI_FT CI_FT,CI_FT_GL CI_FT_GL,CI_FT_GL_EXT CI_FT_GL_EXT where (CI_FT.FT_ID = CI_FT_GL.FT_ID) AND (CI_FT_GL.FT_ID = CI_FT_GL_EXT.FT_ID(+)) AND CI_FT_GL.GL_SEQ_NBR = CI_FT_GL_EXT.GL_SEQ_NBR(+) AND (CI_FT_GL.DST_ID = CI_DST_CD_CHAR.DST_ID) AND (CI_DST_CD_CHAR.CHAR_TYPE_CD = 'DTLREF1') AND (trim(CI_FT_GL.GL_ACCT) is not null) AND (CI_FT.XFER_TO_GL_DT is null) AND (CI_FT.GL_DISTRIB_STATUS in ('G','M')) AND (trunc(CI_FT.SCHED_DISTRIB_DT) <= trunc(sysdate)) AND CI_FT.CIS_DIVISION = '#DIVISION' GROUP BY CI_FT_GL.GL_ACCT,CI_DST_CD_CHAR.CHAR_VAL,CI_DST_CD_CHAR.DST_ID,CI_FT.CURRENCY_CD,CI_FT_GL_EXT.DIVISION_CURCY_CD"
    Then i used a jython code to generate headers. Bcoz the OdiSqlUnload does not generate headers. But the jython code is not useful when we have sql statements lik 'Select AS' :
    SELECT RPAD(CI_FT_GL.GL_ACCT, 31, ' ') AS GL_ACCT,
    LPAD(CASE WHEN CI_FT.CURRENCY_CD != CI_FT_GL_EXT.DIVISION_CURCY_CD THEN sum(CI_FT_GL_EXT.DIVISION_AMT) ELSE sum(CI_FT_GL.AMOUNT) END,17,' ') AS GL_AMOUNT,
    My Jython code is:
    import string
    import java.sql as sql
    import java.lang as lang
    import re
    sourceConnection = odiRef.getJDBCConnection("SRC")
    output_write=open('d:/Bijal/output1.csv','r+')
    myStmt = sourceConnection.createStatement()
    my_query = "SELECT RPAD(CI_FT_GL.GL_ACCT, 31, ' ') AS GL_ACCT,
    LPAD(CASE WHEN CI_FT.CURRENCY_CD != CI_FT_GL_EXT.DIVISION_CURCY_CD THEN sum(CI_FT_GL_EXT.DIVISION_AMT) ELSE sum(CI_FT_GL.AMOUNT) END,17,' ') AS GL_AMOUNT,
    ' ' AS BLANK1,
    RPAD(CI_DST_CD_CHAR.CHAR_VAL, 25, ' ')AS DESCR,
    RPAD(CI_DST_CD_CHAR.DST_ID, 8, ' ')AS DST_ID,
    'RMB ' Currency_Cd,
    ' ' AS BLANK2,
    RPAD(to_char(sysdate, 'YYYYMMDD'), 8, ' ') AS DT_OF_TXN
    FROM CI_DST_CD_CHAR CI_DST_CD_CHAR,CI_FT CI_FT,CI_FT_GL CI_FT_GL,CI_FT_GL_EXT CI_FT_GL_EXT
    where (CI_FT.FT_ID = CI_FT_GL.FT_ID) AND (CI_FT_GL.FT_ID = CI_FT_GL_EXT.FT_ID(+)) AND
    CI_FT_GL.GL_SEQ_NBR = CI_FT_GL_EXT.GL_SEQ_NBR(+) AND (CI_FT_GL.DST_ID = CI_DST_CD_CHAR.DST_ID)
    AND (CI_DST_CD_CHAR.CHAR_TYPE_CD = 'DTLREF1') AND (trim(CI_FT_GL.GL_ACCT) is not null)
    AND (CI_FT.XFER_TO_GL_DT is null) AND (CI_FT.GL_DISTRIB_STATUS in ('G','M')) AND
    (trunc(CI_FT.SCHED_DISTRIB_DT) <= trunc(sysdate)) AND CI_FT.CIS_DIVISION = 'MF'
    GROUP BY CI_FT_GL.GL_ACCT,
    CI_DST_CD_CHAR.CHAR_VAL,
    CI_DST_CD_CHAR.DST_ID,
    CI_FT.CURRENCY_CD,
    CI_FT_GL_EXT.DIVISION_CURCY_CD"
    my_query=my_query.upper()
    if string.find(my_query, '*') > 0:
    myRs = myStmt.executeQuery(my_query)
    md=myRs.getMetaData()
    collect=[]
    i=1
    while (i <= md.getColumnCount()):
    collect.append(md.getColumnName(i))
    i += 1
    header=','.join(map(string.strip, collect))
    elif string.find(my_query,'||') > 0:
    header = my_query[7:string.find(my_query, 'FROM')].replace("||','||",',')
    else:
    header = my_query[7:string.find(my_query, 'FROM')]
    print header
    old=output_write.read()
    output_write.seek(0)
    output_write.write (header+'\n'+old)
    sourceConnection.close()
    output_write.close()
    But it does not populate for Select As statements and throws error lik:
    'mismatched character \'\\n\' expecting \'"\'', ('<string>', 8, 62, 'my_query = "SELECT RPAD(CI_FT_GL.GL_ACCT, 31, \' \') AS GL_ACCT,\n'))
    Plz help me get headers in my output file :)

    Solution1:
    Still you can achieve this by using sys_connect_by_path ( if you know the use of it) to generate header. below link can help with another approach.
    http://www.business-intelligence-quotient.com/?p=546
    Solution2:
    You need to create one file (header= true )with interface as suggested by sutirtha. Then you can copy (odifilecopy) this file to another directory with dynamic name (inside variable) and dynamic path. In this interface keep the truncate option to true so that everytime data wont be appended to the end of file. After reversing the file change the column name Manually from C1 to your ACTUAL_COL_NAME in file. Because ODI always generate the column names using C1,C2,C3 ....
    The only risk in second approach is that if someone will delete the file then you will get error. For this you need to create a temp table in ODI with all column-name (header in file). then using above jython code or sys_connect_by_path (select * from temp_table), you can generate the header easily. Now this file will be generated dynamically and can be used by the interface. So even if someone will delete the file you can generate it during run time.
    Thanks.

  • How get values of columns for selected rows in SortingTable

    Hi,
    is possible to get values of more columns for selected rows? I have SortingTable that have 1st column loaded from list and 2nd and 3rd columns are text areas where user must write some text. I need way how to get values from all three columns for selected rows.
    My table looks like this:
    System name I User Account I  User Password
    system1 ...............jblack ............. passw1
    system2 ...............pdowe..............p@ssw
    system3 ...............ekie................. pas123
    Column System name is loaded from list, columns User Account and User Password are Text class. How can I get values for all three columns in case that I select e.g. system1 or system1 & system2?
    I read [this post|http://forums.sun.com/thread.jspa?forumID=764&threadID=5220609] but there is described selection only for one column.
    Code of my SortingTable is following:
    <Field name='tblDalsiSystemy'>
                   <Display class='SortingTable'>
                       <Property name='align' value='center'/>
                       <Property name='sortEnable' value='false'/>
                       <Property name='selectEnable' value='true'/>
                       <Property name='pageSize' value='5'/>
                       <Property name='pageButtonAlign' value='center'/>
                       <Property name='columns'>
                           <List>
                               <String>System name</String>
                               <String>User Account</String>
                      <String>User Password</String>
                           </List>
                       </Property>
                   </Display>
                   <FieldLoop for='y' in='lstSystemList'>               
                     <Field name='SystemName'>
                         <Display class='SortingTable$Row'>
                             <Property name='key'>
                                 <ref>lstSystemList</ref>
                             </Property>
                         </Display>
                         <Display class='Label'>
                             <Property name='align' value='center'/>
                             <Property name='value'>
                                 <ref>y</ref>                            
                             </Property>
                         </Display>
                     </Field>
                     <Field name='UserAccount'>
                         <Display class='SortingTable$Row'>                        
                         </Display>
                         <Display class='Text'>
                             <Property name='size' value='10'/>
                             <Property name='value'>                            
                             </Property>
                         </Display>
                     </Field>
               <Field name='UserPassword'>
                         <Display class='SortingTable$Row'>                        
                         </Display>
                         <Display class='Text'>
                             <Property name='size' value='10'/>
                             <Property name='value'>                            
                             </Property>
                         </Display>
                     </Field>
                   </FieldLoop>              
               </Field>Getting value is performed by:
    <ref>tblDalsiSystemy.selected</ref>Any help?
    Thanks
    Petr

    Hi Ivan,
    thanks for your advice - it works.
    Here is my final code:
    <Field name='tblDalsiSystemy'>
                   <Display class='SortingTable'>
                       <Property name='align' value='center'/>
                       <Property name='sortEnable' value='false'/>
                       <Property name='selectEnable' value='true'/>
                       <Property name='pageSize' value='5'/>
                       <Property name='pageButtonAlign' value='center'/>
                       <Property name='columns'>
                           <List>
                               <String>System name</String>
                               <String>User Account</String>
                      <String>User Password</String>
                           </List>
                       </Property>
                   </Display>
                   <FieldLoop for='y' in='lstSystemList'>               
                     <Field name='SystemName'>
                         <Display class='SortingTable$Row'>
                             <Property name='key'>
                                 <ref>lstSystemList</ref>
                             </Property>
                         </Display>
                         <Display class='Label'>
                             <Property name='align' value='center'/>
                             <Property name='value'>
                                 <ref>y</ref>                            
                             </Property>
                         </Display>
                     </Field>
                     <Field name='Account[$(y)].login'>
                         <Display class='SortingTable$Row'/>
                         <Display class='Text'>
                             <Property name='size' value='10'/>
                             <Property name='value'>                           
                             </Property>
                         </Display>
                     </Field>
                     <Field name='Account[$(y)].passwd'>
                         <Display class='SortingTable$Row'/>
                         <Display class='Text'>
                             <Property name='size' value='10'/>
                             <Property name='value'>
                             </Property>
                         </Display>
                     </Field>
                   </FieldLoop>              
               </Field>Maybe it could be helpful for somebody another :-)
    Petr

  • Set background color to selected jtable columns cell

    I am clicking on jtables column.I want to select any column and that column (only selected cell of column)should get displayed with specific background color.
    plz help

    You can write your own tablemodel,
    i.e. use DefaultTableModel or implement AbstractTableModel.
    Good luck!

  • Putting a check box above column for selection in WD ALV

    Hi,
    Can anyone provide me a code snippet and help me how I can
    provide a check box above column for selection in WD ALV.
    Best Regards
    Sid

    Hi Sid,
    As far as I know we cannot put checkboxes directly above the Column headers.
    You can achieve this functionality in a round above method
    You can create a group of checkboxes above your ALV table with names of  columns to be selected beside each check box and proceed with your further processing.
    Also If you are just looking at which columns you need to select to be shown on the
    ALV output
    data: lr_standard_functions type ref to if_salv_wd_std_functions.
    lr_standard_functions ?= wd_this->r_table.
    lr_standard_functions->set_column_selection_allowed( ' ' ).
    Hope this is of some help.
    Regards,
    Ismail.
    Edited by: Ismail Basha on Jan 23, 2008 1:47 PM
    Edited by: Ismail Basha on Jan 24, 2008 3:23 AM

  • F2 key not working with custom JTable Column

    I have a custom JTable Column (which is a JPanel with a JTextfield and JButton). Everything works as expected, except when the user presses "F2" to start editing the custom column cell. When the user presses F2, the custom cell goes into editing mode, but I am unable to type anything in it.
    Below is the SSCCE.
    Steps to Reproduce problem:
    1) Run the Program
    2) Select any cell in first Column.
    3) Press "F2" and try to type into the cell. Can't type anything.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class TextButtonCellFrame extends javax.swing.JFrame {
        // Variables declaration - do not modify                    
        private JTextField inputText;
        private JScrollPane jScrollPane1;
        private JPanel testPanel;
        private JTable testTable;
        // End of variables declaration                  
        public TextButtonCellFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            testPanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            testTable = new JTable();
            inputText = new JTextField();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            testTable.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            testTable.setCellSelectionEnabled(true);
            testTable.setRowHeight(52);
            testTable.setSurrendersFocusOnKeystroke(true);
            testTable.getColumnModel().getColumn(0).setCellRenderer(new MyTableCellRenderer());
            testTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor(new JTextField()));
            testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
            jScrollPane1.setViewportView(testTable);
            testPanel.add(jScrollPane1);
            inputText.setPreferredSize(new Dimension(50, 20));
            testPanel.add(inputText);
            getContentPane().add(testPanel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-576)/2, (screenSize.height-417)/2, 576, 417);
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextButtonCellFrame().setVisible(true);
        public class MyTableCellRenderer extends JPanel implements TableCellRenderer {
            Point point;
            JButton button1 = new JButton("Test 1");
            JTextField txtField = new JTextField();
            public MyTableCellRenderer() {
                setLayout(new BorderLayout());
                this.add(button1, BorderLayout.EAST);
                this.add(txtField,BorderLayout.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
                if (isSelected) {
                    txtField.setBackground(testTable.getSelectionBackground());
                    txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                else {
                    txtField.setBackground(testTable.getBackground());
                    txtField.setBorder(null);
                return this;
        public class MyTableCellEditor extends DefaultCellEditor {
            JPanel panel = new JPanel();
            JButton button1 = new JButton ("Test 1");
            JTextField txtField;
            MyTableCellEditor(JTextField txtField) {
                super (txtField);
                this.txtField = txtField;
                panel.setLayout(new BorderLayout());
                panel.add(button1, BorderLayout.EAST);
                panel.add(txtField,BorderLayout.CENTER);
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == button1)
                    JOptionPane.showMessageDialog(null, "Action One Successful");
            public Component getTableCellEditorComponent(JTable table, Object value,
                                        boolean isSelected, int row, int column) {
                return panel;
           public boolean isCellEditable(final EventObject anEvent) {
              if (anEvent instanceof KeyEvent) {
                 final KeyEvent keyEvent = (KeyEvent) anEvent;
                 SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                       if (!Character.isIdentifierIgnorable(keyEvent.getKeyChar())) {
                          txtField.setText(txtField.getText() + keyEvent.getKeyChar());
                       txtField.setCaretPosition(txtField.getText().length());
                       txtField.requestFocusInWindow();
                return super.isCellEditable(anEvent);
    }The code for isCellEditable(final EventObject anEvent) which is needed to edit the cell using keyboard was provided by DarrylBurke here
    regards,
    nirvan.

    The F2 key when pressed generates an action event (either JTable generates it or some other component). I am not sure how to handle the action event in the isCellEditable() method. Also, F(X) range of keys other than F2 dump some junk character in the JTextfield when pressed. I am now stuck at this point and don't know how handle F(X) range of keys.
    regards,
    nirvan.

  • Setting the jTable column width

    Coming from VB6 to Java is hard for me. Syntax is so much different.
    Below is what I am doing to populate the jTable and the values are coming from MySQL. My problem is setting the column width but I am having difficult understanding how to do it. I looked on the website and downloaded some examples and clearly because I am new and I simply do not understand it. I was wonder if someone is willing to modify the codes below on how I should do it. Thanks
    private void populate_grid(){
    Vector dataVector = new Vector();
    Vector columnVector = new Vector();
    columnVector.add("ID#");
    columnVector.add("Account Description");
    columnVector.add("Contact");
    columnVector.add("State");
    while (myResult.next()) {
    Vector rowVector = new Vector();
    System.out.println(myResult.getString("acct_name"));
    rowVector.add(myResult.getString("cust_id"));
    rowVector.add(myResult.getString("acct_name"));
    rowVector.add(myResult.getString("main_contact"));
    rowVector.add(myResult.getString("main_state"));
    dataVector.add(rowVector);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(dataVector, columnVector));

        int rows = 3;
        int cols = 3;
        JTable table = new JTable(rows, cols);
        // Disable auto resizing
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // Set the first visible column to 100 pixels wide
        int vColIndex = 0;
        TableColumn col = table.getColumnModel().getColumn(vColIndex);
        int width = 100;
        col.setPreferredWidth(width);

  • Help with JTable column width

    Hi,
    I'm trying to resize my JTable columns with this code, but it's not working. What I am doing wrong?
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
    TableColumn tc = table.getColumnModel().getColumn(i);
    int width = (i == 0)? 10 : table.getWidth()/2 - 10; // three columns
    tc.setPreferredWidth(width);
    Thanks,
    Andr�

    Now my problem is that using either of these methods
    is they don't carry the user's selected column width
    through updates.It sounds like the change event your table model is firing is causing the entire table to be rebuilt. I would guess that you are firing fireTableStructureChanged() which would cause the entire table to be rebuilt (columns, cell values, etc.) Just fire a change event for the minimum necessary. If you can't identify what data in your table has changed (to fire cell or row change events), but the structure (columns) of the table hasn't changed, just fire fireTableDataChanged(). This will cause the cells to be redrawn with the new values, but shouldn't cause the columns to be rebuilt and resized.

  • Retrieving JTable column number when clicked

    Hello, I'm new in this forum but not so new to java.....but I'm really worried about an issue with an application made using Swing.
    Well , my problem is with JTables. It's about selecting a table cell in order to get the column index when selected. Ok I'm able to get the column index when the cells are simple cells, but the problem appears when the cell is a JComboBox....It's imposible to retrieve the column index. I was trying and trying but finally I couldn't see what the solution is......and I must get that problematic index....
    Please, I really need and advice.
    Thanks in advance for your help
    Best Regards
    Mariojulio Zaldivar

    Hello, I created a short example of my java class:
    * NewClass.java
    * Created on 26 de octubre de 2007, 0:03
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package pruebas;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    public class TableDemoApplet extends JApplet {
    JTable table;
    public TableDemoApplet() {
    createGUI(getContentPane());
    public void createGUI(Container contentPane) {
    Object[][] rowData = new String[][] { {"98-43", "AraAra! SL"},
    {"81-31", "Aragones Transports SA"},
    {"12-72", "Rocca SL"},
    {"99-10", "Rodriguez e Hijos SA"},
    {"00-65", "Rimbau Motors SL"} };
    table = new JTable(rowData, new String[] {"Part No", "Provider"});
    JComboBox companyComboBox = new JComboBox(new Object[] {"AraAra! SL", "Aragones Transports SA", "Rocca SL", "Rodriguez e Hijos SA", "Rimbau Motors SL"});
    companyComboBox.setEditable(true);
    //new S15WorkingBackspace(companyComboBox);
    // setup the ComboBoxCellEditor, DefaultCellEditor won't work!
    table.getColumnModel().getColumn(1).setCellEditor(new ComboBoxCellEditor(companyComboBox));
    table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setPreferredScrollableViewportSize(new Dimension(400, 100));
    addListener();
    JScrollPane scrollPane = new JScrollPane(table);
    contentPane.setLayout(new java.awt.FlowLayout());
    contentPane.add(scrollPane);
    contentPane.add(new JTextField("HALLO!"));
    public void addListener(){
    /*table.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
    int column = table.getSelectedColumn();
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    // get most recently selected column index
    int column = table.getSelectedColumn();
    System.err.println("numero de columna: " + column);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(3);
    TableDemoApplet demo = new TableDemoApplet();
    demo.createGUI(frame.getContentPane());
    frame.pack(); frame.setVisible(true);
    I'm showing there the wrong behavior of the JTable, I hope this help you to help me :)
    Thanks a lot for your time!!
    Greetings
    Mariojulio Zaldivar

  • How Can I set up a JTable columns?

    Dear All,
    How can I set up my JTable columns to have the amount the user specifies?
    for example when the user types in 50 in JTextField 1 I want the JTables columns to then set to 50.
    How can this be done?
    Thanks
    lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

    As you can see I have tried this, but no success.
    If I am doing something wrong please accept my apology, and address me in the right direction.
    Thanks
    Lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
         ((DefaultTableModel)perstab.getModel()).setColumnCount(Integer.parseInt(name.getText()));
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

Maybe you are looking for