Domanda

How would I go about creating a JTable in Swing that allows the user to toggle columns with a simple dropdown meun, like in Windows Explorer folders? My table has 12 columns, and the screen cannot fit all the information on the screen at once. Since the user may not need to see many of these columns, this seems like the best option.

I assume it would use a JPopupMenu that appears when the user right-clicks the table header, with a JCheckBoxMenuItem for each column.

Here's a screenshot of Window's column toggler that I'm trying to replicate: enter image description here

È stato utile?

Soluzione

How would I go about creating a JTable in Swing that allows the user to toggle columns with a simple dropdown meun, like in Windows Explorer folders?

Maybe you can try JXTable (available in SwingX library) which extends from JTable and provides such feature. This code snipet does it all:

DefaultTableModel model = new DefaultTableModel(new Object[]{"Column # 1", "Column # 2", "Column # 3","Column # 4"}, 10);

JXTable table = new JXTable(model);
table.setColumnControlVisible(true); // this added with JXTable

Screenshot

Pay attention to the top-right corner button which is responsible to display the menu:

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top