我在JTable
内JScrollPane
(fillsViewportHeight
是true
)并且想要在表格外部开始拖动时从结尾启用行选择(如图所示) 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();
}
});
}
}
我该怎么做?
UPD:
JTable
的默认行为是选择从开始到当前的所有行,如果我开始选择低于最后一行。 我希望在我拖动鼠标时只选择鼠标下面的行(如图所示)。
答案 0 :(得分:3)
成分:
类似的东西:
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);