quinny
quinny

Reputation: 75

Method to Reset Buttons?

In my program, I have 12 different toggle buttons that will need to be reset at the same time. Instead of writing

buttonOne.setText("");
buttonOne.setSelected(false);
buttonOne.setEnabled(true);

over and over for 12 different toggle buttons, is there a way to do this in a method by passing parameters? I've only recently started java and i've never used parameter declarations that aren't strings or ints, so I was not sure if there would be a way to do it with a toggle button.

Upvotes: 4

Views: 1384

Answers (3)

drvdijk
drvdijk

Reputation: 5554

You could pass the button in as a parameter to a new method, and call your methods on that parameter

private void toggleButton(JToggleButton button) {
    button.setText("");
    button.setSelected(false);
    button.setEnabled(true);
}

// ...

toggleButton(buttonOne);
toggleButton(buttonTwo);
...

Upvotes: 4

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

If you want to reset all Buttons in your panel or fram you can use call this method:

private void clearAllFields() {

    for (Component C : myPanel.getComponents()) {

        if (C instanceof JButton) {
            ((JButton) C).setText("");
            ((JButton) C).setEnabled(true);
            ...
        }
    }
}

Witch will loop throw all the component and check if it is instance of JButton and reset to the default values.

The good thing in this way, that you can use many component consider you want to reset also JTextFields or any components you can just use :

private void clearAllFields() {

    for (Component C : myPanel.getComponents()) {
        if (C instanceof JButton || C instanceof JTextField) {
            ((JTextField) C).setText("");
            ...
        }

        if (C instanceof JButton) {
            ((JButton) C).setText("");
            ((JButton) C).setEnabled(true);
            ...
        }

        if (C instanceof JRadioButton) {
            ((JRadioButton) C).setSelected(false);
            ...
        }

        if (C instanceof JDateChooser) {
            ((JDateChooser) C).setDate(null);
            ....
        }
    }
}

Upvotes: 3

If You want to trigger all those buttons at once then you can put those buttons in a list and do:

for (JButton button : myListOfButtons) {
     button.setText("");
     button.setSelected(false);
     button.setEnabled(true);
}

Upvotes: 3

Related Questions