从actionlistener访问在main中创建的JFrame

时间:2011-11-21 16:56:40

标签: java swing jframe jpanel actionlistener

我已经在主类中为我的程序创建了一个框架(主框架),我想要添加并删除面板,以便在程序的不同屏幕之间切换。我程序的第一个屏幕是登录面板,它有一个开始按钮。当我按下开始按钮时,我想切换到菜单框。

removeAll方法似乎工作正常,因为登录面板消失了,但是当我使用add,validate和repaint方法时,它的位置没有出现。我试图明确地引用actionlistener中的大型机(即mainframe.add(menu)),但它无法识别该对象。

提前致谢!

public class Main {

    public static JFrame mainframe = new JFrame();

    public static void main(String[] args) {

        // Create mainframe to add and remove panels from
        LoginPanel lp = new LoginPanel();
        System.out.println("mainframe created!");

        // Set size of mainframe
        mainframe.setBounds(0, 0, 500, 500);
        mainframe.add(lp);

        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the mainframe
        int w = mainframe.getSize().width;
        int h = mainframe.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

        // Move the mainframe
        mainframe.setLocation(x, y);
        mainframe.setVisible(true);     
    }
}

这是我的登录面板类:

public class LoginPanel extends JPanel {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private final Action action = new SwingAction();

    /**
     * Create the panel.
     */
    public LoginPanel() {

        JButton btnLogin = new JButton("Login");
        btnLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String (passwordField.getPassword());

                Login login = new Login();
                boolean Correct = login.isCorrect(username, password);
                **if (Correct == true){
                    removeAll();
                    Menu menu = new Menu();
                    add(menu);
                    validate();  
                    repaint();
                    setBounds(0, 0, 500, 500);
                    System.out.println("Attempted to start menu!");
                }**
            }
        });
        btnLogin.setAction(action);
        btnLogin.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {

        }});

}

2 个答案:

答案 0 :(得分:4)

  

我想在程序的不同屏幕之间按顺序添加和删除面板

听起来你应该使用Card Layout

答案 1 :(得分:1)

mainframe定义为类字段:

private JFrame mainframe;