如何向JComponent添加多个对象?

时间:2015-10-20 04:51:11

标签: java swing

这是我的测试人员课程:

public void start() {
    // We do our drawing here       
    JFrame frame = new JFrame("Animation");
    frame.setSize(800, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));
    frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));
    frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));


    frame.setVisible(true);
}

Shape1类:

public class Shape1 extends JComponent{
    protected double x, y, r;
    protected double height, width;
    protected Color col;
    protected int counter;

    public Shape1(double x, double y, double r) {
        this.x = x - 2*r;
        this.y = y - r;
        this.r = r;
        this.width = 4*r;
        this.height = 2*r;

        this.col = new Color((int)(Math.random() * 0x1000000));
    }

    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D)g;
        draw(g2);
    }

    public void draw(Graphics2D g2){
        Ellipse2D.Double face = new Ellipse2D.Double(this.x, this.y, this.width, this.height);

        g2.setColor(this.col);
        g2.fill(face);
    }
}

我将Shape1类实例化3次并将它们添加到帧中。但是形状只画了一次,我怎么画3次呢?

3 个答案:

答案 0 :(得分:0)

您可以尝试使用循环:

List<Shape1> shapes = new ArrayList<>();

@Override
protected void paintComponent(Graphics g) {
    super.paintCompoent(g);
    for (Shape1 s : shapes) {
        s.draw(g);
    }
}

答案 1 :(得分:0)

JFrame默认使用BorderLayout,这意味着只有最后一个组件位于默认/ CENTER位置。

首先更改布局管理器。

public void start() {
    // We do our drawing here       
    JFrame frame = new JFrame("Animation");
    frame.setSize(800, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setLayout(new GridLayout(1, 3));
    frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));
    frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));
    frame.add(new Shape1(getRandom(WIDTH), getRandom(HEIGHT), objRadius));


    frame.setVisible(true);
}

请查看Laying Out Components Within a Container了解详情

当然,这假设您希望将形状的每个实例保留在其自己的组件中。如果你想让形状以某种方式相互作用或重叠,你最好创建一个可以自己绘制不同形状的JComponent

查看2D Graphics了解更多提示

此外,在进行任何自定义绘画之前,您应该调用super.paintComponent(g)

有关详细信息,请查看Painting in AWT and SwingPerforming Custom Painting

答案 2 :(得分:0)

  

我将Shape1类实例化3次并将它们添加到帧中。但是形状只画了一次,我怎么画3次呢?

如果要在面板中随机定位组件(即示例中JFrame的内容窗格),则需要将面板的布局设置为null。这意味着您需要手动确定组件的大小/位置。

所以你需要添加:

frame.setLayout( null );
在开始将形状添加到框架之前

但是,通常使用null布局绝不是一个好主意。所以我建议您使用Drag Layout,因为它被设计为在这种情况下替换空布局。