当前位置: 首页 > 知识库问答 >
问题:

Java应用程序,多场景

南宫海超
2023-03-14

我在一个java项目上工作,我处理了每一个功能,但当谈到GUI时,我是一个初学者。我想知道的是,我可以像在JavaFX中一样使用java在一个阶段中显示不同的场景吗?例如,我的起点是一个登录面板,登录后清空Jframe,并显示下一个veiw或场景。观点很多,怎么办?

共有1个答案

苍志文
2023-03-14

基本上,在Swing中CardLayout允许您在单个容器中切换视图。首先看一下如何使用CardLayout以获得更多细节。

下面的示例使用模型-视图-控制器方法,目的是同时解耦代码,所以恐怕有点冗长,但这是使用MVC和代码分离方法的结果(我喜欢对接口进行编码)

让我们从定义我们想要的视图开始...

public interface IView<C extends IViewController> {

    public JComponent getView();
    public C getViewController();

}

public interface ILoginView extends IView<ILoginViewController> {
}

public interface IWelcomeView extends IView<IWelcomeViewController> {
}
public interface IViewController {

}

public interface ILoginViewController extends IViewController {

    public void loginWasSuccessful(ICredentials credentials);

    public void loginDidFail();

    public void loginWasCancelled();

}

public interface IWelcomeViewController extends IViewController {

    public ICredentials getCredentials();
    public void setCredentials(ICredentials credentials);

    public void setCredentialsListener(ICredentialsListener listener);
    public ICredentialsListener getCredentialsListener();

    public interface ICredentialsListener {

        public void credentialsWereUpdated(ICredentials credentials);

    }

}
public interface ICredentials {

    public String getUserName();

}
public abstract class AbstractView<C extends IViewController> extends JPanel implements IView<C> {

    private C viewController;

    public AbstractView(C viewController) {
        this.viewController = viewController;
    }

    @Override
    public JComponent getView() {
        return this;
    }

    @Override
    public C getViewController() {
        return viewController;
    }

}

public class WelcomeView extends AbstractView<IWelcomeViewController> implements IWelcomeView {

    private JLabel userName;

    public WelcomeView(IWelcomeViewController viewContoller) {
        super(viewContoller);
        viewContoller.setCredentialsListener((ICredentials credentials) -> {
            userName.setText(credentials.getUserName());
            revalidate();
            repaint();
        });

        userName = new JLabel("...");

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.insets = new Insets(10, 10, 10, 10);

        add(new JLabel("WELCOME!"), gbc);
        add(userName, gbc);

    }

}

public class LoginView extends AbstractView<ILoginViewController> implements ILoginView {

    private JTextField userName;
    private JPasswordField password;

    private JButton login;
    private JButton cancel;

    public LoginView(ILoginViewController controller) {
        super(controller);
        setLayout(new GridBagLayout());

        userName = new JTextField(10);
        password = new JPasswordField(10);

        login = new JButton("Login");
        cancel = new JButton("Cancel");

        login.addActionListener((ActionEvent e) -> {
            // Fake the login process...
            // This might be handed off to another controller...
            String name = userName.getText();
            if (name != null && !name.isEmpty()) {
                Random rnd = new Random();
                if (rnd.nextBoolean()) {
                    getViewController().loginWasSuccessful(new DefaultCredentials(userName.getText()));
                } else {
                    getViewController().loginDidFail();
                }
            }
        });
        cancel.addActionListener((ActionEvent e) -> {
            getViewController().loginWasCancelled();
        });

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(2, 2, 2, 2);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        add(new JLabel("Login"), gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = 1;
        add(new JLabel("Username:"), gbc);

        gbc.gridy++;
        add(new JLabel("Password:"), gbc);

        gbc.gridx++;
        gbc.gridy = 1;
        add(userName, gbc);

        gbc.gridy++;
        add(password, gbc);

        JPanel controls = new JPanel();
        controls.add(login);
        controls.add(cancel);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        add(controls, gbc);
    }

    public class DefaultCredentials implements ICredentials {

        private final String userName;

        public DefaultCredentials(String userName) {
            this.userName = userName;
        }

        @Override
        public String getUserName() {
            return userName;
        }

    }

}
public class MainPane extends JPanel {

    protected static final String LOGIN_VIEW = "View.login";
    protected static final String WELCOME_VIEW = "View.welcome";

    private CardLayout cardLayout;

    private ILoginView loginView;
    private IWelcomeView welcomeView;

    public MainPane() {
        cardLayout = new CardLayout();
        setLayout(cardLayout);

        // This could be established via a factory or builder pattern
        loginView = new LoginView(new LoginViewController());
        welcomeView = new WelcomeView(new WelcomeViewController());

        add(loginView.getView(), LOGIN_VIEW);
        add(welcomeView.getView(), WELCOME_VIEW);

        cardLayout.show(this, LOGIN_VIEW);
    }

