我在Java中遇到了一个非常基本的问题,它阻碍了我实现和测试项目。问题是,当我使用MVC模式时,一旦按下按钮,我需要打开一个新的JFrame,在那里我画N个红色矩形。根据MVC模式,输入值N是从Control类中的文本字段中读取的,在那里我测试并正确读取了值。但是,当我进入新的帧时,该值将消失,并得到一个nullPointerException。
我也尝试过类似问题的源代码(比如:使用paintComponent()在JFrame中绘制矩形),但似乎都不起作用。
控制类的相关部分是:
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的类如下所示:
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);
}
}
我还试着在这两个地方调用repait方法,我也试着不使用getter,只是直接通过类实例获取值,我还试过在构造函数内部,在构造函数外部,在任何可以定位它的地方,但在某个地方,我一直犯着同样明显的错误,我找不到。
您正在传递View模型类(它应该有您想要绘制的矩形数量),但您正在调用"control.getNumberOfQueues()",而您从未实例化"control control"
你的视图不应该知道控件,它应该使用你传递给它的模型来渲染你的模型。你的控件应该接受输入并用矩形的数量更新模型,然后你的视图应该再次渲染该模型。