更新时间:2023-12-05 08:26:04
要具有在给定位置绘制圆的组件,请按照oracle
To have a component that draws a circle at a given location, properly override paintComponent
as explained in oracle's tutorial:
class PaintTimeUnit extends JPanel {
private final int xlocation, ylocation;
private static final int W = 500, H = 300, RADIUS = 50;
public PaintTimeUnit(int x, int y) {
xlocation = x;
ylocation = y;
setPreferredSize(new Dimension(W, H));
}
@Override
public void paintComponent(Graphics g) { //override paintComponent for custom painting
super.paintComponent(g); //call super
g.setColor(Color.RED); //set painting color
g.drawOval(xlocation, ylocation, RADIUS, RADIUS); //draw circle
}
}
但是,如建议的那样,***有一个可以画一堆圆的容器.
为此,您需要添加一个集合来存储所有要绘制的圆圈,例如
However, as advised, it may better to have a container that draws a bunch of circles.
To achieve it you need to add a collection to store all circles to be painted such as
List<Point> circleCenters== new ArrayList<>()
您还需要向该集合添加点:
You would also need to add points to that collection:
void addCircle(int centerX, int centerY){
circleCenters.add(new Point(centerX, centerY));
}
并让paintComponent
根据其存储的中心绘制圆:
and have paintComponent
draw circles based on their stored centers:
public void paintComponent(Graphics g) { //override paintComponent for custom painting
super.paintComponent(g); //call super
g.setColor(Color.RED); //set painting color
for(Point center : circleCenters){
g.drawOval(center.x, center.y, RADIUS, RADIUS); //draw circle
}
}
将它们放在一起:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
class PaintTimeUnit extends JPanel {
private final List<Point> circleCenters;
private static final int W = 500, H = 300, RADIUS = 50;
public PaintTimeUnit() {
circleCenters = new ArrayList<>();
setPreferredSize(new Dimension(W, H));
}
@Override
public void paintComponent(Graphics g) { //override paintComponent for custom painting
super.paintComponent(g); //call super
g.setColor(Color.RED); //set painting color
for(Point center : circleCenters){
g.drawOval(center.x, center.y, RADIUS, RADIUS); //draw circle
}
}
void addCircle(int centerX, int centerY){
circleCenters.add(new Point(centerX, centerY));
}
}
并使用它:
PaintTimeUnit ptu= new PaintTimeUnit();
//add 3 circles
ptu.addCircle(90,90);
ptu.addCircle(150,150);
ptu.addCircle(210,90);