Im making a game but I have found a problem. Lets say I had 2 classes 1 With JPanel/JFrame and its paintComponenet in it. That will draw the graphics onto the frame. And the other called MainMenu.java only has a Rectangle Object in it:
Rectangle r = new Rectangle();
And In that class I set properties to it:
r.setSize(100, 200)
How would I send it I know how to draw objects.
Question: How do I take a graphics object from another class and take it to the class with paint on it and draw it but keep its properties?
How do I take a graphics object from another class and take it to the class with paint on it and draw it but keep its properties?
You don't. Everything should be drawn within the graphics context of the paintComponent method.
One solution is to keep a List<Rectangle>
in the panel class you are drawing on and iterate through the list the draw the objects. Have a method in the class to add shapes to it
public class DrawingPanel extends JPanel {
private List<Rectangle> rects = new ArrayList<Rectangle>();
protected void paintComponent(Grapchics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (Rectangle rect: rects) {
// draw rectangle
}
}
public void addRectangle(Rectangle rect) {
rects.add(rect);
repaint();
}
}
Now you can do something like
DrawingPanel panel = new DrawingPanel();
Rectangle rect = new Rectangle(...);
panel.addRectagnle(rect);
Every new rectangle you add will be painted on the panel. You can initialize the list with no rectangle, and nothing will be painted until you add one.