我正在實驗中練習繼承,其中我們要創建一個水平橢圓作爲「Shape1」,然後創建一個「Shape2」 Shape1繪製它的超類Shape1,然後在頂部繪製一個垂直橢圓以創建一個新的外觀形狀。在繼承和外觀(顏色/位置等)方面,形狀顯示效果很好,但是在運行程序時,框架寬度設置爲1000,高度設置爲700,但是如果將角框拖動到角落放大它,隨着我不斷拖動框架變大,形狀會一遍又一遍地重複。理想情況下,形狀應該保持在相對於框架大小的位置。我認爲這是發生的,因爲當我拖動框架變大時,系統會一遍又一遍地調用繪製方法,但我不確定發生了什麼或者如何修復它。有什麼建議麼?Java - 使用Graphics2D學習繼承,調整框架大小時重繪對象
所有課程均顯示如下:
Shape1:
public class Shape1 {
private double x, y, r;
protected Color col;
private Random randGen = new Random();
public Shape1(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
this.col = new Color(randGen.nextFloat(), randGen.nextFloat(), randGen.nextFloat());
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getR() {
return this.r;
}
public void draw(Graphics2D g2){
//Create a horizontal ellipse
Ellipse2D horizontalEllipse = new Ellipse2D.Double(x - 2*r, y - r, 4 * r, 2 * r);
g2.setPaint(col);
g2.fill(horizontalEllipse);
}
}
Shape2:
public class Shape2 extends Shape1 {
public Shape2(double x, double y, double r) {
super(x, y, r);
}
public void draw(Graphics2D g2) {
//Create a horizontal ellipse
Ellipse2D verticalEllipse = new Ellipse2D.Double(super.getX() - super.getR(),
super.getY() - 2*super.getR(),
2 * super.getR(), 4 * super.getR());
super.draw(g2);
g2.fill(verticalEllipse);
}
}
ShapeComponent:
public class ShapeComponent extends JComponent {
//Instance variables here
private Random coordGen = new Random();
private final int FRAME_WIDTH = 1000;
private final int FRAME_HEIGHT = 700;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Shape2 myShape = new Shape2(1 + coordGen.nextInt(FRAME_WIDTH), 1 + coordGen.nextInt(FRAME_HEIGHT), 20);
//Draw shape here
myShape.draw(g2);
}
}
ShapeViewer(凡JFrame的是科瑞編):
public class ShapeViewer {
public static void main(String[] args) {
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 700;
//A new frame
JFrame frame = new JFrame();
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Lab 5");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ShapeComponent component = new ShapeComponent();
frame.add(component);
//We can see it!
frame.setVisible(true);
}
}
public void paintComponent(Graphics g)在您調整大小時由java調用,因此新Shape2 myShape.draw(g2);, –