从最后选择JTable行

时间:2014-01-02 11:46:00

标签: java swing jtable jscrollpane

祝大家新年快乐! :)

我在JTableJScrollPanefillsViewportHeighttrue)并且想要在表格外部开始拖动时从结尾启用行选择(如图所示) 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();
            }
        });
    }
}

我该怎么做?

UPD:

JTable默认行为是选择从开始到当前的所有行,如果我开始选择低于最后一行。 我希望在我拖动鼠标时只选择鼠标下面的行(如图所示)。

1 个答案:

答案 0 :(得分:3)

成分:

  • mouseListener检测mousePressed"下面"最后一行
  • 如果是,请将行选择模型的锚点设置为最后一行

类似的东西:

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);