gpt4 book ai didi

java - 尝试使用图形 2d 创建饼图需要帮助访问数组列表

转载 作者:行者123 更新时间:2023-12-01 11:07:56 24 4
gpt4 key购买 nike

所以我有两个文件,我想从第一个文件访问一个变量,并在绘制饼图的第二个文件中使用它。

import java.util.*;
import java.lang.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;

public class Main {

public static void main(String[] args) throws FileNotFoundException {
File file = new File(args[0]);
Scanner input = new Scanner(file);
//int i = 0;
ArrayList<Integer> slices = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
while (input.hasNextLine()) {
names.add(input.next());
slices.add(input.nextInt());
}
JFrame f = new JFrame("Pie chart");
f.setSize(600, 350);
f.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
f.add(new PieChart());
f.setVisible(true);
}
}

这是我的第二个文件

import java.awt.*;
import javax.swing.*;

public class PieChart
extends JComponent {

public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
Graphics2D g3 = (Graphics2D) g.create();
g3.setColor(Color.BLACK);
g2.setColor(Color.BLUE);
for (int i = 0; i < 4; i = i + 1) {
g2.fillRect(230, 20 * i + 50 , 20, 20);
g3.drawString(names.get(i), 255, 20 * i + 65);
g3.drawString("37.0%", 385, 20 * i + 65);
}
g2.fillArc(50, 50, 150, 150, 0, 360);
}
}

这是我遇到的错误...
error

我正在尝试从文本文件读取到两个单独的数组中。我想要一个列表来保存名称,然后用一个列表来保存值。然后我希望能够从第二个文件访问数组中的值。

最佳答案

您可以将名称传递给PieChart构造函数。改变

f.add(new PieChart());

某些东西(假设您也需要切片),例如

f.add(new PieChart(slices, names));

并在PieChart中添加本地slicesnames字段以及构造函数。类似的东西

private List<Integer> slices;
private List<String> names;
public PieChart(List<Integer> slices, List<String> names) {
this.slices = slices;
this.names = names;
}

关于java - 尝试使用图形 2d 创建饼图需要帮助访问数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729817/

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