I have created a class which extends JDialog, where I have some checkboxes and 3 buttons: accept, cancel, and select all.
When user clicks select all, every checkbox should get checked, and if clicked again, every checkbox should get unchecked. That's working fine, but i also want the text of the button to change between "select all" and "unselect all". I'm having troubles there, so when user clicks the button and text changes to "unselect all", the button dissapears.
I have reduced the class to its simplest form here:
public class NodeSelectionCheckBoxJDialog extends JDialog {
public enum Options {ACEPT, CANCEL};
private Options selectedOption;
private JButton allButton;
private boolean allCheckBoxesSelected;
private JButton aceptButton;
public NodeSelectionCheckBoxJDialog(){
super(MainFrame.getInstance());
this.setTitle("Select nodes to apply");
this.setModal(true);
selectedOption = Options.CANCEL;
nodeCheckBoxesSet = new HashSet<NodeCheckBox>();
try {
initComponents();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void initComponents() throws Exception {
this.getContentPane().add(createActionButtons(), BorderLayout.SOUTH);
}
private Component createActionButtons() {
JPanel buttonsPanel = new JPanel();
allCheckBoxesSelected = false;
aceptButton = new JButton("Accept");
aceptButton.setEnabled(false);
buttonsPanel.add(aceptButton);
aceptButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedOption = Options.ACEPT;
dispose();
}
});
JButton cancelButton = new JButton("Cancel");
buttonsPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedOption = Options.CANCEL;
dispose();
}
});
allButton = new JButton("Select all");
buttonsPanel.add(allButton);
allButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(allCheckBoxesSelected){
allCheckBoxesSelected = false;
allButton.setText("Select all");
} else {
allCheckBoxesSelected = true;
allButton.setText("Unselect all");
}
}
});
return buttonsPanel;
}
}
I can't see what's wrong. Any help?
The button does not disappear, it just becomes too wide to fit in the window. Just redraw the component when changing the button label :
@Override
public void actionPerformed(ActionEvent e) {
if(allCheckBoxesSelected){
allCheckBoxesSelected = false;
allButton.setText("Select all");
} else {
allCheckBoxesSelected = true;
allButton.setText("Unselect all");
NodeSelectionCheckBoxJDialog.this.pack();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With