DarkPotatoKing
DarkPotatoKing

Reputation: 499

JFrame: How to hide main window when button is clicked?

I have a simple code, what it does is first there's a Frame with a button, if you click the button a message dialog appears, how will I set the visibility of the main frame to false when the button is pressed, then set back the visibility to true when the user clicks 'Ok' in the message dialog

here's the code:

package something;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;  //notice javax

public class Something extends JFrame implements ActionListener {

    JLabel answer = new JLabel("");
    JPanel pane = new JPanel();
    JButton somethingButton = new JButton("Something");

    Something() {
        super("Something");
        setBounds(100, 100, 300, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container con = this.getContentPane(); // inherit main frame
        con.add(pane); // add the panel to frame
        pane.add(somethingButton);
        somethingButton.requestFocus();
        somethingButton.addActionListener(this);
        setVisible(true); // display this frame
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == somethingButton) {
            answer.setText("Button pressed!");
            JOptionPane.showMessageDialog(null, "Something", "Message Dialog",
                    JOptionPane.PLAIN_MESSAGE);
            setVisible(true);  // show something
        }
    }

    public static void main(String args[]) {
        Something something = new Something();
    }
}

Upvotes: 1

Views: 3126

Answers (1)

Maninderjit Singh
Maninderjit Singh

Reputation: 36

@Override
public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == somethingButton) {
        answer.setText("Button pressed!");
        setVisible(false);  // hide something            
        JOptionPane.showMessageDialog(this, "Something", "Message Dialog",JOptionPane.PLAIN_MESSAGE);
        setVisible(true);  // show something 
    }
}

Upvotes: 2

Related Questions