Search code examples
javaswingjpaneldrawgraphics2d

Drawing rectangles on a JPanel


I have a JScrollPane and on top of it I have a JPanel named 'panel1'. I want some rectangles to be drawn on this JPanel.

I have a class named DrawRectPanel which extends JPanel and does all the drawing stuff. The problem is that, I tried to draw the rectangles on panel1 by writing the following code :

panel1.add(new DrawRectPanel());

but nothing appeared on panel1 then I tried, just as a test to the class DrawRectPanel :

JFrame frame = new JFrame();
frame.setSize(1000, 500);
Container contentPane =    frame.getContentPane();
contentPane.add(new DrawRectPanel());
frame.show();

This worked, and produced the drawings but on a separate JFrame How can I draw the rectangles on panel1 ? Thanks in advance.

EDIT : code for DrawRectPanel

public class DrawRectPanel extends JPanel  {

    DrawRectPanel() {
        Dimension g = new Dimension(400,400);
        this.setPreferredSize(g);
        System.out.println("label 1");
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("label 2");
        g.setColor(Color.red);
        g.fillRect(20, 10, 80, 30);
    }
 }

only label 1 is printed on the screen


Solution

  • still no idea,

    for example

    enter image description here

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    
    public class CustomComponent extends JFrame {
    
        private static final long serialVersionUID = 1L;
    
        public CustomComponent() {
            setTitle("Custom Component Graphics2D");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public void display() {
            add(new CustomComponents());
            pack();
            // enforces the minimum size of both frame and component        
            setMinimumSize(getSize());
            setVisible(true);
        }
    
        public static void main(String[] args) {
            CustomComponent main = new CustomComponent();
            main.display();
        }
    }
    
    class CustomComponents extends JComponent {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        public Dimension getMinimumSize() {
            return new Dimension(100, 100);
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 300);
        }
    
        @Override
        public void paintComponent(Graphics g) {
            int margin = 10;
            Dimension dim = getSize();
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
        }
    }