gpt4 book ai didi

java - 限制 JTable 中的行选择

转载 作者:行者123 更新时间:2023-11-30 06:29:46 25 4
gpt4 key购买 nike

有没有一种简单的方法可以限制 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;

最佳答案

针对您的情况

.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
}
}
}

关于java - 限制 JTable 中的行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11164130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com