1

I have a library application that permits users to log in, and many other things.

I don't really know how to make multiple windows (views), such as a login, and if it is succesfull, closing the current window and opening the other user interface.

I hope that I have been clear.

4

1 回答 1

2

更新答案:假设您的三个JPanel扩展名为MyLoginPanelMyWelcomePanelMyFormPanel。我假设您提到的表单将是其中的主要类,而不是构成表单的实际组件。

这些面板中的每一个都应该照顾自己的组件。

查看下面的代码,您只需要用您正在使用的名字查找并替换我的名字。

建议:让你的类实现一些接口,以监听三个不同面板上的变化。例如:用户单击了一些按钮,该按钮应该使应用程序前进到下一个面板。该按钮必须通知某人。有人将成为接口的实现者。


enum AppState {
    LOGIN, WELCOME, FORM
}

interface ProgressListener {
    void progressFrom(AppState currentState);
}

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

public class MyForm implements Runnable, ProgressListener {
    // instance variables
    private JFrame frame;
    private MyLoginPanel loginPanel;
    private MyWelcomePanel welcomePanel;
    private MyFormPanel formPanel;

    /** Empty constructor of objects of class SomeClassUI. */
    public SomeClassUI() {
        // ...
    }

    /** Interface initialization. */
    @Override
    public void run() {
        // These should handle their own component initialization.
        // They should, at least, receive a reference to the listener.

        loginPanel = new MyLoginPanel(this);
        welcomePanel = new MyWelcomePanel(this);
        formPanel = new MyFormPanel(this);

        frame = new JFrame("Testing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(loginPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /** */
    @Override
    public void progressFrom(AppState whoTriggeredIt) {
        switch (whoTriggeredIt) {
            case LOGIN:
            frame.setContentPane(welcomePanel);
            frame.pack();
            return;

            case WELCOME:
            frame.setContentPane(formPanel);
            frame.pack();
            return;

            default: return;
        }
    }


    /** */
    public void go() {
        SwingUtilities.invokeLater(this);
    }


    /** */
    public static void main(String[] args) {
        new SomeClassUI().go();
    }
}

class MyLoginPanel extends JPanel implements ActionListener {
    private final ProgressListener listener;

    public MyLoginPanel(ProgressListener listener) {
        // Components, etc.
        this.listener = listener;
    }

        ...

    /** */
    @Override
    public void actionPerformed(ActionEvent e) {
        // Validate login, or whatever.
        // All went well, notify listener to progress.
        this.listener.progressFrom(AppState.LOGIN);
    }
}

JFrame您可能希望在自己的某个内容面板上执行这些操作,而不是直接从 中添加/删除元素,并将其存储为实例变量(请参阅 参考资料JFrame.setContentPane())。

如果您希望同时轻松访问所有面板而不是这种程序性的逐步更改,您可能需要查看CardLayout,如先前在评论中建议的那样。

我给出的建议只是一般指导方针,因为我不了解您的需求细节。

于 2013-05-19T17:55:51.367 回答