gpt4 book ai didi

java - 运行 Java Swing MVC 的驱动程序不显示 View

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:31 24 4
gpt4 key购买 nike

我对 MVC 不太了解,所以如果这是一个基本问题,请原谅我。

我目前正在做一个学校项目,我似乎无法让程序正常运行。我尝试编译这些 java 文件,没有出现任何错误。但是,当我尝试运行 MenuDriver.java 文件时,GUI 窗口/ View 不会弹出,程序就结束了。

MenuController.java

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

public class MenuController implements ActionListener {
private StartMenu start;

public MenuController(StartMenu start) {
this.start = start;
start.setListeners (this);
}

public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Play")) {
start.setVisible(false);
}
}

菜单驱动程序.java

public class MenuDriver
{
public static void main (String[] args)
{
StartMenu start = new StartMenu();
MenuController controller = new MenuController (start);
}
}

StartMenu.java

import javax.swing.JLabel;
import javax.swing.JButton;

public class StartMenu extends JFrame {

private JPanel contentPane;
private JButton btnPlay = new JButton("");
private JLabel label = new JLabel("");

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StartMenu frame = new StartMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public StartMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 450);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

Image img = new ImageIcon(this.getClass().getResource("/smthn1.png")).getImage();
label.setIcon(new ImageIcon(img));
label.setBounds(84, 58, 457, 183);
contentPane.add(label);

Image img2 = new ImageIcon(this.getClass().getResource("/smthn2.png")).getImage();
btnPlay.setIcon(new ImageIcon(img2));
btnPlay.setBounds(222, 251, 166, 64);
contentPane.add(btnPlay);

btnPlay.setActionCommand("Play");
}

public void setListeners (ActionListener a) {
btnPlay.addActionListener (a);
}
}

我正在失去理智,任何帮助将不胜感激。谢谢!

最佳答案

when I try to run the MenuDriver.java file, the GUI window/View does not pop-up, and the program just ends.

您永远不会使框架可见,因此程序就结束了。

您需要使框架在构造函数末尾可见:

btnPlay.setActionCommand("Play");
setVisible( true );

另外,学习使用 Layout Managers来定位组件。将 null 布局与 setBounds(...) 一起使用并不是 Swing 的设计使用方式。

关于java - 运行 Java Swing MVC 的驱动程序不显示 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com