Problem
So my program takes in a .csv file and loads the data and displays it. When data is loaded in, it creates a new JCheckBox
for every column header there is in the data. How do I add an ActionListener
such that when the user ticks/unticks any of the boxes, it should do a certain function?
When data is loaded in, it updates the JPanel
by the code:
public void updateChecklistPanel(){ checklistPanel.removeAll(); checklistPanel.setLayout(new GridLayout(currentData.getColumnNames().length, 1, 10, 0)); for (String columnName : currentData.getColumnNames()){ JCheckBox checkBox = new JCheckBox(); checkBox.setText(columnName); checklistPanel.add(checkBox); } checklistPanel.revalidate(); checklistPanel.repaint(); }
I also have the following at the bottom:
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == newDataFrameItem){ newFile(); System.out.println("New DataFrame Loaded in"); } if (e.getSource() == loadDataFrameItem){ loadFile(); System.out.println(".csv Data loaded into DataFrame."); } if (e.getSource() == saveDataFrameItem){ System.out.println("Saved the data to a .csv file"); } }
What I'm trying to do is that when a checkbox is unticked, it should hide a column in the JTable
and when ticked, it should redisplay the column.
Current Solution
So far, I have the following working for me
checkBox.addActionListener(event -> { JCheckBox cb = (JCheckBox) event.getSource(); if (cb.isSelected()) { System.out.println(checkBox.getText() + " is now being displayed"); currentData.showColumn(checkBox.getText()); } else { System.out.println(checkBox.getText() + " is now being hidden"); currentData.hideColumn(checkBox.getText()); } updateTable(); });
As shown in the code, for each checkbox, I add an addActionListener such that when the checkbox is ticked, it will display the column and if is unticked, it will hide the column.
currentData is my model that handles all data and I've added 2 functions; hideColumn(String columnName) and showColumn(String columnName). So the model has an ArrayList of boolean values where each index value represents a column in the ArrayList of column names. When I want to show/hide a column, it sets the Boolean value to true/false. The tableModel is then changed such that it only adds the column to the tableModel if the columnName's boolean value is true or false.
I then run the updateTable() function to update the table with the new tableModel.
https://stackoverflow.com/questions/66841789/how-do-i-add-an-actionlistener-to-a-jcheckbox March 28, 2021 at 09:11PM
没有评论:
发表评论