在JComponent中只显示一个对象

时间:2012-02-11 20:50:53

标签: java jcomponent graphic

嘿伙计们,对不起,我对编程很陌生,但我的BarChart程序遇到了一个小问题。一切似乎都运行正常。我想要做的是输入几个整数,然后让我的程序生成图像来表示数据上的表格。如果我输入几个数字,则只显示一个图像。请帮帮我!

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

1 个答案:

答案 0 :(得分:1)

int x = 10;

这应该移出for循环。它每次都被初始化为相同的值,因此所有条形都在同一个地方绘制。

如果您刚刚在for循环中添加了System.out.println(x);,则问题就很明显了。