为什么我可以在框架上画画而不是在容器内?

csbfibhn  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(361)

你能帮忙吗?我想画一个圆。所以我做了下面的圆圈课。我可以通过将圆添加到框架来绘制圆,但不能通过将圆添加到面板然后将面板添加到框架来绘制圆。我想做后者,因为我想要多个圆。

public class Circle extends Canvas{
    int x;
    int y;
    int rectwidth;
    int rectheight;

    public Circle(int x, int y, int r) {
        this.x=x;
        this.y=y;
        this.rectwidth=r;
        this.rectheight=r;
    }

    public void paint (Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        super.paint(g);
        // draw Ellipse2D.Double
        g2.draw(new Ellipse2D.Double(x, y, rectwidth, rectheight));
        g2.setColor(Color.BLACK);
    }
}

以下内容摘自 View 班级:

Panel container = new Panel();
container.setPreferredSize(new Dimension(400,400));
container.setLayout(new BorderLayout());
Circle circle = new Circle(20,20,200);
container.add(circle, BorderLayout.CENTER);
frame.add(container); // <- this does not draw
frame.add(circle);// <- this draws the circle   
frame.pack();
frame.setVisible(true);

我试过了 FlowLayout ,无布局,删除 pack() ,删除preferredsize,在 Frame . 谢谢你的回答。

9wbgstp7

9wbgstp71#

frame.add(container); // <- this does not draw
frame.add(circle);// <- this draws the circle

首先,一个组件只能有一个父级,所以不能将“圆”添加到“容器”中,然后再添加到“框架”中。“圆”将从“容器”中删除。
所以我假设你一次只测试一个语句。
每个组件应确定其自己的首选尺寸。

container.setPreferredSize(new Dimension(400,400));

不应设置面板的首选大小。面板将根据添加到面板的组件的首选尺寸确定其自己的首选尺寸。
问题是“circle”类不确定自己的首选大小。
在构造函数中,需要如下代码:

int width = x + rectWidth;
int height = y + rectHeight;
setPreferredSize( new Dimension(width, height) );

现在,当您将圆添加到面板时,面板的布局管理器可以完成其工作。
或者,如果将圆添加到框架中,则内容窗格的布局管理器可以完成其工作。

相关问题