问题描述
我试图更改JTable的选择行为,以便能够在不使用CTRL修饰符的情况下向选择中添加和删除行.方法:
I'm trying to change the Selection behaviour of a JTable to be able to add and remove rows to the selection without using the CTRL modifier. The method:
public void changeSelection(int rowIndex,
int columnIndex,
boolean toggle,
boolean extend)
似乎正是我要的东西,尤其是这种情况:
seems to be exactly what I'm looking for, in particular the case:
toggle: true, extend: false. If the specified cell is selected, deselect it. If it is not selected, select it.
是我的意思.问题是我无法使其正常工作.也许我缺少一些有关内部JTable工作方式的信息,但这是我的代码:
is what I mean to do. The problem is I can't make it work. Maybe I'm missing some info about internal JTable workings, but here's my code:
initComponents();
mainTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
mainTable.setRowSelectionAllowed(true);
mainTable.setSelectionModel(new DefaultListSelectionModel() {
@Override
public void addSelectionInterval(int index0, int index1) {
if (index0 == index1) {
for (int i = 0; i < mainTable.getColumnModel().getColumnCount(); i++) {
mainTable.changeSelection(index0, i, true, false);
}
}
}
});
这似乎无能为力.有人可以告诉我是什么问题吗?
this seems to be doing nothing. Can anybody tell me what is the problem please?
谢谢.
推荐答案
您可以创建自定义ListSelectionModel
.
简单的例子:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ToggleListSelectionModel extends DefaultListSelectionModel
{
@Override
public void setSelectionInterval(int index0, int index1)
{
// Select multiple lines
if (index0 != index1)
{
super.addSelectionInterval(index0, index1);
return;
}
// Toggle selection of a single line
if (super.isSelectedIndex(index0))
{
super.removeSelectionInterval(index0, index0);
}
else
{
super.addSelectionInterval(index0, index0);
}
}
private static void createAndShowGUI()
{
String[] numbers = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
final JList<String> list = new JList<String>( numbers );
list.setVisibleRowCount( numbers.length );
list.setSelectionModel(new ToggleListSelectionModel());
// list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JButton clear = new JButton("Clear");
clear.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
list.clearSelection();
}
});
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(list), BorderLayout.CENTER);
frame.add(clear, BorderLayout.PAGE_END);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
该示例用于JList,但是JTable也使用ListSelectionModel.
The example is for a JList, but a JTable also uses a ListSelectionModel.
这篇关于JTable的多选不带CTRL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!