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));
        
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Shapes Example");

        add(new DrawingPanel());
        
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    }

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

    class DrawingPanel extends JPanel {

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.setColor(Color.RED);
            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