Filomena Del Sorbo
Filomena Del Sorbo

Reputation: 75

Add a rectangle to the center of JPanel

I'm trying to draw a Rectangle to the center of a JPanel. I have made this code but when I run it, the rectangle does not appears in the panel. If I try with JFrame, the rectangle appears. Can someone help me?

RectangleTester

package eventi5;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class RectangleTester {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Rectangle");
        frame.setSize(250, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final RectangleComponent component = new RectangleComponent();
        frame.setVisible(true);
        JPanel panel=new JPanel();
        panel.add(component);
        frame.add(panel);
    }
}

RectangleComponent

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JPanel;

public class RectangleComponent extends JPanel{

    private Rectangle box;

    public RectangleComponent(){
        box=new Rectangle(10,20,30,40);
    }

      public void paintComponent(Graphics g){
        Graphics2D g2=(Graphics2D) g;
        g2.draw(box);
        g2.setColor(Color.BLUE);
        g2.fill(box);
    }   
}

Upvotes: 1

Views: 2255

Answers (1)

alex2410
alex2410

Reputation: 10994

1) You need override getPreferredSize() of RectangleComponent like next:

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(box.width+box.x*2,box.height+box.y*2);
    }

2) call super() method of paintComponent()( super.paintComponent(g);) before your customizations.

EDIT:

public class RectangleComponent extends JPanel {

        private List<Rectangle> boxes;
        private int width = 30;
        private int height = 40;
        private int startX = 10;
        private int startY = 20;

        public RectangleComponent() {
            boxes = new ArrayList<Rectangle>();
            for (int i = 0; i < 3; i++){
                boxes.add(new Rectangle(startX+(width+startX)*i, startY, width, height));
            }
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            for (int i = 0; i < boxes.size(); i++){
                g2.draw(boxes.get(i));
            }
            g2.setColor(Color.BLUE);
            for (int i = 0; i < boxes.size(); i++){
                g2.fill(boxes.get(i));
            }

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(boxes.size()*(width+startX)+startX, height+startY*2);
        }

    }

Upvotes: 3

Related Questions