简体   繁体   中英

How to add mouse listener to a component in a custom JTable header cell renderer

I implemented a custom header cell renderer which is used by a JTable instance.

private final class TableHeaderCellRenderer extends DefaultTableCellRenderer {
    private static final long serialVersionUID = 6288512805541476242L;

    public TableHeaderCellRenderer() {
        setHorizontalAlignment(CENTER);
        setHorizontalTextPosition(LEFT);
        setVerticalAlignment(BOTTOM);
        setOpaque(false);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        setIcon(getIcon(table, column));

        JPanel headerContainer = new JPanel();
        headerContainer.setLayout(new BorderLayout());
        headerContainer.setBorder(UIManager.getBorder("TableHeader.cellBorder"));

        Box buttonBox = Box.createHorizontalBox();

        JButton pinButton = new JButton();
        pinButton.setOpaque(false);
        pinButton.setMaximumSize(new Dimension(16, 16));
        pinButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JOptionPane.showMessageDialog(null, "ASD");
            }
        });

        buttonBox.add(pinButton);

        headerContainer.add(this, BorderLayout.CENTER);
        headerContainer.add(buttonBox, BorderLayout.EAST);

        return headerContainer;
    }
}

When I click "Pin Button" the message dialog doesn't appear instead only sorting occurs. Note that the respective JTable instance uses setAutoCreateRowSorter(true);. Can this be the cause why the button doesn't receive any mousePressed events?

Note that the respective JTable instance uses setAutoCreateRowSorter(true). Can this be the cause why the button doesn't receive any mousePressed events?

That is not the problem.

A renderer is NOT a real component. It is only a painting of a component so it can not receive events.

If you want to handle mouseEvents then you need to add the MouseListener to the table header. You then need to convert the mouse point to the appropriate table header column and then do your processing.

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