Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable row selection from the end

Happy New Year for everyone! :)

I have a JTable inside JScrollPane (fillsViewportHeight is true) and want to enable row selection from the end when drag starts outside the table (as shown on the pic) enter image description here

SSCCE:

public class SimpleTableDemo extends JPanel {

    public SimpleTableDemo() {
        super(new BorderLayout(0, 0));

        String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

        Object[][] data = { { "Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false) }, { "John", "Doe", "Rowing", new Integer(3), new Boolean(true) }, { "Sue", "Black", "Knitting", new Integer(2), new Boolean(false) }, { "Jane", "White", "Speed reading", new Integer(20), new Boolean(true) }, { "Joe", "Brown", "Pool", new Integer(10), new Boolean(false) } };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(table);

        add(scrollPane, BorderLayout.CENTER);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 400);

        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

How can I do that?

UPD:

The default behavior of JTable is to select all rows from start to current one, if I start selection lower the last row. I want to select only that rows which was under the mouse while I've dragged the mouse up (as I've shown in picture).

like image 667
SeniorJD Avatar asked Oct 21 '22 17:10

SeniorJD


1 Answers

Ingredients:

  • a mouseListener detecting the mousePressed "below" the last row
  • if so, set the anchor of the row selection model to the last row

Something like:

MouseListener l = new MouseAdapter() {

    @Override
    public void mousePressed(MouseEvent e) {
        Rectangle lastRow = table.getCellRect(table.getRowCount() - 1, 0, false);
        if (e.getY() < lastRow.y + lastRow.height) return;
        System.out.println(table);
        table.getSelectionModel().setAnchorSelectionIndex(table.getRowCount()-1);
    }

};
table.addMouseListener(l);
like image 61
kleopatra Avatar answered Oct 23 '22 11:10

kleopatra