I'm experiencing a very basic trouble in Java which blocks me from implementing and testing a project. The problem is that while I'm using an MVC pattern once a button is pressed I need to open a new JFrame where I draw N red rectangles. According to the MVC pattern the input value N is read from a text field in the Control class, where I tested and reads the value correctly. However, when I get into the new frame the value disappears and I get a nullPointerException.
I also tried similar question's source codes from here (like this: Using paintComponent() to draw rectangle in JFrame), but none of them seemed to work.
Relevant part of the Control class is:
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!");
}
}
}
}
Input validation is surely good and if I try here to print out the value of numberOfQueues does it well.
The class which extends the JFrame looks the following:
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);
}
}
I also tried to call the repaint method in both places, I also tried not using a getter, just getting the value directly through a class instance, I also tried inside the constructor, outside the constructor, wherever it could be positioned, but somewhere I keep making the same obvious mistake which I couldn't find.