我創建了一個擴展JDialog的類,其中有一些複選框和3個按鈕:接受,取消和全選。單擊時更改JButton文本
當用戶點擊選擇全部時,每個複選框應該被檢查,如果再次點擊,每個複選框應該被取消選中。這工作正常,但我也希望在「全選」和「全部取消」之間切換按鈕的文本。我在那裏遇到麻煩,所以當用戶單擊按鈕並且文本更改爲「取消全選」時,該按鈕消失。
我有類減少到這裏最簡單的形式:
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;
}
}
我看不出有什麼不對。任何幫助?
哪裏是:只是改變了按鈕標籤時重繪組件你的代碼的其餘部分?你如何選擇/取消選擇複選框?你是否在其他地方操作'allButton'變量? – Marcelo 2012-02-23 12:03:10
我有一個複選框的偵聽器,但我刪除它使代碼更簡單。選擇/取消選擇工作正常,只有當我也嘗試更改按鈕文本時纔會出現問題。不,allButton不會在其他地方被操縱 – 2012-02-23 12:06:27