我正在尝试使用Java2D进行一些简单的图形编程。我开始很容易,只是尝试在JFrame中显示几个圆圈。我成功显示了一个圆,但是添加第二个圆时,仅显示添加到JFrame的最后一个圆。我使用Circle类来定义我的圈子并覆盖用于显示它的paintComponent方法。关于我可能做错了什么的任何建议将不胜感激。下面提供了我的Circle和DancingCircles类的代码,以供参考。
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
/**
*
* @author Paul
*/
public class Circle extends JPanel {
// Data members for Circle center and radius
private double centerX, centerY;
private double radius;
// No-argument constructor
Circle() {
centerX = 200;
centerY = 200;
radius = 10;
}
// Full-argument constructor
Circle( double x, double y, double r) {
centerX = x;
centerY = y;
radius = r;
}
// Draw a Circle
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//Convert to Java2D Object
Graphics2D g2 = (Graphics2D) g;
// Create the circle
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
// Draw it
g2.draw(circle);
}// end paintComponent
// Get/set data members
public void setCenterX(double x){this.centerX = x;}
public void setCenterY(double y){this.centerY = y;}
public void setRadius(double r){radius = r;}
public double getCenterX(){return centerX;}
public double getCenterY(){return centerY;}
public double getRadius(){return radius;}
}// end class Circle
import java.awt.*;
import javax.swing.*;
/**
*
* @author Paul
*/
public class DancingCircles extends JFrame{
// Display Dimensions
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
// Default constructor
private DancingCircles() {
setTitle("Dancing Circles");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Add Circles to JFrame
Circle myCircle = new Circle(200.0, 200.0, 20.0);
add(myCircle); // Add circle to frame
Circle myCircle2 = new Circle(100.0, 100.0, 30.0);
add(myCircle2); // Add circle to frame
}// end DancingCircles
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DancingCircles dc = new DancingCircles();
dc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dc.setVisible(true);
}
});
}// end main
}
谢谢!
保罗
最佳答案
这样做的方法是从circle类中删除绘制方法,并创建一个带有多个圆的单个面板:
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.*;
public class Circles extends JPanel
{
ArrayList<Circle> circles = new ArrayList<Circle>();
public void add(Circle circle) {
circles.add(circle);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Circle circle: circles) {
Ellipse2D circle2D = new Ellipse2D.Double();
circle2D.setFrameFromCenter(
circle.getCenterX(),
circle.getCenterY(),
circle.getCenterX() + circle.getRadius(),
circle.getCenterY() + circle.getRadius());
g2.draw(circle2D);
}
}
}