限制JTable中的行选择

时间:2012-06-22 21:06:34

标签: java swing jtable listselectionlistener

是否有一种简单的方法来限制JTable中行的总选择?我的意思是我想让用户使用shift和ctrl来选择最多X行。如果他再次点击一行,它将取消所有选择。排序当前的行为方式,但限制所选行的总量。

这是我当前的实现,我对如何以图形方式限制选择毫无头绪。

public class RoomsListView extends AbstractViewPanel {

public RoomsListView(DefaultController controller)
{
    this.controller = controller;
    initUI();
}

private void initUI() 
{
    tableT = new JTable(RoomsModel.getInstance());
    sorter = new TableRowSorter<RoomsModel>(RoomsModel.getInstance());
    tableT.setRowSorter(sorter);

    tableT.setPreferredScrollableViewportSize(new Dimension(CUSTOM_TABLE_WIDTH, CUSTOM_TABLE_HEIGHT));

    tableT.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            rowClickedPerformed(e);
        }
    });
}

private void rowClickedPerformed(MouseEvent e) 
{

}

public void modelPropertyChange(PropertyChangeEvent evt) 
{
}

public JTable getTable()
{
    return tableT;
}

private final int CUSTOM_TABLE_WIDTH = -1;
private final int CUSTOM_TABLE_HEIGHT = 150;

private JTable tableT;
private DefaultController controller;
private TableRowSorter<RoomsModel> sorter;

}

2 个答案:

答案 0 :(得分:3)

对于你的情况

.addMouseListener(new MouseAdapter() {
   public void mouseClicked(MouseEvent e) {
     int row = m_table.getSelectedRow();
     int col = m_table.getSelectedColumn();
  }
});

只需查看last - first < X

即可

或者像这样

SelectionListener listener = new SelectionListener(table);
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel()
    .addListSelectionListener(listener);

public class SelectionListener implements ListSelectionListener {
    JTable table;

    // It is necessary to keep the table since it is not possible
    // to determine the table from the event's source
    SelectionListener(JTable table) {
        this.table = table;
    }
    public void valueChanged(ListSelectionEvent e) {
        // If cell selection is enabled, both row and column change events are fired
        if (e.getSource() == table.getSelectionModel()
              && table.getRowSelectionAllowed()) {
            // Column selection changed
            int first = e.getFirstIndex();
            int last = e.getLastIndex();
        } else if (e.getSource() == table.getColumnModel().getSelectionModel()
               && table.getColumnSelectionAllowed() ){
            // Row selection changed
            int first = e.getFirstIndex();
            int last = e.getLastIndex();
        }

        if (e.getValueIsAdjusting()) {
            // The mouse button has not yet been released
        }
    }
}

答案 1 :(得分:1)

这可能有助于将行选择限制为一个选择

  

table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);