无法在JFrame中看到一个组件

时间:2011-10-13 08:42:58

标签: java jframe

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;

public class Box {
    public static void main(String[] args){
        BoxFrame frame = new BoxFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class BoxFrame extends JFrame{
    public BoxFrame(){
        setTitle("BoxGame");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        DrawComponent[] component = new DrawComponent[4];
        component[0] = new DrawComponent(0, 0, 20, 20);
        component[1] = new DrawComponent(400, 0, 20, 20);

        add(component[0]);
        add(component[1]);//here the problem is
    }
    public static final int DEFAULT_WIDTH = 600;
    public static final int DEFAULT_HEIGHT = 400;
}

class DrawComponent extends JComponent{
    private double left;
    private double top;
    private double width;
    private double height;
    public DrawComponent(double l, double t, double w, double h){
        left = l;
        top = t;
        width = w;
        height = h;
    }
    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        Rectangle2D rect = new Rectangle2D.Double(left, top, width, height);
        g2.draw(rect);
        g2.setPaint(Color.BLUE);
        g2.fill(rect);
    }
}

这是我的代码,并不复杂。但是当我尝试绘制两个组件时,窗口只绘制一个。这段代码,当我摆脱第一个组件时,窗口将绘制第二个组件。我在javadocs中查找了JFrame.add方法,但没有找到错误,PLZ帮帮我

1 个答案:

答案 0 :(得分:5)

问题是您使用JFrame的默认布局管理器BorderLayout。当你add第二个组件时,它将取代第一个组件。 (两者都被添加到CENTER单元格。)

如果你想使用组件来显示方框,我建议你把它们放在一起,不要重叠。

否则我建议你在同一个组件上绘制所有框。