2015-10-20 94 views
3

这是我的测试类:如何向JComponent添加多个对象?

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次?

+1

'JFrame'默认使用'BorderLayout',这意味着只有最后一个组件被放置在默认/'CENTER'位置。另外,在做任何自定义绘画之前,你应该调用'super.paintComponent(g)' – MadProgrammer

回答

0

您可以尝试使用一个循环:

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

@Override 
protected void paintComponent(Graphics g) { 
    super.paintCompoent(g); 
    for (Shape1 s : shapes) { 
     s.draw(g); 
    } 
} 
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更多细节

0

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

如果您想要在面板中随机定位组件(即您的示例中的JFrame的内容窗格),则需要将面板的布局设置为空。这意味着您需要手动确定组件的大小/位置。你开始添加形状到帧之前

frame.setLayout(null); 

所以,你会需要添加。

但是,通常使用空布局从来都不是好主意。因此,我建议您使用Drag Layout,因为它旨在替换这种情况下的空布局。

相关问题