我是一名初学程序员,我试图让这个程序运行。尽管没有图像出现在JComponent的新Java屏幕上,但所有内容都能正确编译。这个程序假设要做的就是获取一个输入值并将其分配给条形图的大小值。在程序中我必须使用外部paintcomponent类来运行原始类,并且有一个驱动程序可能是什么让我失望。在此先感谢!
public class BarChartTester
{
public static void main(String[] args)
{
BarChartPaintComponent component = new BarChartPaintComponent();
Scanner in = new Scanner(System.in);
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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(component);
frame.setVisible(true);
}
}
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 = 20;
int width = 20;
double barNumber = list.get(i);
double size = barNumber;
if(list.get(i) == greatest){
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,300,width,300));
}
else
{
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,300,width, barNumber));
}
x +=20;
}
}
}
public class BarChartPaintComponent extends BarChart
{
public void paintComponent(Graphics g, double array){
Graphics2D g2 = (Graphics2D) g;
BarChart component= new BarChart();
component.add(array);
component.draw(g2);
}
}
答案 0 :(得分:2)
您的主要问题是,由于您没有实现paintComponent(Graphics g)方法,因此永远不会调用用于绘制的代码。因此,请将paintComponent替换为:
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
this.draw(g2);
}
然后进行史蒂文斯提出的更正。
此外,在第二个中,您正在初始化变量x(int x = 20)。这样,在循环的每次迭代中x都是20。在for循环之前执行此操作。