【问题标题】:JTable row selectionJTable 行选择
【发布时间】:2023-03-24 18:22:01
【问题描述】:

单击 JTable 上的行时,我需要选择一行。默认行为是当鼠标按下时,该行被选中。我怎样才能改变这种行为?我的期望是::

鼠标按下 --> 鼠标释放 ==> 选中

按下鼠标 --> 拖动鼠标 --> 松开鼠标 ==> 未选中

鼠标点击 ==> 选择行

我想在拖动鼠标时做其他事情,但不想更改该操作上的前一行选择。

【问题讨论】:

    标签: java swing jtable


    【解决方案1】:

    这是“stange”,但对我来说有效:

    table.setDragEnabled(true); 
    

    【讨论】:

    • 好主意,不会想到 :-) 发生的情况是 ui 安装了一个单独的侦听器和一些逻辑来触发“正常”的东西,比如选择只有在延迟之后它试图决定是否应该将印刷机视为拖动开始
    • hmm ...刚刚测试过:不会阻止按下时的选择(就像OP的目标一样)
    【解决方案2】:
    import java.awt.event.*;
    import javax.swing.*;
    
    /**
     *
     * @author Jigar
     */
    public class JTableDemo  extends MouseAdapter   {
    int selection;
    
    
        public static void main(String[] args) throws Exception
        {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            String[] headers = {"A", "B", "C"};
            Object[][] data = {{1, 2, 3}, {4, 5, 6}};
            JTable table = new JTable(data, headers);
            JScrollPane scroll = new JScrollPane();
            scroll.setViewportView(table);
            frame.add(scroll);
            frame.pack();
            frame.setVisible(true);
            table.addMouseListener(new JTableDemo());
            scroll.addMouseListener(new JTableDemo());
        }
    
        @Override
        public void mousePressed(MouseEvent e)
        {
            JTable jtable = (JTable) e.getSource();
            selection= jtable.getSelectedRow();
            jtable.clearSelection();
        }
        @Override
        public void mouseReleased(MouseEvent e){
            JTable jtable = (JTable) e.getSource();
            //now you need to select the row here check below link
        }
    
    
    
    }
    

    【讨论】:

      【解决方案3】:

      我发现这并不容易。我试图在其中突出显示行的表格不是当前活动的组件,因此您需要类似:

      // get the selection model
      ListSelectionModel tableSelectionModel = table.getSelectionModel();
      
      // set a selection interval (in this case the first row)
      tableSelectionModel.setSelectionInterval(0, 0);
      
      // update the selection model
      table.setSelectionModel(tableSelectionModel);
      
      // repaint the table
      table.repaint();
      

      【讨论】:

        猜你喜欢
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多