Question

Is there are a method to clear the value of a Swing component. For example if we take the JTextField every time I want it to be cleared I have to call - txtField.setText(""). I once made a utility method for these type of cases -

public static void clearFields(JComponent[] components) {
        for (int i = 0; i < components.length; i++) {
            JTextComponent jComponent = (JTextComponent) components[i];
            jComponent.setText("");
        }
    }

I want to know if a better way is available in the Swing API itself. Or whether there is a way to refresh all the values in a JPanel.

Was it helpful?

Solution

there are two ways

  1. nothing wrong with your way, but I'd suggest to test if (c instanceof JTextField) {, then you can to re_set (differen too) value for different JComponents (or their group of) in one loop

  2. put desired JComponents to the some type of array or map,

  3. notice remove (if is there) Document or DocumentListener from all JTextComponent before, thenafter value is re_seted, loop ended, then add requied listener back to JTextComponent, to avoid to firing recrusive events ...

OTHER TIPS

No, that's the correct way to do it and I don't see the downside of clearing them in this way.

The only alternate way I'm thinking about is just recreating the GUI by instantiating new UI components and relayout them but it seems overkill and it will also make you lose all the references to old ones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top