gpt4 book ai didi

java - 使用 ArrayList 绘图时遇到问题

转载 作者:行者123 更新时间:2023-12-01 04:11:02 26 4
gpt4 key购买 nike

我在从我创建的 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();
}
}

}

我尝试在每次添加到容器 c 后添加一个 main.repaint() ,在我的绘画方法中尝试了一个 repaint() 但似乎没有任何效果。还有其他东西可以放置我刚刚缺少的 repaint() 吗?

最佳答案

您需要将所有逻辑放在 setVisible() 之前,否则您的框架将在执行逻辑之前变得可见。

public FaceShortCode() {

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));

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);
}

考虑使 FaceShortCode 扩展 JFrame

public class FaceShortCode extends JFrame {
private ArrayList<CreateCircles> faceCircles = new ArrayList<CreateCircles>();

public FaceShortCode {
setLayout(new Girdlayout(1, 2));

faceCircles.add(0, new CreateCircles(100, 50, 400, 350, Color.red));
faceCircles.add(1, new CreateCircles(200, 100, 65, 65, Color.black));

add(faceCircles.get(0));
add(faceCircles.get(1))

setTitle("Face Frame");
setSize(new Dimension(600, 600));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}

关于java - 使用 ArrayList 绘图时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com