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
source
share