Given a JTable
with a column of type Boolean.class
, the default renderer is a JCheckBox
. It's easy enough to select individual cells based on a user selection, but it may be convenient to select all or none of the check boxes, too. These recent examples mentioned using JCheckBox
in the table header, but the implementation was awkward and unappealing. If I don't need to sort the column, how can I put a well-behaved control in the JTableHeader
?
Addendum: For convenience, I've added my sscce as an answer, but I'd be pleased to accept an answer that addresses the well-behaved aspect of the problem.
Use a custom TableCellRenderer:
Please note that components with popupmenu (e.g. JComboBox or JMenu) don't work well. See: JComboBox fails to expand in JTable TableHeader). But you can use a MenuButton in the TableHeader:
There are two parts of the problem (as I see it :-)
Usability: inventing UI-interaction/elements is prone to confusing users. In no particular order:
So even if interaction analysis comes out with a clear we-do-need/want-it,
Technical aspects
The article How to Use Tables: Using Custom Renderers offers
TableSorter
as an example of how to detect mouse events on a column header. Using a similar approach,SelectAllHeader extends JToggleButton
andimplements TableCellRenderer
in the example below to achieve a similar effect. ATableModelListener
is used to condition the toggle button when all the check boxes are in a uniform state.