我在从我创建的 ArrayList 中绘制组件时遇到了一些麻烦。如果我搞砸了,我可以得到第一个元素或第二个元素,如果我幸运的话,也不会出现!
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class FaceShortCode {
ArrayList<CreateCircles> faceCircles = new ArrayList<CreateCircles>();
public FaceShortCode() {
JFrame main = new JFrame();
main.setTitle("Face Frame");
main.setSize(new Dimension(600, 600));
main.setLocationRelativeTo(null);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
Container c = main.getContentPane();
// c.setLayout(null);
faceCircles.add(0, new CreateCircles(100, 50, 400, 350, Color.red));
faceCircles.add(1, new CreateCircles(200, 100, 65, 65, Color.black));
c.add(faceCircles.get(0));
c.add(faceCircles.get(1));
}
class CreateCircles extends JComponent {
double x, y, width, height;
Color myColor;
public CreateCircles(double x, double y, double width, double height,
Color myColor) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.myColor = myColor;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(x, y, width, height);
g2.setColor(myColor);
g2.fill(circle);
}
}
static class Run {
public static void main(String[] args) {
new FaceShortCode();
}
}
}
我尝试在每次添加到 Container c 后加入 main.repaint(),在我的绘画方法中尝试了 repaint(),但似乎没有任何效果。还有其他东西可以放置我刚刚丢失的 repaint() 吗?