1
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);
}
}
這是我的代碼,它並不複雜。但是當我嘗試繪製兩個組件時,窗口只繪製一個。這段代碼,當我擺脫第一個組件時,窗口將繪製第二個組件。我已經看過了在的javadoc JFrame.add的方法,但沒有發現什麼錯誤,plz幫助我在JFrame中看不到一個組件
哦,thx非常。我再次忘記this.thx – cloud