Search code examples
javaswingjframejcheckbox

Controlling JCheckBox from other JFrame


I am working on a Swing Application in which I need to uncheck or check the JCheckBox in a JFrame from another JFrame. I have tried multiple ways but was unable to do. Is that possible? My application is offline. Please help me with that. Thanks


Solution

  • This shouldn't be a problem. What have you done?

    Common problems include:

    • A tendency to subclass unnecessarily. The message seems to have got through for java.lang.Thread, but not GUIs for some reason.
    • Poor separation of concerns (go for models straight away).
    • Starting with the component and getting the model, rather starting with the model and constructing the component with that.

    Here's an example of how you might do it.

    import javax.swing.*;
    
    public class Example {
        public static void main(String[] args) { 
            java.awt.EventQueue.invokeLater(Example::go);
        }
        private static void go() {
            ButtonModel model = new JToggleButton.ToggleButtonModel();
            openFrame("Frame A", model);
            openFrame("Frame B", model);
        }
        private static void openFrame(String title, ButtonModel checkModel) {
            JFrame frame = new JFrame(title);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            JCheckBox checkBox = new JCheckBox("Tick me!");
            checkBox.setModel(checkModel);
            frame.add(checkBox);
            frame.pack();
            frame.setVisible(true);
        }
    }