JFrame:如何在单击按钮时隐藏主窗口?

时间:2014-10-29 06:10:23

标签: java swing jframe

我有一个简单的代码,它的作用是首先有一个带按钮的框架,如果单击按钮会出现一个消息对话框,如何在按下按钮时将主框架的可见性设置为false,然后当用户在消息对话框中单击“确定”时,将可见性设置为true

这是代码:

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

1 个答案:

答案 0 :(得分:2)

@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 
    }
}