Method for reset buttons?

In my program, I have 12 different toggle buttons that should 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 the method by passing parameters? I just started java recently and I never used parameter declarations that are not strings or ints, so I was not sure if there would be a way to do this using the toggle button.

+4
source share
3 answers

You can pass the button as a parameter to a new method and call your methods on this parameter

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

// ...

toggleButton(buttonOne);
toggleButton(buttonTwo);
...
+4
source

, :

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

If you want to reset all buttons in a panel or frame, you can use this method:

private void clearAllFields() {

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

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

Witch loops the entire component and checks to see if this matches the instance JButtonand reset to the default values.

It is good that you can use many components, considering that you want to reset also JTextFields or any components that you can 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);
            ....
        }
    }
}
+3
source

Source: https://habr.com/ru/post/1677690/


All Articles