来自其他 class 的变量未在 JFrame 中获取值

Variable from other class doesn't get value in JFrame

我在 Java 中遇到了一个非常基本的问题,这使我无法实施和测试项目。问题是,当我使用 MVC 模式时,一旦按下按钮,我需要打开一个新的 JFrame,在其中绘制 N 个红色矩形。根据 MVC 模式,输入值 N 是从控件 class 中的文本字段读取的,我在其中测试并正确读取了该值。但是,当我进入新框架时,该值消失并且我得到一个 nullPointerException。

我也从这里尝试了类似问题的源代码(例如:Using paintComponent() to draw rectangle in JFrame),但其中 none 似乎有效。

控件class的相关部分是:

private void readInput()
{
    numberOfQueues = Integer.parseInt(v_view.field1.getText());
}
public int getNumberOfQueues()
{
    return numberOfQueues;
}
class StartListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                if(m_model.validateInput(v_view.field1.getText()) && m_model.validateInput(v_view.field2.getText()) &&
                   m_model.validateInput(v_view.field3.getText()) && m_model.validateInput(v_view.field4.getText()) && 
                   m_model.validateInput(v_view.field5.getText()) && m_model.validateInput(v_view.field6.getText()))
                {
                    if(Integer.parseInt(v_view.field3.getText()) <= Integer.parseInt(v_view.field4.getText()) &&
                        Integer.parseInt(v_view.field5.getText()) <= Integer.parseInt(v_view.field6.getText()))
                    {
                        readInput();
                        SimulationFrame simulationFrame = new SimulationFrame(m_model);
                        simulationFrame.setVisible(true);
                        simulationFrame.repaint();
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null,"Invalid input range! Please try again!");
                    }
                }
            }
}

输入验证确实很好,如果我在这里尝试打印出 numberOfQueues 的值,就可以了。

扩展 JFrame 的 class 如下所示:

public class SimulationFrame extends JFrame{

Control control;
private int numberOfQueues;

public SimulationFrame(Model model)
{
    setPreferredSize(new Dimension(1000, 550));
    this.pack();
    this.setTitle("Simulator Frame");
    this.setLayout(new FlowLayout());
    this.setVisible(true);
    this.setLocation(100, 100);
    numberOfQueues=control.getNumberOfQueues();
    System.out.println(numberOfQueues);
    repaint();
}

protected void paintComponent(Graphics g)
{
    g.setColor(Color.red);
    for(int i=0; i<numberOfQueues; i++)
    {
        System.out.println(control.numberOfQueues);
        g.fill3DRect(50+20, 20, 50, 50, true);
    }

}

我也试过在两个地方调用repaint方法,我也试过不使用getter,直接通过class实例获取值,我也在构造函数中试过,在构造函数之外,无论它可以放置在哪里,但在某个地方我一直在犯我找不到的同样明显的错误。

您正在传递您的视图模型 class(它应该有多少个您想绘制的矩形)但是您正在调用 "control.getNumberOfQueues()",您从未实例化 "Control control"

您的视图不应该知道该控件,它应该使用您传递给它的模型来呈现您的模型。您的控件应接受输入并使用矩形数更新模型,然后您的视图应再次呈现该模型。