简体   繁体   中英

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();
    }
}
@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 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM