JTable - Toggle Columns with PopupMenu (like Windows Explorer)

跟風遠走 提交于 2019-12-06 10:04:10

问题


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:


回答1:


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:



来源:https://stackoverflow.com/questions/22417797/jtable-toggle-columns-with-popupmenu-like-windows-explorer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!