我有一个带有多行的JTable,每行由许多JPanel组成。我希望JTable中的一行不可选。我用过:
panel.setFocusable(false);
在这一特定行上。但是,当按下表格上的向下箭头键时,选择在到达不可聚焦的面板时消失。有没有一种快速的方法可以在这一行中一起跳过选择并只选择下一行?
答案 0 :(得分:2)
您可以在ListSelectionListener
的帮助下实现这一目标。阅读更多How to Write a List Selection Listener。简单的例子:
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TestFrame extends JFrame{
private int notSelectable = 2;
private JTable t1;
public TestFrame(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
pack();
setVisible(true);
}
private void init() {
t1 = new JTable(10,1);
t1.getSelectionModel().addListSelectionListener(getListener());
t1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(t1);
}
private ListSelectionListener getListener() {
return new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(t1.getSelectedRow() == notSelectable){
if(notSelectable+1 == t1.getRowCount()){
t1.getSelectionModel().setSelectionInterval(0, 0);
} else {
t1.getSelectionModel().setSelectionInterval(notSelectable+1, notSelectable+1);
}
}
}
};
}
public static void main(String... strings) {
new TestFrame();
}
}