我创建了一个扩展了JDialog的类,其中包含一些复选框和三个按钮:接受、取消和全选。当用户点击“全选”时,每个复选框都应该被选中;再次点击,则所有复选框都应该取消选中状态。这方面已经运行良好,但我还希望按钮的文本在“全选”和“取消全选”之间切换。我在这方面遇到了麻烦,所以当用户点击按钮并且文本更改为“取消全选”时,按钮会消失。
我已将该类简化为以下形式:
我已将该类简化为以下形式:
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;
}
}
我看不出有什么问题。需要帮忙吗?