2

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?

jilt3d
  • 3,864
  • 8
  • 34
  • 41

1 Answers1

7

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • +1 very good explanation, @jilt3d example for that http://stackoverflow.com/questions/7556380/sorting-jtable-causes-nullpointerexception/7557018#7557018 – mKorbel Sep 30 '11 at 16:34
  • Hmm, so the renderer is just... let say... a graphic? Which I need to allocate by the coordinates of my mouse pointer? Interesting to know that. Thank you for the explanation. – jilt3d Sep 30 '11 at 17:42
  • +1 Here's a related [Q&A](http://stackoverflow.com/questions/7137786/how-can-i-put-a-control-in-the-jtableheader-of-a-jtable). – trashgod Sep 30 '11 at 22:05