JTable selection visible

Is it possible to set a table or list selection always visible ?
And if yes, How ? (of course)
Thanks

Not sure if this will help you but I had a similar issue when sorting a table. After the sort a tableChanged event is issued and the default JTable behavior is to clear the selection. As part of the tableChanged event processing I attempted to reset a selection by calling setRowSelectionInterval() but the selection never showed up.
What eventually worked was to schedule the row selection on the event thread via SwingUtilities.invokerLater() instead of issuing the call from the tableChanged method.

Similar Messages

  • Shortcut for "select visible pixels"?

    CS3 had a command when you right-clicked on a layer in the layermenu: "Select visible pixels", but it's gone in CS4. A Mac-user showed me how a command-click on a layer selected visible pixels, but it doesn't work with cntrl, alt or shift on my Win7/CS4-PC. There is neither any choice for this command on the select-menu. Does anybody have any suggestions?
    Einar Ryvarden, Norway

    Ah, many thanks, it was the "click on the layer-icon"-part the other explanations didn't mention.

  • Cross-JTable selection

    In a scenario where there are two JTable's in order to implement "locked (frozen) columns", one has to address the cross-JTable selection issue that occurs when both tables' "columnSelection" and "rowSelection" properties are enabled, and the user clicks & drags the mouse to select a range of cells across the two JTables.
    Has anyone ever done this?
    Mert

    Interesting question - I would try to register one mouseListener to both tables that makes sure the events are redispatched if the mouse exits the one and enters the other during a addSelection.Or you can try to patch the BasicTableUI.MouseHandler to go on with addSelection even after a mouseExited during a mouseDragged. Never tried it, though. (Always assuming that one there is one selectionListener that extends a selection in one table to the other)
    Greetings
    Jeanette

  • JTable selection and sorting

    hi,
    I have JTable with simple sorting method and i dont use the swing's example.
    I need to add a row in a sorted order and the row selection should remaim intact even after i sort and when i refresh the table the selection should not change.if anybody can help to solve this problem they are most welcome.
    thanks,
    SK

    You are on the right track. First get the rect of the row you want to make visible:Rectangle cellRect = aTable.getCellRect( row, 0, true );Then tell the table to scroll to that rect:aTable.scrollRectToVisible( cellRect );There used to be a bug if you tried to scroll to the last row. I haven't gotten around to seeing if it is fixed 1.4 yet. Here is the full method I use (that works around the bug), enjoy:/**
    * Make sure the passed row is visible in the table (in case it is in a
    * scroll view, and the view is currently viewing elsewhere)
    * @param aTable The table to work with
    * @param row The row number that should be visible
    public static void MakeRowVisible( JTable aTable, int row ) {
        Rectangle cellRect = aTable.getCellRect( row, 0, true );
        if( cellRect != null ) {
            // Have to tweak the height of the table so that if we are
            // scrolling to the bottom, it really shows the bottom (swing bug
            // I guess)
            aTable.setSize( aTable.getWidth(), Integer.MAX_VALUE );
            aTable.scrollRectToVisible( cellRect );

  • JTable: Selecting rows in columns independently

    Dear all,
    I have a JTable with two columns. I want the user to be able to select cells in columns independently. At present, the entire row gets marked as selected. Is it possible at all to, for instance, select row1 1 to 3 in column 1 and rows 4 to 5 in column 2? If so, where's the switch? Thanks a lot in advance!
    Cheers,
    Martin

    Are you trying to use a seperate table for each column.
    Thats not a good idear.
    Here is what you have to do.
    1. Create a sub class of JTable
    2. You will have to redefine how the selection is done so. You will need some sort of a collection to store the list of selected cells indexes
    2.1 Selecting a cell is simply adding the coordinations of the cell to the selection
    2.2 de selecting is just removing it from the collection.
    2.3 Here is what you have to override
         setColumnSelectionInterval()
         setColumnSelectionInterval()
         changeSelection()
         selectAll()
         getSelectedColumns()
         getSelectedColumn()
         getSelectedRows()
         getSelectedRow() You migh also need few new methods such as
         setCellSelected(int row, int column, boolean selected);
         boolean isCellSelected(int row, int column);
         clearSelection();
         int[][] getSelectedCells();You will have to implement the above in terms of your new data structure.
    3. Handle mouse events.
    Ex:- when user cicks on a cell if it is already selected it should be deselected (see 2.2)
    other wise current selected should be cleared and the clicked cell should be selected
    if your has pressed CTRL key while clicking the the cell should be selected without deselecting the old selection.
    ---you can use above using a MouseListener
    When the user hold down a button and move the mouse accross multiple cell those need to be selected.
    --- You will need a MouseMotionListener for this
    You might also need to allow selection using key bord. You can do that using a KeyListener
    4. Displaying the selection
    You have to make sure only the selected cells are high lighted on the table.
    You can do this using a simple trick.
    (Just override getCellEditor(int row, int column) and getCellRenderer(int row, int column) )
    Here is what you should do in getCellRenderer(int row, int column)
    public TableCellRenderer getCellRenderer(int row, int column)
      TableCellRenderer realRenderer = super.getCellRenderer(int row, int);
      return new WrapperRenderer(realRenderer,selectedCellsCollection.isCellSelected(row,column));
    static class WrapperRenderer implements TableCellRenderer{
        TableCellRenderer realRenderer;
        boolean selected;
        public WrapperRenderer(TableCellRenderer realRenderer, boolean selected){
           this.realRenderer = realRenderer;
           this.selected = selected;
        public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column){       
            return realRenderer.getTableCellRendererComponent(table,value,selected,hasFocus,row,column);
    }What the above code does is it simply created wrapper for the Renderer and when generating the rendering component it replaces the isSeleted flag with our on selected flag
    and the original renderer taken from the super class will do the rest.
    You will have to do the same with the TableCellEditor.
    By the way dont use above code as it is becouse the getCellRenderer method create a new instance of WrapperRenderer every time.
    If the table has 10000 cells above will create 10000 instances. So you should refine above code.
    5. Finnaly.
    Every time the selection is changes you should make the table rerender the respective cells in or der to make the changes visible.
    I'll leave that part for you to figure out.
    A Final word
    When implementing th above make sure that you do it in the java way of doing it.
    For the collection of selected cells write following classes
    TableCellSelectionModel  // and interface which define what it does
    DefaultTableCellSelectionModel //Your own implementation of above interface the table you create should use thisby default
    //To communicate the selection changes
    TableCellSelectionModelListener
    TableCellSelectionModelEventif you read the javadoc about similer classes in ListSelectionModel you will get an idear
    But dont make it as complex as ListSelectionModel try to keep the number of methods less than 5.
    If you want to make it completly genaric you will have to resolve some issues such as handling changes to the table model.
    Ex:- Rows and colums can be added and removed in the TableModle at the run time as a result the row and column indexes of some cells might change
    and the TableCellSelectionModel should be updated with those changes.
    Even though the todo list is quite long if you plan your implementation properly the code will not be that long.
    And more importantly you will learn lots more by trying to implementing this.
    Happy Coding :)

  • JTable selection problem with jdk1.5.0_05

    Today I tried the new jdk1.5.0_05 release and noticed with a JTable I can only select a single column and row with the mouse. With jdk1.5.0_05 I could select multiple cols and rows with the mouse. I looking at the listselectionmodel for the jtable i see it is set to mulitple. Is this a bug in the new java 1.5 release?

    Yeah, the .jar files are definitely there and the
    small class I just wrote is in the Classes directory.Yes, but you're calling javac.exe, not some jars. Did you check that javac.exe is there? Stupid question, yes, but I've seen it all...
    I changed the path in Control Panel -> System ->
    Advanced -> Environment Variables. I've also beendoing this is the command prompt:
    set
    CLASSPATH=%CLASSPATH%;C:\Java\jdk1.5.0\bin;C:\Java\Cla
    ssesNo need to add the /bin directory to the classpath, there are no classes in it...

  • Intermittent JTable Selection Problem

    Hi,
    Everyone once in a while, under NT with 1.4.x, I have problems selecting and highlighting row under JTable. It happens a good bit, but this does not happen all the time. When the table is buggy, it does not keep the row selected nor does it highlight the row. You may have the row selected on a mousedown, but once you release the mouse it's done.
    Since this is happening for a variety of JTable's I didn't bother to send Java code. Has anyone else encountered this sort of thing? Or does anyone know what I should be looking at?
    The intermittent part is what's killing me. It makes it hard to track down with any high degreee of confidence in the answers.
    thanks for any input or suggestions,
    Geoff

    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = new String[40][3];
        for (int r=0; r<40; r++) {
          data[r] = new String[3];
          for (int c = 0; c < 3; c++) data[r][c] = "R" + r + "-C" + c;
        content.add(new JScrollPane(new JTable(data,head)));
        setSize(400, 400);
        show();
      public static void main(String args[]) { new Test(); }
    }I've been clicking until my fingers bled. Can't see a problem.

  • JTable select row by double click, single click

    Hi all,
    I would like to double click on the row of the JTable and pop up a window for adding stuff, a single click for selecting the row and then in the menu bar I can choose to etither add, change or delete stuff. I try to use the ListSelectionModel but does not seems to distinguish between double or single click.
    Any idea, doc, samples?
    or I should not use ListselectionModel at all?
    thanks
    andrew

    Hi. I used an inner class. By using MouseAdapter u dont have to implement all methods in the interface..
    MouseListener mouseListener = new MouseAdapter()
    public void mouseClicked(MouseEvent e)
    if(SwingUtilities.isLeftMouseButton(e))// if left mouse button
    if (e.getClickCount() == 2) // if doubleclick
    //do something
    U also need to add mouselistener to the table:
    table.addMouseListener(mouseListener);
    As I said, this is how I did it.. There are probably alot of ways to solve this, as usual :). Hope it helps

  • Overriding Default JTable Selection Behavior

    I'm attempting to override the default selection behavior of a JTable. For clicking, I want the table to behave basically as if the ctrl key was being held down all the time. That works great.
    I want the behavior of dragging a selection to behave a certain way as well. If ctrl is not held down, then a drag should cancel the current selection and start a new one at the drag interval. This works fine too.
    However, if ctrl is held down during a drag, I want the dragged interval to be added to the selection instead of replacing it. This almost works. However, if I hold ctrl while dragging, it no longer let's me "undrag" the selection: once a cell is inside the dragged interval, it's selected, even if you drag back over it to deselect it.
    I understand why that's happening given my approach, but I'm looking for a way around it. Does anybody have any ideas about how to get a JTable to behave the way I want?
    Here's a compilable program that demonstrates what I'm doing:
    import javax.swing.*;
    import java.awt.event.*;
    public class TestTableSelection{
         boolean ctrlDown = false;
         JTable table;
         public TestTableSelection(){
              JFrame frame = new JFrame("Test Table Selection");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //give the table random data
              String [][] data = new String [10][5];
              String [] names = new String [5];
              for(int i = 0; i < 5; i++){
                   names[i] = "C: " + i;
                   for(int j = 0; j < 10; j++){
                        data[j] = "t: " + (int)(Math.random()*100);
              table = new JTable(data, names){
                   //override the default selection behavior
                   public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                        if(ctrlDown){
                             //ctrl + dragging should add the dragged interval to the selection
                             super.changeSelection(rowIndex, columnIndex, toggle, extend);     
                        else{
                             //clicking adds a row to the selection without clearing others
                             //dragging without holding ctrl clears the selection
                             //and starts a new selection at the dragged interval
                             super.changeSelection(rowIndex, columnIndex, !extend, extend);
              //keep track of when ctrl is held down
              table.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        ctrlDown = e.isControlDown();
                   public void keyReleased(KeyEvent e){
                        ctrlDown = e.isControlDown();
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(250, 250);
              frame.setVisible(true);
         public static void main(String[] args){
              new TestTableSelection();
    Let me know if any of that isn't clear.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    This change seemed to work for me
              table = new JTable(data, names){
                   int prevRow = -1;
                   //override the default selection behavior
                   public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                        if(ctrlDown){
                             //ctrl + dragging should add the dragged interval to the selection
                             if ( rowIndex != prevRow ) {
                                  prevRow = rowIndex;
                                  super.changeSelection(rowIndex, columnIndex, true, false);
                        else{
                             //clicking adds a row to the selection without clearing others
                             //dragging without holding ctrl clears the selection
                             //and starts a new selection at the dragged interval
                             super.changeSelection(rowIndex, columnIndex, !extend, extend);
              };

  • Jtable selection problems

    I'm trying the following code, but it doesn't work!
    the selection is not set to another row at all in my JTable.
    collectionsTableModel.collections.remove(collectionsTableModel.getCollection(num));
    setNewSelectionInsteadOf(num);
    collectionsTableModel.fireTableDataChanged();
    private void setNewSelectionInsteadOf(int num) {
    int newSelectedRow = num+1>collectionsTableModel.getRowCount() ? num-1: num;
    if (newSelectedRow>=0 && newSelectedRow < collectionsTableModel.getRowCount()) {
    collectionsTable.setRowSelectionInterval(newSelectedRow,newSelectedRow);
    }

    Actually the bug is just here:
    collectionsTable.setRowSelectionInterval(newSelectedRow,newSelectedRow);
    where collectionsTable is my JTable
    and newSelectedRow is an int that set the new selected row.
    it does not set the selected row at all...
    could this be because I do not fire the fireTableDataChanged in the right time?

  • JTable- Selection Color

    Hallo,
    I want to change my border Color of selected Cell. Because I don�t find any possibilty to change this Color.
    I create my Table with my own AbstractTableModel. Till now, I don�t have write my own TableCellRenderer.
    Can you help me?
    Stefan Gabel

    Till now, I don�t have write my own TableCellRenderer.Well, it seems that now you do...
    But watch out from a bug: the isSelected always returns false.
    So you have to do it this way:
            DefaultTableCellRenderer myColumnRenderer = new DefaultTableCellRenderer() {
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                    // Correct the selected value, since java has a bug here.
                    int[] iSelectedRows = table.getSelectedRows();
                    if (iSelectedRows != null) {
                        for(int i=0; i< iSelectedRows.length; i++) {
                            if (iSelectedRows[i] == row) {
                                isSelected = true;
                                break;
    ...This handles the rows, add a similar check for columns if you like cell-specific.
    Then just set the color if it is REALLY selected.

  • JTable select problem

    Hello,
    I have a great problem with my JTable. I have a JTable with few lines and two columns. The user can select one line and with the following statements
    int column = tblSearchResults.getSelectedColumn();
    int row = tblSearchResults.getSelectedRow();     
    Object value = tblSearchResults.getValueAt(row,column);
    I retrieve the value with which I display details of a second line in a new window (when the user presses a certain button). The problem is when I close this new window and want to select a new line the getSelectedColumn and the getSelectedRow returns always -1 which says that no line is marked although I have marked a line.
    Does anybody know what the problem can be? - it must concern the open and close of the detail window, because when I omit the code line which opens the detail window and only make System.out.println's with the getSelectedColumn and getSelectedRow it will always output the right line...
    thx
    pat

    Swing related questions should be posted in the Swing forum.
    You have not provided enough information to solve your problem. We don't know how you are invoking the dialog. Are you double clicking on a row, do you have a button the user clicks on to invoke processing?
    So for this, and future postings, you should learn how to create a simple demo program that shows your problem so we don't have to guess what you are doing.

  • Simple JTable / Select Row example?

    Hi - I'm having a really hard time wrapping my brain around JTables and their events. Can anybody give me just a real simple example of how to get the value of whatever cell (row, preferrably) by clicking on that cell / row?

    Hey there,
    im currently doing Jtables within a system i am coding too so thought i would help ya out!
    1. You can recognise if a row is selected within your table by using a possible two methods: example of how this can be implemented:
    //This method used for only one row at a time being selected
    int selectedRow = table.getSelectedRow(); (table being the name of your JTable obviously)
                        if (selectedRow == -1) {//When there is no selected row show error message
                             JOptionPane.showMessageDialog(null, "Must select an employee from the table", "Error Message",
                                                      JOptionPane.ERROR_MESSAGE);
                        else {
                        //DO SOMETHING                    }
                   }2. Or you could use the public int [ ] getSelectedRows() method of recognising selected JTable rows: example of how u might implement this, this returns an array of interger values when 1 or more rows are selected:
    int [ ] rowselected = table.getSelectedRows();
    //In order to go through each selected row and do something with it a loop is obviously needed like:
    for (int i = 0; i < rowselected.length; i++) {
                        String empName = (String)(table.getValueAt(rowselected,0));
                        System.out.println(empName);
    Hope this helps ;-)

  • JTable, select row on right mouse click

    Hi,
    If I right click on a jTable row in my application, the row I click on does not get selected.
    How can I modify the mouse listener attached to the jtable to deal with this?
    jtable.addMouseListener( { e->
    if (e.isPopupTrigger())
        swing.popupMenu(menuItems).show(e.getComponent(), e.getX(), e.getY());
    } as java.awt.event.MouseListener)Thanks!

    Problem solved!
    jtable.addMouseListener( { e->
    if (e.isPopupTrigger()){
        int row = jtable.rowAtPoint( e.getPoint() );
        jtable.changeSelection( row, 0, false, false );
        swing.popupMenu(menuItems).show(e.getComponent(), e.getX(), e.getY());
    } as java.awt.event.MouseListener)

  • Jtable - Set visible columns

    Hi,
    I'm trying to build an applet to edit mysql tables. I used a Jtable inside a JscrollPane but I would like to display only 3 or 4 columns at a time (I can have up to 40 !) and then let the user scrolls to the others with the horizontal scrollbar.
    My problem is that all the columns are always displayed (width reduced to fit) in the scrollpane. How can I reduce the number of visible columns ?
    Thanks,
    Olivier
    Edited by: user1721669 on 16 sept. 2012 11:06

    Random guess. Don't set any size (especially, preferredSize) on the JTable if it's within a JSCrollPane.
    For better help (anything less random), please post an SSCCE (http://sscce.org).
    Best regards,
    J.

Maybe you are looking for

  • Problem Submit Via Job in BADI

    Hello All I am using SUBMIT VIA JOB in BADI "work order update" and but no job is created....also sy-subrc is 0. Here is the code   call function 'JOB_OPEN'     exporting       jobname          = name     importing       jobcount         = number    

  • Nikon D90 footage: Can you edit natively in Final Cut?

    Just wondering if anyone has been using the new Nikon D90 to shoot video, and then importing the footage natively into FCP6. The camera's video-recording format, from what I have read, is 720p24, an .avi file, and a Motion JPEG codec. I see that in t

  • Build WAR with servlet in JAR not work

    I am building a WAR file and have a bunch of jars and one of the jars has 2 servlets. When I create new web component from deploytool, I add all the jars and no class files. I then get to a page where I can select servet,jsp, or no component. I selec

  • Drawing thick line

    Hi, For some graphical user interface, I was overriding PaintComponent() method with Graphics argument and then using drawLine() method of Graphics class of Java. It worked in the way I wanted. However, the lines drawLine() method draws are too thin.

  • CollectionEvent MOVE

    Ok, I am confused and need help. I have a Flex 3 application with a List component bound to an ArrayCollection. I have dragEnable, dragMoveEnable, etc set to true. When I drag an item and drop it (to reorder the items) i do NOT get a Collection event