Java: need an explanation about graphics
I would like to know a little more about Graphics and how to use it.
I have this class:
public class Rectangle 
{
    private int x, y, length, width;
    // constructor, getters and setters
    public void drawItself(Graphics g)
    {
        g.drawRect(x, y, length, width);
    }
}
      
        
        
        
      
    And a very simple shot like this:
public class LittleFrame extends JFrame 
{
    Rectangle rec = new Rectangle(30,30,200,100);      
    public LittleFrame()
    {
        this.getContentPane().setBackground(Color.LIGHT_GRAY);
        this.setSize(600,400);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String[] args)
    {
        new LittleFrame();
    }
}
      
        
        
        
      
    I just want to add this rectangle to the LittleFrame container. But I don't know how to do it.
+3 
Rob 
source
to share
      
1 answer
      
        
        
        
      
    
I suggest you create an additional class that extends JPanel
      
        
        
        
      
    as shown below:
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class GraphicsPanel extends JPanel {
    private List<Rectangle> rectangles = new ArrayList<Rectangle>();
    public void addRectangle(Rectangle rectangle) {
        rectangles.add(rectangle);
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Rectangle rectangle : rectangles) {
            rectangle.drawItself(g);
        }
    }
}
      
        
        
        
      
    Then in your class, LittleFrame
      
        
        
        
      
    you will need to add this new panel to the frame's content panel and add yours Rectangle
      
        
        
        
      
    to the list of rectangles to be colored. At the end of the constructor LittleFrame
      
        
        
        
      
    add:
GraphicsPanel panel = new GraphicsPanel();
panel.addRectangle(rec);
getContentPane().add(panel);
      
        
        
        
      
    
+4 
Dan D. 
source
to share