    protected class LoginViewController implements ILoginViewController {

        @Override
        public void loginWasSuccessful(ICredentials credentials) {
            welcomeView.getViewController().setCredentials(credentials);
            cardLayout.show(MainPane.this, WELCOME_VIEW);
        }

        @Override
        public void loginDidFail() {
            JOptionPane.showMessageDialog(MainPane.this, "Login vaild", "Error", JOptionPane.ERROR_MESSAGE);
        }

        @Override
        public void loginWasCancelled() {
            SwingUtilities.windowForComponent(MainPane.this).dispose();
        }

    }

    protected class WelcomeViewController implements IWelcomeViewController {

        private IWelcomeViewController.ICredentialsListener credentialsListener;
        private ICredentials credentials;

        @Override
        public ICredentials getCredentials() {
            return credentials;
        }

        @Override
        public void setCredentials(ICredentials credentials) {
            this.credentials = credentials;
            IWelcomeViewController.ICredentialsListener listener = getCredentialsListener();
            if (listener != null) {
                listener.credentialsWereUpdated(credentials);
            }
        }

        @Override
        public void setCredentialsListener(IWelcomeViewController.ICredentialsListener listener) {
            this.credentialsListener = listener;
        }

        @Override
        public IWelcomeViewController.ICredentialsListener getCredentialsListener() {
            return credentialsListener;
        }

    }

}
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestCardLayout {

    public static void main(String[] args) {
        new TestCardLayout();
    }

    public TestCardLayout() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

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

    public class MainPane extends JPanel {

        protected static final String LOGIN_VIEW = "View.login";
        protected static final String WELCOME_VIEW = "View.welcome";

        private CardLayout cardLayout;

        private ILoginView loginView;
        private IWelcomeView welcomeView;

        public MainPane() {
            cardLayout = new CardLayout();
            setLayout(cardLayout);

            // This could be established via a factory or builder pattern
            loginView = new LoginView(new LoginViewController());
            welcomeView = new WelcomeView(new WelcomeViewController());

            add(loginView.getView(), LOGIN_VIEW);
            add(welcomeView.getView(), WELCOME_VIEW);

            cardLayout.show(this, LOGIN_VIEW);
        }

        protected class LoginViewController implements ILoginViewController {

            @Override
            public void loginWasSuccessful(ICredentials credentials) {
                welcomeView.getViewController().setCredentials(credentials);
                cardLayout.show(MainPane.this, WELCOME_VIEW);
            }

            @Override
            public void loginDidFail() {
                JOptionPane.showMessageDialog(MainPane.this, "Login vaild", "Error", JOptionPane.ERROR_MESSAGE);
            }

            @Override
            public void loginWasCancelled() {
                SwingUtilities.windowForComponent(MainPane.this).dispose();
            }

        }

        protected class WelcomeViewController implements IWelcomeViewController {

            private IWelcomeViewController.ICredentialsListener credentialsListener;
            private ICredentials credentials;

            @Override
            public ICredentials getCredentials() {
                return credentials;
            }

            @Override
            public void setCredentials(ICredentials credentials) {
                this.credentials = credentials;
                IWelcomeViewController.ICredentialsListener listener = getCredentialsListener();
                if (listener != null) {
                    listener.credentialsWereUpdated(credentials);
                }
            }

            @Override
            public void setCredentialsListener(IWelcomeViewController.ICredentialsListener listener) {
                this.credentialsListener = listener;
            }

            @Override
            public IWelcomeViewController.ICredentialsListener getCredentialsListener() {
                return credentialsListener;
            }

        }

    }

    public interface IViewController {

    }

    public interface ILoginViewController extends IViewController {

        public void loginWasSuccessful(ICredentials credentials);

        public void loginDidFail();

        public void loginWasCancelled();

    }

    public interface IWelcomeViewController extends IViewController {

        public ICredentials getCredentials();

        public void setCredentials(ICredentials credentials);

        public void setCredentialsListener(ICredentialsListener listener);

        public ICredentialsListener getCredentialsListener();

        public interface ICredentialsListener {

            public void credentialsWereUpdated(ICredentials credentials);

        }

    }

    public interface ICredentials {

        public String getUserName();
    }

    public interface IView<C extends IViewController> {

        public JComponent getView();

        public C getViewController();

    }

    public interface ILoginView extends IView<ILoginViewController> {
    }

    public interface IWelcomeView extends IView<IWelcomeViewController> {
    }

    public abstract class AbstractView<C extends IViewController> extends JPanel implements IView<C> {

        private C viewController;

        public AbstractView(C viewController) {
            this.viewController = viewController;
        }

        @Override
        public JComponent getView() {
            return this;
        }

        @Override
        public C getViewController() {
            return viewController;
        }

    }

    public class WelcomeView extends AbstractView<IWelcomeViewController> implements IWelcomeView {

        private JLabel userName;

        public WelcomeView(IWelcomeViewController viewContoller) {
            super(viewContoller);
            viewContoller.setCredentialsListener((ICredentials credentials) -> {
                userName.setText(credentials.getUserName());
                revalidate();
                repaint();
            });

            userName = new JLabel("...");

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.insets = new Insets(10, 10, 10, 10);

            add(new JLabel("WELCOME!"), gbc);
            add(userName, gbc);

        }

    }

    public class LoginView extends AbstractView<ILoginViewController> implements ILoginView {

        private JTextField userName;
        private JPasswordField password;

        private JButton login;
        private JButton cancel;

        public LoginView(ILoginViewController controller) {
            super(controller);
            setLayout(new GridBagLayout());

            userName = new JTextField(10);
            password = new JPasswordField(10);

            login = new JButton("Login");
            cancel = new JButton("Cancel");

            login.addActionListener((ActionEvent e) -> {
                // Fake the login process...
                // This might be handed off to another controller...
                String name = userName.getText();
                if (name != null && !name.isEmpty()) {
                    Random rnd = new Random();
                    if (rnd.nextBoolean()) {
                        getViewController().loginWasSuccessful(new DefaultCredentials(userName.getText()));
                    } else {
                        getViewController().loginDidFail();
                    }
                }
            });
            cancel.addActionListener((ActionEvent e) -> {
                getViewController().loginWasCancelled();
            });

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(2, 2, 2, 2);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(new JLabel("Login"), gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.gridwidth = 1;
            add(new JLabel("Username:"), gbc);

            gbc.gridy++;
            add(new JLabel("Password:"), gbc);

            gbc.gridx++;
            gbc.gridy = 1;
            add(userName, gbc);

            gbc.gridy++;
            add(password, gbc);

            JPanel controls = new JPanel();
            controls.add(login);
            controls.add(cancel);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(controls, gbc);
        }

        public class DefaultCredentials implements ICredentials {

            private final String userName;

            public DefaultCredentials(String userName) {
                this.userName = userName;
            }

            @Override
            public String getUserName() {
                return userName;
            }

        }

    }

}
 类似资料:
  • 下载jython-standalone-2.7.0.jar - 用于在其官方下载页面中嵌入Jython的Java应用程序: http://www.jython.org/downloads.html : jython-standalone-2.7.0.jar并将此jar文件包含在Java CLASSPATH环境变量中。 该库包含PythonInterpreter类。 使用此类的对象,可以使用exec

  • 问题内容: 我最近继承了一个小型Java程序,该程序从大型数据库中获取信息,进行一些处理并生成有关该信息的详细图像。原始作者使用单个线程编写了代码,然后对其进行了修改,以使其可以使用多个线程。 他在代码中定义了一个常量; 然后,它设置用于创建映像的线程数。 我理解他的理由,即线程数不能大于可用处理器的数目,因此将其设置为可以充分发挥处理器潜力的数量。这样对吗?还是有更好的方法来充分利用处理器的潜力

  • 问题内容: 我不是在寻找java-web- start,而是在寻找胖客户端应用程序安装工具包。我有一个独立的应用程序,其中包含几个文件(jar文件,数据文件等),并且需要执行一些非常标准的安装任务,例如向用户询问目标目录,让他们找到系统的某些部分- 选择一些按计算机或按用户配置的选项,并可能尝试检测它们的某些计算机设置。 我正在寻找类似于MSI或其他向导驱动的安装应用程序的东西。什么是Java的良

  • 我有一个包含“资源管理器”类的多线程Java应用程序。 此类提供了一个资源列表,这些资源可以作为初始化参数请求。然后检查每个文件的本地文件系统,并将确定为本地的文件添加到列表中。 当类收到资源请求时,会发生以下情况之一: > 如果资源被确定为本地资源(在列表中):请提供可以找到它的URI。 如果资源是远程的(不在列表中):安排一个工作进程来获取资源。工作进程将在任务完成时通知经理,并更新本地资源列

  • 我有一个多线程应用程序,它有一个生产者线程和几个消费者线程。数据存储在一个共享的线程安全集合中,当缓冲区中有足够的数据时,就刷新到数据库中。 来自爪哇文档 - 一个队列,它还支持在检索元素时等待队列变为非空,并在存储元素时等待队列中的空间变为可用。 检索并删除此队列的头部,如有必要,请等待元素可用。 我的问题是- < li >是否有另一个集合具有E[] take(int n)方法?即阻塞队列等待,