I'm currently working on a project that involves using the Model-View-Controller architecture, in the project I have to implement freehand drawing inside of a JPanel, however the panel.paintComponent(g) method doesn't seem to work.
In my view package I create the GUI and give each object a getter, my controller class creates a GUI and uses these getters to instantiate the JPanels, JButtons etc. The Drawing model is passed the JPanel I want to draw on, as seen below.
public class Editor extends JPanel implements MouseListener, MouseMotionListener {
private int index = 0;
private Point[] arr = new Point[100000];
private JPanel xPanel = new JPanel();
Updater upDate = new Updater();
public void getPanel(JPanel dPanel)
{
xPanel = dPanel;
xPanel.addMouseListener(this);
xPanel.addMouseMotionListener(this);
xPanel.setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
System.out.println("Got to this point");
xPanel.paintComponents(g);
for(int i = 0; i < index - 1; i++)
{
System.out.println("And here 2");
g.drawLine(arr[i].x, arr[i].y, arr[i+1].x, arr[i+1].y);
System.out.println("And here 3");
}
}
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
arr[index] = new Point(e.getX(), e.getY());
index++;
System.out.println(index);
upDate.update(xPanel);
}
@Override
public void mouseDragged(java.awt.event.MouseEvent e) {
arr[index] = new Point(e.getX(), e.getY());
index++;
System.out.println(index);
upDate.update(xPanel);
}
My Controller class looks like this.
private GUI view;
private JButton buttonLoad;
private JButton buttonZoom;
private JButton buttonDrag;
private JButton buttonSave;
private JButton buttonRotate;
private JButton buttonDraw;
private JMenuBar menuB;
private JPanel dPanel;
private MouseListener e;
Graphics g;
public Controller(GUI gui){
this.view = gui;
menuB = view.getMenu();
buttonLoad = view.getLoad();
buttonZoom = view.getZoom();
buttonRotate = view.getRotate();
buttonSave = view.getSave();
buttonDrag = view.getDrag();
buttonDraw = view.getDraw();
dPanel = view.getModel();
g = dPanel.getGraphics();
FunctionListener x = new FunctionListener();
MenuBarListener y = new MenuBarListener();
buttonLoad.addActionListener(x);
buttonZoom.addActionListener(x);
buttonRotate.addActionListener(x);
buttonSave.addActionListener(x);
buttonDrag.addActionListener(x);
buttonDraw.addActionListener(x);
//menuB.addMenuListener(y);
}
class FunctionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(buttonZoom)){
Editor editor = new Editor();
editor.getPanel(dPanel);
editor.paintComponent(g);
}
It's worth noting that dPanel = view.getModel(); is a getter for a JPanel called Model in my GUI class. Everything seems to be working, the index of points is being returned properly yet there is no drawing, after running some simple System.out.println tests, I know that the code isn't entering the for loop in the Editor class.
Thanks for any help!