简体   繁体   中英

How to select with the mouse the JTable's column name

I created a query executor and used a JTable based on a resultSet to show the results. My Jtable implementation is like this:

        ResultSetMetaData metaData = rs.getMetaData();
        columnCount = metaData.getColumnCount();
        Vector<String> columnNames = new Vector<String>();

        for (int i = 1; i <= columnCount; i++) {
            columnNames.add(metaData.getColumnName(i));

        }

        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int i = 1; i <= columnCount; i++) {
                vector.add(rs.getObject(i));
            }
            data.add(vector);

        }
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        model.fireTableStructureChanged();

        tableSwing.setModel(model);

Everything is working fine except one thing. I cannot select or copy the column names. Can you recommend a me a solution ?

This has nothing to do with your code, it works perfectly fine. Your problem is that JTable does not have this functionality by default. You will need to implement a JTableHeader mouse listener, which detect when the user clicks on the table header.

An example:

JTableHeader header = table.getTableHeader();
header.setReorderingAllowed(false);
header.addMouseListener(new MouseAdapter() {  
    public void mouseClicked(MouseEvent e) {  
         int col = header.columnAtPoint(e.getPoint());  
         StringSelection selection = new StringSelection(table.getColumnName(col));
         Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
         clipboard.setContents(selection, selection);
       }  
   }); 

Note that this will not allow the user to select or copy the column name since Swing does not allow that (The column name is not rendered in a way that allows it).

What I did in my example is making the code copy the column name to clipboard automatically. Is not a perfect solution, but it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM