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)
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).
Ingredients:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With