0

I have two classes:

public class Screen1 extends javax.swing.JFrame {
...
//disables JButton1 after it is clicked on
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){                                         
      setVisible(false);  
....
}
}

And another class:

public class Screen2 extends javax.swing.JFrame {
...
//Clicking on JButton2 is supposed to enable JButton1 (from Screen1) again     
...
}

Now, what is the easiest way to enable JButton1 again? I don't have direct access to JButton1 from Screen1 to set is visible again. I've looked into ActionListeners and Modal JDialogs which seemed from my Google search like some promising ways to solve this (possibly?). But I can't really find an example that I would understand (I'm more of a Java beginner).

Any helpful input is appreciated!

lilisyn
  • 63
  • 1
  • 7
  • 1
    Maybe you should consider implementing some kind of [Observer Pattern](http://www.oodesign.com/observer-pattern.html) which the first class can use to monitor for changes made by the second and update it's state accordingly – MadProgrammer May 02 '16 at 10:51
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson May 02 '16 at 13:53

1 Answers1

1

Please find below this simple example

Screen2 contains a JButton disabled by default, and Screen1 contains another JButton that can enable the first button.

Screen2

public class Screen2 extends JPanel {

    private JButton button;

    public Screen2() {
        button = new JButton("Button");
        button.setEnabled(false); //the button is disabled by default
        this.add(button);// add the button to the screen
    }

    // this method will be used to enable the button
    public void changeButtonStatus(boolean flag) {
        button.setEnabled(flag);
    }
}

Screen1

public class Screen1 {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Screen1");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        JButton button = new JButton("Enable the button");
        Screen2 screen2 = new Screen2();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                screen2.changeButtonStatus(true); //Call the method that enable the button
            }
        });
        frame.add(screen2, BorderLayout.SOUTH);
        frame.add(button, BorderLayout.NORTH);
        frame.setVisible(true);
    }
}

Output

First, the Screen2 JButton was disabled

enter image description here

When clicking on the Screen1 JButton, the Screen2 JButton will enable.

enter image description here

Jad Chahine
  • 6,849
  • 8
  • 37
  • 59