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);

Similar Messages

  • Can i move blob column one tablespace to another tablespace

    When I ruining the following script
    ALTER TABLE T_Transaction_Image
    MOVE LOB(RCSCOMPRESSED_IMAGE,CAMERA_PHOTO_1,CAMERA_PHOTO_2,NUMBER_PLATE)
    STORE AS TABLESPACE IMAGE
    I found error
    ORA-22853: invalid LOB storage option specification
    Here we have more than one column having BLOB data type .
    Question
    I want to know can i move multiple column in single alter table ?
    and how can i move blob column one tablespace to another tablespace
    Thanks in advance
    Edited by: abdul moyed on Feb 3, 2011 6:33 PM

    http://decipherinfosys.wordpress.com/2007/11/21/moving-lob-column-to-a-different-tablespace/
    Regards
    Asif Kabir

  • JTable - how to disable the drag / move  for column

    hi there, please give me a hand with this problem,
    i am trying to disable drag / move column in JTable.
    ie.
    ===============================================================
    JTable mainTable = new JTable();
    tableModel recordTable; //this extand AbstractTableModel
    this.mainTable.setModel(this.recordTable);
    ie.
    Product size quantity price
    Shoe 8 200 $120
    Shirt 9 100 $100
    Dress 12 50 $60
    the position of column Product,size,quantity,price, however, if i click on price and drag, i will be able to move the whole lot and place to different position ie. Product,price,size,quantity.
    =======================================================================
    please let me know how can i stop this happening....

    Try something like this:
    mainTable.getTableHeader().setReorderingAllowed(false);

  • JTable: Multiple Columns to Single Header

    Hi
    How is it possible to allocate multiple columns in a JTable to the one header.
    I retrieve a resultset from a DB. At present 'firstname' and 'lastname' go into separate columns with separate headers.('firstname' and 'lastname')
    I would like to either combine 'firstname' and 'lastname' then add to the table as one column, or, leave 'firstname' and 'lastname' as is and combine the headers of these columns.
    Not sure how to go about this...
    Any help would be appreciated,
    Thanks
    Gregg

    Look at http://www2.gol.com/users/tame/

  • Select single column but multiple rows in JTable

    Hi
    I have a jTable and want to be able to select multiple rows but only in a single column.
    I've set these properties which makes selection almost the way I would like it.
    table1.setCellSelectionEnabled(true);
    table1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);the only problem now is that the user can select multiple columns.
    Is there a simple way to restrict selection to single column?
    regards
    abq

    table.setCellSelectionEnabled(true);
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    DefaultListSelectionModel model =
         (DefaultListSelectionModel)table.getColumnModel().getSelectionModel();
    model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

  • Multiple column sorting in JTable

    There is way to release multiple column sorting in JTable.
    ADF/SWing, Jdev 10.1.3

    I do not know that there is, but it would be really nice!
    regards,
    mario udina

  • Multiple column  sorting on JTable data

    if any body can please send an example code how multiple column sorting can be done on table data.
    condition:- one column should sort in ascending order another column in descending order.
    am completly out of ideas it's urgent any help is greatly appritiated
    Thank's in advance
    sri

    I think the crosspost is because the OP was advised to post it in the Swing forum instead (it would've been nice to see the original post closed as well, though). Anyway...
    Have you got your table sorting using one column? If so, how have you achieved that (eg, are you using Java 6)?
    All you're after is a stable sorting algorithm so that any elements that are the same in the new sorting scheme stay in the same position relative to each other. Then you can just sort by "Column B" then "Column A" to achieve multiple column sorting. I believe that Collections.sort is stable and therefore any sorting approach based on that should be easily modifiable to do what you want.
    Hope this helps.

  • JTextAreaCellRenderer to wrap text in multiple columns... any better way?

    I would like to use a basic JTextArea cell renderer to wrap the text in a JTable cell, like in this thread
    http://forum.java.sun.com/thread.jspa?threadID=664671&messageID=3893724
    Although the technique works, a disadvantage is that it cannot be used "as is" for multiple columns due to the setRowHeight/revalidate issue. One suggested workaround was to keep track of the maximum row height, as described here:
    http://www.javaspecialists.co.za/archive/newsletter.do?issue=106
    Both seem a bit rough. Are there any other options or more efficient techniques for automatically wrapping text in a JTable cell?

    Hello, did you search online? there are many tutorials like this one: http://www.photoshopessentials.com/photoshop-text/text-effects/text-wrap/
    You simply create a path, substract the parts you do not need, then click with the text tool inside.
    Note that it is not a dynamic text wrap, you need to change it if you move the objects around.

  • Crystal Report multiple columns

    I'm having trouble with Crystal Report's multiple columns in the detail section.
    The details section, the multiple columns is checked then the printing direction is across - down. Since the form I am using is a pre-printed form, by estimation it can only allow at best 30 records in one page, that is 15 in the 1st half of the column and another 15 records on the next. For visual:
    Invoice No    Invoice Date        invoice total                                               Invoice No    Invoice Date        invoice total
    1                                                                                16
    2                                                                                17
    3                                                                                .
    .                                                                                28
    14                                                                                29
    15                                                                                30
    For some reason there is this giant space after the last set of rows before it prints out the page footer. This giant blank section disrupts the layout of the page footer section.
    Here are some info on the details section as configuration is involved:
    Format with  Multiple Columns - checked
    In Paging: New Page after 30 visible Records
    In Layout: Width: 3.5 in       Height: 0.0 in
                     Horizontal: 0.0 in      Vertical: 0.0 in     
    Printing Direction: Across-Down
    Anyone knows how to suppress it or have the page footer move upwards?
    P.S To see actual pre-printed form, please download this [http://www.mediafire.com/i/?csu0q75mjynys2k]
    Edited by: Khristine Angelei  Basilla on Mar 1, 2012 8:34 AM

    Now why didn't I try that out. Actually, initial plan was 2 subreports.
    So when I added the second subreport in the group footer section, it only prints the details on the last page, which should not be the case as I need to be printed on all pages.
    I'll test it out. I'll post an update soon.
    Thanks.

  • How do I create multiple columns with bullets in pages

    I'm trying to figure out how to create multiple columns within a document in which I bullet information...

    At the point you wish to change to two columns, Insert > Columns and then in the Layout Inspector, select the number of columns. After the insertion point, you will also need to insert another Column Change to return the following paragraphs to single column.
    Then Select the text to be bulleted and in the Text Inspector > List tab select the type of bullets.
    Note: This creates two columns that flow together. This can be tricky if you add any text later.
    If you wish to ensure alignment, create a two column text table and remove the lines with the Graphic Inspector > Lines > No Lines option and insert your text in each column and apply the bullets as above.
    This will create a text box - you then need to ensure it moves with the text by electing "Object Moves With Text" in the Wrpa Inspector.
    Message was edited by: bwfromspring hill

  • Moving columns in JTable

    hi all
    i'm having a slight problem after i've moved a column within my JTable, i need to reallocate the column index numbers. i'm using a sorter for the data, so when i move a column and select another column (or that one) it sorts a different column to the one selected based on the original (pre-move) indexes ( i do hope that makes some sense).
    i have a mouseDragged listener which works fine when moving a column, i just now need to add the index changes for all columns to it but i keep coming up with very very bad code that doesn't work.
    any suggestions would be most appreciated.
    thanks heaps...
    Takis

    i've actually been fiddling with those and that is actually where my problem lies.
    i use the following:
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    the sorter then works on "column".
    problem is, that when the column is moved, the viewColumn changes, but the column value remains the same. i've also tried sorting on the view column but then it gets even more confused.
    i just can't seem to figure it out...
    Takis

  • Multiple Column in JLIst

    Hi friend,
    Please could u tell me how can i make a multiple Column in a JList without using JTable. It would be better if u send me a complete code for that.
    Thanks u very much in Advance.
    Khaled Mahmud

    First of all I would like to thank u for reply.
    I have searched through the Forums but I could not get any solution.
    Actually, I have a code for Multi Column JList but that was made up using JTable.
    But I want a Multi Column JList which is made up without using JTable.

  • Multiple Icon on Jtable header

    Hi All:
    Any one had used multiple icons on JTable header ? According to the user's clicking positon under one column, one of these icons should change such as changing from sorting up arrows to sorting down arrows.
    I got the mouse clicking position on the header and column, then depend on the location, I wanted to perfrom different things. But I have not figured out if I should call header renderer to perform the repaint or not ? If I use JTable header render, how should I confine the one column that change should happen? I don't want to have all columns repainted. If I treat each column indivisually, should I reconstruct the JTable ? I used SortableTableModel to create the JTable.
    Any help is appreciated.
    Regards

    Here's the idea. I didn't test thisclass JComponentCellRenderer extends JButton implements TableCellRenderer {
        public JComponentCellRenderer (ImageIcon ii) { super("",ii); }
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            setText(value.toString());
            return this;
    }and thentblChanges.getColumnModel().getColumn(0).setHeaderRenderer(new JComponentCellRenderer(new ImageIcon( "CheckBoxHeaderImage" )));

  • Multiple selection in JTable

    Hi ,
    The problem is to select multiple rows and columns in the JTable like that of a excel application and have the focus on the first column of the last row. for example if select cells from ( 1,1 ) to ( 4,4), after selection the focus should be in cell (4,1). i have written a prgram( which is below) which uses listSelection to find out the cells which are selected. i found out the cells which are selected also. but i do not know how to get the focus on that cell. i have attached the code below also.. i want to know whether there is any method which set the focus to the particular cell. Can the problem above can be solved in any other way..or a simpler way..
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    class myTable {
    public static void main(String a[] ) {
              JFrame myframe = new JFrame();
              JTable jtable = new JTable(10,10);
              jtable.setCellSelectionEnabled(true);
         // add the listener to the table
    ListSelectionModel listSelectionModel;
         OSSTableSelectionHandler obj = new OSSTableSelectionHandler(jtable,10,10);
         listSelectionModel = jtable.getSelectionModel();
    listSelectionModel.addListSelectionListener(obj);
         myframe.getContentPane().add(jtable);
         myframe.show();
    } // end of public static void main
    } // end of class of myTable
    class OSSTableSelectionHandler implements ListSelectionListener {
                   JTable table;
         int row;
                   int col;
    OSSTableSelectionHandler(JTable tab, int r, int c ) {
         table = tab;
    row = r;
              col = c;
    public void valueChanged(ListSelectionEvent e) {
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                   int i = 0,j = 0;
    int firstIndex = e.getFirstIndex();
    int lastIndex = e.getLastIndex();
    boolean isAdjusting = e.getValueIsAdjusting();
    if (lsm.isSelectionEmpty()) {
    System.out.println(" Selection empty ");
    } else {
    // Find out which indexes are selected.
                        int maxrow = 0 ;
    int minIndex = lsm.getMinSelectionIndex();
    int maxIndex = lsm.getMaxSelectionIndex();
    for ( i = minIndex; i <= maxIndex; i++) {
    if (lsm.isSelectedIndex(i)) {
                                  if ( maxrow < i )
                                       maxrow = i;
                                  for (j = 0;j < col ;j++ )
                                       if ( table.isCellSelected(i,j) )
                                            System.out.println("The selected index is " + i + " " + j);
                             } // end of if                    
    } // end of for
                   // after this maxrow contains the last row that has beeb selected
                   // this for loop is to find out the first column in the maxrow that is selected
                   for (j = 0;j < col ;j ++ )
                        if ( table.isCellSelected(maxrow,j) )
                                  break;
                   // set the focus to the column ( maxrow, j )
    } // end of else
    } // end of fucn value changed
    } // end of class OSSTableSelectionHandler

    Whic cell is focused depends on where you begin your selection. The cell that you press your mouse first will be the focused one. Here is how I implement the mutiple selection functionality in a JTable as what MS Excel provides. This class is independent of my any other package. your table has to have column headers and a upper left JLabel corner(int the scroll pane containing the table) in order to make this class which I named TableSelectionAdapter function properly. You can revise and imporve it as you need, however.
    package petrochina.riped.gui.table.tableadapter;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.datatransfer.*;
    import java.util.*;
    * Enables multiple selection funtionality on <code>JTable</code>s.
    * @author Guanglin Du,SEC of Riped, PetroChina,
    * [email protected]
    * @version 1.0 2002/09/16
    public class TableSelectionAdapter extends MouseAdapter {
    private String newline = "\n";
    private boolean DEBUG = false;
    // private boolean DEBUG = true;
    private JTable myTable = null;
    private boolean shiftKeyDown = false;
    private boolean ctrlKeyDown = false;
    private int firstSelectedColIndex = -1;
    * Constructs with a <code>myTable</code> to simplify its reusability.
    * Guanglin Du, 2002/09/19
    * @param myTable     a <code>JTable</code>
    public TableSelectionAdapter(JTable myTable) {      
    this.myTable = myTable;
    initTableSelection();
    * The initTableSelection method: initializes the row/column/cell
    * selection functionality of the table.
    * Guanglin Du, 2002/09/19
    public void initTableSelection() {      
    getMyTable().setSelectionMode(
              ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
         //Cell selection
         myTable.addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
              myTable.setColumnSelectionAllowed(true);
              myTable.setRowSelectionAllowed(true);
         setMyKeyListener(); //shift/control key listener
         //column selection functionality
         JTableHeader myTableHeader = getMyTable().getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
         //enalbles select-all functionality
         setSelectAllFunction();
    * This setSelectAllFunction isto set the select-all functionality
    * when the upper left corner label of the JTable is clicked.
    * Note: JTable's parent JScrollPane has to be found.
    * Guanglin Du, 2002/09/19
    public void setSelectAllFunction() {      
    Container firstParent = getMyTable().getParent();
    if (firstParent instanceof JViewport) {
         Container secondParent = firstParent.getParent();
         if (secondParent instanceof JScrollPane) {
         JScrollPane myScrollPane = (JScrollPane)secondParent;
         JLabel myLabel =
              (JLabel)myScrollPane.getCorner(JScrollPane.UPPER_LEFT_CORNER );
         myLabel.addMouseListener(this);
    * Detects shift/control key state.
    * DGL, 2002/09/18
    public void setMyKeyListener() {
         getMyTable().addKeyListener(new KeyAdapter(){               
         //keyPressed
         public void keyPressed(KeyEvent e){
              //shift key state
              if(e.isShiftDown())     shiftKeyDown = true;                    
              //control key state
              if(e.isControlDown()) ctrlKeyDown = true;
    //keyReleased
         public void keyReleased(KeyEvent e){
              //shift key state
              if( !e.isShiftDown() ) shiftKeyDown = false;                    
              //control key state
              if( !e.isControlDown() ) ctrlKeyDown = false;
    * Adds the table header listener to enable single/multiple column selection.
    * DGL, 2002/09/17
    public void setTableHeaderListener() {
         JTableHeader myTableHeader = myTable.getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
    * Returns the <code>myTable</code> property value.
    * @return myTable the table that this class handles
    public JTable getMyTable() {
    return myTable;
    * Sets <code>myTable</code> property value of this class.
    * @param myTable the table that this class handles
    public void setJTable(JTable myTable) {
         this.myTable = myTable;
    * Returns the shiftKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getShiftKeyDown(){
         return shiftKeyDown;
    * Return the ctrlKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getCtrlKeyDown(){
         return ctrlKeyDown;
    * This inner class handles the column selection, the same
    * behavior as MS Excel.
    * Guanglin Du, 2002/09/18
    class TableHeaderListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {    
         stopLatestCellEditing(); //To save the data being edited
         if(DEBUG) System.out.print("mousePressed on ");
         JTableHeader myColumnHeader = (JTableHeader)e.getSource();
         Point myPoint = e.getPoint();
         int selectedColIndex = myColumnHeader.columnAtPoint(myPoint);
         if(DEBUG) System.out.print("the header of column "
              + selectedColIndex+newline);
         JTable table = myColumnHeader.getTable();
         //The following column selection methods work only if these
         //properties are set this way
         table.setColumnSelectionAllowed(true);
         table.setRowSelectionAllowed(false);
         int myRowCount = table.getRowCount();
         //makes this table focused, so that setMyKeyListener method can
         //listen for shift/control KeyEvent
         table.requestFocus();
    //     System.out.println("myRowCount = " + myRowCount);
         if( getShiftKeyDown() ){
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(firstSelectedColIndex > -1) {
              table.addColumnSelectionInterval(firstSelectedColIndex, selectedColIndex);
              firstSelectedColIndex = -1;//restore to -1
         } else if( getCtrlKeyDown() ) {
         table.addRowSelectionInterval(0,myRowCount-1);
         table.addColumnSelectionInterval(selectedColIndex,selectedColIndex);
         } else {
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(DEBUG) System.out.println("shiftKeyDown = " + shiftKeyDown
              +";"+" ctrlKeyDown = " + ctrlKeyDown);     
         //saves the first selected column index
         firstSelectedColIndex = selectedColIndex;
    * MouseAdapter implemenation.
    * mousePressed: sets the select-all functionality
    * when upper left corner label of the table is clicked
    * Guanglin Du, 2002/09/18
    public void mousePressed(MouseEvent e) {    
         if(DEBUG) System.out.println("Select all");
         stopLatestCellEditing();//To save the data in editing
         getMyTable().selectAll();
    * Triggers the latest <code>ActionEvent</code> in a table cell to save
    * the latest data. Or, the newly input data will not be stored into the table
    * model and cannot be retrieved.
    public void stopLatestCellEditing() {
    int editingRow = getMyTable().getEditingRow();
    int editingCol = getMyTable().getEditingColumn();
    if (editingRow != -1 && editingCol != -1){
         TableCellEditor cellEditor =
         getMyTable().getCellEditor(editingRow, editingCol);
         cellEditor.stopCellEditing();
    Here is how you can use it in your coding(where myTable is a JTable instance you create):
         /* Adds TableSelectionAdapter to enable all kinds of selection action. */
         TableSelectionAdapter tableSelect = new TableSelectionAdapter(myTable);     

  • Swap columns in JTable

    Hi, I�m having a huge problem in my JTable.
    I�ve got several columns in my Jtable and each cell has Double values. Some columns are editable and some aren�t.
    Some columns use values from anothers, i.e., they have formulas, and because of that when I change a value some other cells must have to recalculate their own values. This works fine when I don�t move the columns, but when I swap them the recalculation process doesn�t work very well.
    Questions
    1) Are the values in formulas pulled correctly (getValueAt)?
    2) Is the problem related with setValueAt method?
    3) Is this a bug?
    Note: I tried to use the convertColumnIndexToView, but this didn�t work.

    Sorry my mistake
    Let me give an example of what I�m doing to see if it's more easier:
    Suppose that I change a value in column index �SSProjectorUtils.POS� then the method above is called to refresh the cell in column index �SSProjectorUtils.TOT_MDS�.
    private void refreshTotMds(int row)
            if(!noFormula[row][SSProjectorUtils.TOT_MDS])  // if this cell has a formula
                SSProjectorTableModel model = (SSProjectorTableModel)dataTable.getModel(); // Getting table model
                double total = (Double.valueOf((String)model.getValueAt(row,
                                                                        SSProjectorUtils.CLR))).doubleValue()
                +
                    (Double.valueOf((String)model.getValueAt(row,
                                                             SSProjectorUtils.POS))).doubleValue();
                // Refreshing cell
                model.setValueAt(new Double(total),row,SSProjectorUtils.TOT_MDS);
        }indexes on the beginning:
    SSProjectorUtils.CLR = 5
    SSProjectorUtils.POS = 6
    SSProjectorUtils.TOT_MDS = 7
    If I move SSProjectorUtils.TOT_MDS forward for example index 9, the calculation is ok, but if I move to index 3 then the calculation is completely wrong another column is refreshed.
    Can this help you?
    Regards,
    Tiago

Maybe you are looking for

  • Printing to PDF using Acrobat X Pro - Cannot figure it out!

    I do not have the option to print to pdf and cannot figure out how to perform this function.  Following the user guides there should be an option under file > Print > advanced > print to pdf However under the advanced options i do not have the option

  • Lumia 620 usb disconnection problem

    Hi. Am facing a problem of usb disconnection while transferring data from my laptop. It's good for 1 or 2 minutes, after that am getting device not available on my laptop. Also I noticed the charging symbol on battery is blinking when connected to us

  • Save JTable's data

    hello, Can i save the JTable's data in binary and reload them? give me some suggestions please Now i save the JTable's data as txt format,but i want to save a password's MD5 result before them(its format is binary).i want to save them in one format,h

  • Everytime I start Itunes, I get the Welcome Screen and everything is reset

    Hi, everytime I start ITunes 64 bit on my Windows 7 64 bit PC, I get the Welcome Screen and all is reset. Seems to be ITunes can not store the settings after closing.

  • Power Plug for South Africa?

    I'm planning a trip to South Africa this summer and want to take my computer with me. I've heard of those conversion plugs that you can buy at Radio Shack and here are my questions: 1. Are those converters safe to use with my MBP? I've heard some sto