开发者

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.cel开发者_开发百科lBorder"));

        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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