简体   繁体   English

在 JPanel 的中心添加一个矩形

[英]Add a rectangle to the center of JPanel

I'm trying to draw a Rectangle to the center of a JPanel .我正在尝试将Rectangle绘制到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.如果我尝试使用JFrame ,则会出现矩形。 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);
    }   
}

1) You need override getPreferredSize() of RectangleComponent like next: 1)你需要像下面这样覆盖RectangleComponent getPreferredSize()

    @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. 2) 在自定义之前调用paintComponent() ( super.paintComponent(g); ) 的super()方法。

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM