about overwritting jpanel paintcomponent and relative position

Here’s a somewhat simple example I created for a different question.

Change the location of the rectangles and see where they wind up.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ShapesExample extends JFrame {

    private static final long serialVersionUID = 1L;

    private List<Rectangle> rectangles;

    public ShapesExample() {
        rectangles = new ArrayList<>();
        rectangles.add(new Rectangle(10, 10, 20, 20));
        rectangles.add(new Rectangle(41, 41, 20, 20));
        setTitle("Shapes Example");

        add(new DrawingPanel());

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ShapesExample();

    class DrawingPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        public DrawingPanel() {
            this.setPreferredSize(new Dimension(300, 300));

        protected void paintComponent(Graphics g) {

            for (Rectangle rectangle : rectangles) {
                g.drawRect(rectangle.x, rectangle.y, 
                        rectangle.width, rectangle.height);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top