Drawing rectangles on JPanel

I have a JScrollPane, and in addition, I have a JPanel named "panel1". I want rectangles to be drawn on this JPanel.

I have a class called DrawRectPanel that extends JPanel and does all the drawing material. The problem is that I tried to draw the rectangles in panel 1 by writing the following code:

panel1.add(new DrawRectPanel());

but nothing appeared on panel 1, I tried it as a test of the DrawRectPanel class:

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

This worked and created the drawings, but on a separate JFrame. How to draw rectangles on panel 1? 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 mark 1 is displayed on the screen

+2
source share
3 answers

still don't know

eg

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);
    }
}
+2
source

contentPane.add(new DrawRectPanel());

contentPane.add(panel1);

DrawRectPanel 1. DrawRectPanel contentPane. panel1 container.

+1

to fix your problem, change "paintComponent" to "paint", when the window is automatically repainted, it should work.

0
source

All Articles