Not selecting a row in a JTable

411 Views Asked by At

I have a JTable with a number of rows, each row made up of a number of JPanels. I want one of the rows in the JTable to be unselectable. I have used a:

panel.setFocusable(false);

on this particular row. However, when pressing the down arrow key on the table, the selection disappears when it gets to the unfocusable panel. Is there a quick way of skipping the selection all together on this row and just selecting the next row?

1

There are 1 best solutions below

3
On

You can achieve that with help of ListSelectionListener. Read more How to Write a List Selection Listener. Simple example:

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class TestFrame extends JFrame{
    private int notSelectable = 2;
    private JTable t1;

    public TestFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        init();
        pack();
        setVisible(true);
    }

    private void init() {
      t1 = new JTable(10,1);
      t1.getSelectionModel().addListSelectionListener(getListener());
      t1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      add(t1);
    }


    private ListSelectionListener getListener() {
        return new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if(t1.getSelectedRow() == notSelectable){
                    if(notSelectable+1 == t1.getRowCount()){
                        t1.getSelectionModel().setSelectionInterval(0, 0);
                    } else {
                        t1.getSelectionModel().setSelectionInterval(notSelectable+1, notSelectable+1);
                    }
                }
            }
        };
    }

    public static void main(String... strings) {
        new TestFrame();
    }

}