日期:2014-05-20  浏览次数:20710 次

在子panel里可不可以用类似setVisible关闭主窗体 !!panel是自定义加载到窗体上的!!
就是在主窗体里按了退出按钮;切换到自定义panel上,在这panel里按了确定,退出后直接切换的登入界面。setVisible这时只能控制这个panel!

------解决方案--------------------
这样不能符合你的要求么

Java code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test
{
    public static void main(String[] args)
    {
        MFrame frame = new MFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class MFrame extends JFrame
{
    public static final int Default_Width = 300;
    public static final int Default_Height = 300;
    private CardLayout card;
    private Container con;
    
    MFrame()
    {
        setTitle("test");
        setSize(Default_Width, Default_Height);
        
        card = new CardLayout();
        con = getContentPane();
        con.setLayout(card);
        
        FirstPanel fPanel = new FirstPanel();
        SecondPanel sPanel = new SecondPanel();
        
        con.add(fPanel, "first");
        con.add(sPanel, "second");
    }
    
    class FirstPanel extends JPanel
    {
        public FirstPanel()
        {
            setLayout(new FlowLayout());
            
            JButton button = new JButton("登录");
            button.addActionListener(new
                                    ActionListener()
                                    {
                                        public void actionPerformed(ActionEvent e)
                                        {
                                            card.show(con, "second");
                                        }
                                    });
            JLabel label = new JLabel("登录界面");
            
            add(label);
            add(button);
        }
    }
    
    class SecondPanel extends JPanel
    {
        public SecondPanel()
        {
            setLayout(new BorderLayout());
            setBackground(Color.RED);
            
            JLabel label = new JLabel("WELCOME", JLabel.CENTER);
            JButton button = new JButton("QUIT");
            
            button.addActionListener(new
                                    ActionListener()
                                    {
                                        public void actionPerformed(ActionEvent e)
                                        {
                                            card.show(con, "first");
                                        }
                                    });
            
            add(label, BorderLayout.CENTER);
            add(button, BorderLayout.SOUTH);
        }
    }
}