在 JPanel 的中心添加一个矩形

Add a rectangle to the center of JPanel

我正在尝试将 Rectangle 画到 JPanel 的中心。我已经制作了这段代码,但是当我 运行 它时,矩形不会出现在面板中。如果我尝试使用 JFrame,就会出现矩形。有人可以帮助我吗?

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);
    }   
}

1) 您需要覆盖 RectangleComponentgetPreferredSize(),如下所示:

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

2) 在自定义之前调用 paintComponent()(super.paintComponent(g);) 的 super() 方法。

编辑:

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);
        }

    }