在我的程序中,我想绘制一个简单的得分趋势图。我有一个文本文件,每一行都是一个整数分数,我读入并想将其作为参数传递给我的图表类。我在实现图表类方面遇到了一些困难,我看到的所有示例都将其方法放在与main函数相同的类中,但我没有这样做。
我希望能够将我的数组传递给对象并生成图表,但是当调用我的paint方法时,它要求我提供一个Graphics g...以下是我目前的代码:
我希望能够将我的数组传递给对象并生成图表,但是当调用我的paint方法时,它要求我提供一个Graphics g...以下是我目前的代码:
public class Graph extends JPanel {
public void paintGraph (Graphics g){
ArrayList<Integer> scores = new ArrayList<Integer>(10);
Random r = new Random();
for (int i : scores){
i = r.nextInt(20);
System.out.println(r);
}
int y1;
int y2;
for (int i = 0; i < scores.size(); i++){
y1 = scores.get(i);
y2 = scores.get(i+1);
g.drawLine(i, y1, i+1, y2);
}
}
}
现在,我已经插入了一个简单的随机数生成器来填充我的数组。
我有一个现有的框架,基本上想要实例化Graph类并将面板挂载到我的框架上。顺便说一句,很抱歉这个问题看起来有点混乱,但我睡得很少...
我的主语句中的代码是:
testFrame = new JFrame();
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graph graph = new Graph();
testFrame.add(graph);
我不确定SSCE的确切含义,但这是我的一次尝试:
public class Test {
JFrame testFrame;
public Test() {
testFrame = new JFrame();
testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graph graph = new Graph();
testFrame.add(graph);
testFrame.setBounds(100, 100, 764, 470);
testFrame.setVisible(true);
}
Graph.java
public class Graph extends JPanel {
public Graph() {
setSize(500, 500);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D gr = (Graphics2D) g; // This is if you want to use Graphics2D
// Now do the drawing here
ArrayList<Integer> scores = new ArrayList<Integer>(10);
Random r = new Random();
for (int i : scores) {
i = r.nextInt(20);
System.out.println(r);
}
int y1;
int y2;
for (int i = 0; i < scores.size() - 1; i++) {
y1 = (scores.get(i)) * 10;
y2 = (scores.get(i + 1)) * 10;
gr.drawLine(i * 10, y1, (i + 1) * 10, y2);
}
}
}
get(i + 1)
时,你的代码不会抛出数组越界异常吗? - Hovercraft Full Of Eels