首页 > 解决方案 > 如何从另一个 Java 类调用 GUI 表单

问题描述

所以我一直在弄清楚如何使这项工作但我找不到,所以我决定寻求帮助,下面是我的代码的样子,我想做的是在用户之后显示主菜单拒绝继续本教程,我试图

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


public class Login {
   public Login() {
      String userName;
      int    option;

    //This will ask user to input the username
    userName = JOptionPane.showInputDialog(null,"Please enter your name","Welcome", JOptionPane.INFORMATION_MESSAGE);

    //Display option
    option =JOptionPane.showOptionDialog(null, "Welcome " + userName + "\n\nWould you like to have a tutorial about this game?",
            "Welcome", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);


    //Ok to continue to the tutorial
    if(option == JOptionPane.OK_OPTION)
    {
    //Call the tutorial class
    }

这是代码出错的地方,我尝试用不同的方式解决

    else //If select cancel will proceed to the Main menu
        {
         //This is the part I can't figure it out, it display different errors when I try different ways 
            that I searched from website
         MainMenu MainMenuGUI = new MainMenu();
        }
    }
}

这是我的主菜单代码

     import javax.swing.*;
     import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
     import java.awt.event.ActionEvent;
     import java.awt.event.ActionListener;
     import java.awt.*;
     import javax.swing.*;

    public class MainMenu {
         private JButton exitButton;
         private JPanel MainMenu;
         private JButton startButton;
         private JButton historyButton;

    public MainMenu() {
        exitButton.addActionListener(new ActionListener() {


            @Override
            public void actionPerformed(ActionEvent e) {
                int exitButton = JOptionPane.YES_NO_OPTION;

                exitButton = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Warning", JOptionPane.YES_NO_OPTION);
                if (exitButton == JOptionPane.YES_OPTION) 
                   {
                    System.exit(0);
                   } 

            }
        });
    }

    //Main Menu GUI setup
    public static void main(String[] args) {
        JFrame frame = new JFrame("Main Menu");
        frame.setContentPane(new MainMenu().MainMenu);
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.setMinimumSize(new Dimension(500, 500));
        frame.pack();
        frame.setVisible(true);
    }
}

标签: javajoptionpane

解决方案


摆脱public static void main(String args[])MainMenu 类中的方法。在 java 程序中只使用一次 main 方法。相反,创建一个类似的方法public void initUI()并将您拥有的所有代码放在其中的main()方法中。

在你的Login课堂上,就在你打电话之后MainMenu MainMenuGUI = new MainMenu();

你可以打电话MainMenuGUI.initUI()

一件小事MainMenuGUI可能应该是mainMenuGUI正确遵循驼峰格式并避免以后混淆。


推荐阅读