mercredi 18 décembre 2019

How can i make a JButton to switch its function

I had a frame with two buttons. The first button opened a second frame and the other button was closing it. It worked. Now I want to make a single button that opens a frame and by clicking it again the frame shall close. But it is not working. I set boolean conditions. By clicking the button once it is set from false to true. If it is set to "true" the actionListener is supposed to recognize that annother action (close frame) shall be performed. But nothing happens. Here the code.

   public class Main {

       public static void main(String[] args) {

       FrameOne frameOne = new FrameOne ();
       }
   }

.

public class FrameOne extends JFrame implements ActionListener {

    private FrameTwo frameTwo;
    private boolean  frameIsOpen  = false;          // By clicking the button once the value is set to true.
    private JButton  btn          = new JButton();

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

FrameOne(){

    btn.addActionListener(this);
    add(btn);
    setSize(400,400);
    setLocation(300, 250);
    setLayout(new FlowLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);

}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

public void actionPerformed(ActionEvent e) {

    if(e.getSource() == btn && frameIsOpen == false) {

                        frameTwo = new FrameTwo();    // Opens the new frame
                        boolean frameIsOpen = true;}  // Fulfills the condition for the else if statement.

    else if (e.getSource() == btn && frameIsOpen == true) {      

                        frameTwo.dispatchEvent(new WindowEvent(frameTwo, WindowEvent.WINDOW_CLOSING)); }
}
}

.

public class FrameTwo extends JDialog {

    FrameTwo() {

        setSize(400,400);
        setLocation(900, 250);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);

}

Aucun commentaire:

Enregistrer un commentaire