0
嘿,夥計們,對不起,我對編程很陌生,但是我的BarChart程序存在一個小問題。一切似乎都運行良好。我想要做的是輸入一些整數,然後讓我的程序生成圖像來表示數據表單。如果輸入幾個數字,則只會顯示一個圖像。請幫助我!在JComponent中只有一個對象正在顯示
PS。我知道我可以在我的BarChart類中使用paintcomponent方法,但是我的教授專門只想在這個類中使用這兩種方法。
import javax.swing.JFrame;
import java.util.Scanner;
public class BarChartTester
{
public static void main(String[] args)
{
BarChartPaintComponent component = new BarChartPaintComponent();
Scanner in = new Scanner(System.in);
BarChart test = new BarChart();
System.out.println("Enter the Values you wish to use (>0). Press -1 on an empty line to stop");
Boolean flag = false;
while(!flag)
{
double numbers = in.nextDouble();
if(numbers == -1)
flag = true;
else if(numbers<-1)
System.out.println("You have typed in invalid number");
else
component.add(numbers);
}
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setTitle("A Bar Graph");
frame.add(component);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.*;
import javax.swing.JComponent;
import java.util.ArrayList;
public class BarChart extends JComponent
{
private ArrayList<Double> list;
private double value;
private int i;
public BarChart()
{
list = new ArrayList<Double>();
}
public void add(double value)
{
list.add(i, value);
i++;
}
public void draw(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Double greatest = list.get(0);
Double least;
for(int j =1;j<list.size();j++)
{
if(list.get(j)> greatest)
greatest = list.get(j);
else
least = list.get(j);
}
for(int i = 0;i<list.size();i++)
{
int x = 10;
int width = 20;
double barNumber = list.get(i);
if(barNumber == greatest){
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,0,width,300));
}
else
{
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,0,width, barNumber));
}
x +=20;
}
}
}
import java.awt.Graphics;
import java.awt.Graphics2D;
public class BarChartPaintComponent extends BarChart
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
this.draw(g);
}
}
謝謝!我不覺得這很愚蠢。欣賞它 – James 2012-02-11 21:12:27