Rob
Rob

Reputation: 16002

Java : need 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 frame 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();
    }
}

What I simply want to do is to add this rectangle into my LittleFrame's container. But I have no idea of how to do it.

Upvotes: 3

Views: 100

Answers (1)

Dan D.
Dan D.

Reputation: 32391

I suggest you create an extra class that extends JPanel like the one 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 LittleFrame class, you will need to add this new panel to your frame content pane and add your Rectangle to the list of rectangles to be painted. At the end of the LittleFrame constructor, add:

GraphicsPanel panel = new GraphicsPanel();
panel.addRectangle(rec);
getContentPane().add(panel);

Upvotes: 4

Related Questions