Hello everyone, now to this forum
I'm fairly new to 2D graphics in Java.
I learned how to draw simple shapes on a JPanel, using the paintComponent method.
Now I'm trying to do the same thing, except the drawing should be done from an exterior class, to the class that extends JPanel.
I tried something that I believe should work, but it doesn't. Could you explain to me the standard way to do such a thing?
Here is my attempt:
Class Main:
package m; import java.util.*; import java.awt.*; import java.awt.Event.*; import javax.swing.*; public class Main extends JFrame { public static void main(String[] args) { Main m = new Main(); } public Main(){ setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("Bla"); setSize(500,500); Surface s = new Surface(); add(s); setVisible(true); } }
Class Surface:
package m; import java.util.*; import java.awt.*; import java.awt.Event.*; import javax.swing.*; public class Surface extends JPanel { public void paintComponent(Graphics g){ super.paintComponent(g); DrawRect d = new DrawRect(this); d.draw(); } }
Class DrawRect:
package m; import java.util.*; import java.awt.*; import java.awt.Event.*; import javax.swing.*; public class DrawRect { Surface surface; Graphics g; public DrawRect(Surface surface){ this.surface = surface; g = surface.getGraphics(); } public void draw(){ g.fillRect(20,20,100,50); // (this won't work). } }
Thanks a lot