java - 如何从另一个 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);
}
}
解决方案
摆脱public static void main(String args[])
MainMenu 类中的方法。在 java 程序中只使用一次 main 方法。相反,创建一个类似的方法public void initUI()
并将您拥有的所有代码放在其中的main()
方法中。
在你的Login
课堂上,就在你打电话之后MainMenu MainMenuGUI = new MainMenu();
你可以打电话MainMenuGUI.initUI()
。
一件小事MainMenuGUI
可能应该是mainMenuGUI
正确遵循驼峰格式并避免以后混淆。
推荐阅读
- css - Fontawesome 无法通过 css 中的参考编号加载图标
- css - 反转列顺序
- php - PHP 检查是否调试构建
- sql - 加入 2 个表,其中右日期是最大日期小于或等于左日期
- image - 如何将几块图像组合成一张图像?
- amazon-web-services - 在哪里可以设置 TLSv1.2 以进行 Web 分发?
- jasper-reports - 在 JRS 上执行报告时未生成多张工作表,但在本地 Studio 应用程序上也可以正常工作
- javascript - 如何在 openlayers 4.6.5 中使用 map.on('click'...) 从 GeoJson-Multipoint 特征中获取单个特征
- php - PHP PDO MySQL:插入语句运行没有错误,没有插入发生
- python - 如果组合框的值为空,则返回无