用Java创建简单的条形图 - 读取数据和输出条形图 [英] Creating a Simple Bar Chart in Java - Reads Data and Outputs Bar Graph

查看:140
本文介绍了用Java创建简单的条形图 - 读取数据和输出条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我的一个项目创建一个简单的条形图。该程序需要输入1到9个大于零的整数。然后程序需要显示一个非常简单的条形图,条上方显示整数。我的教授没有很好地向我解释这个程序,这是第一次使用图形。



该程序需要:

一个类SimpleBarChart(它将扩展Frame)与私有变量Bar [] bars和int [] inputData等(如私人图形g,私人诠释windowWid,windowHt等)和以下功能。它还使用了一个辅助类Bars:

  class Bar 
{public int height,width,value,nix ,nwy;
public Bar(){}
public Bar(int height,int width,int value,int nix,int nwy)
{this.height = height;接下来是一个构造函数SimpleBarChart(),它调用readData(),createBars(),getBars(),getBars ()和drawBars()。

函数private void readData(),读取条形图的inputData。使用下面给出的代码,它使用JOptionPane。

一个函数private void createBars()在分配宽度,高度,值(bars [i] .value = inputData [i]),nix时创建bars数组,和每个酒吧的nwy。在显示窗口的顶部和底部需要25个像素的空间,条形之间需要10个像素,并且必须允许条形高度缩放为inputData项的形式。



最后一个函数private void drawBars()来绘制酒吧,一次一个酒吧之间适当的睡眠时间,两种不同的颜色。需要使用g.drawString(+ b.value,nix + b.width / 2,nwy - 10)来标记每个小黑条的黑b值,它的顶部为10像素。


我一直试图弄清楚这一点,并且我迷路了。任何帮助将不胜感激!



继承我到目前为止的代码:

  package simplebarchart; 

import java.awt。*;
import java.awt.event。*;
import java.awt.Toolkit。*;
import javax.swing。*;
import java.io. *;
import java.util。*;


公共类SimpleBarchart扩展JFrame
{
private final int OUTER_MARGIN = 20;
私有静态最终颜色BACKGROUND_COLOR = Color.white;
private static final Color BAR_COLOR = Color.red;
private int SPACE_ON_LEFT_RIGHT;
private Image fImageBuffer;
private Insets fInsets;
私人图形g;
私人酒吧[]吧;
private static int SLEEP = 500;
private int [] inputData;


class Bar
{
private int height,value;
public int width;
public int nwx;
public int nwy;
公共颜色的颜色;
$ b $ public bar(){}
public Bar(int height,int width,int value,int nwx,int nwy)
{
this.height = height ;
this.width = width;
this.value = value;
this.nwx = nwx;
this.nwy = nwy;




public SimpleBarchart(final int [] inputData)
{
this.inputData = inputData;
addWindowListener(new WindowCloser());
fInsets = getInsets();
setSize(WIDTH + fInsets.left + fInsets.right,HEIGHT + fInsets.top + fInsets.bottom);
setTitle(条形图);
if(((fImageBuffer = createImage(WIDTH,HEIGHT))== null)||
((g = fImageBuffer.getGraphics())== null))
System.exit 1);
readData();
createBars();
getContentPane()。add(new SimpleBarchart(inputData),BorderLayout.CENTER);
setVisible(true);

$ b / **
*
* @param g
* /
protected void paintComponent(final Graphics g){
g.drawImage(fImageBuffer,fInsets.left,fInsets.top,null);
}

类WindowCloser扩展WindowAdapter
{
@Override
public void windowClosing(WindowEvent e)
{
System。出口(0);



private void readData()
{
String [] inputItems = JOptionPane.showInputDialog(Enter 1 to 9 integers> 0 ).trim()。split(+);
int numData = inputItems.length;
inputData = new int [numData];
$ b $ for(int itemIndex = 0; itemIndex< inputItems.length; itemIndex ++)
inputData [itemIndex] = numData;


}

private void createBars()
{

//我对如何创建bar for这个程序。
//这个函数在显示窗口的顶部和底部需要25个像素的空间,在这些条之间有10个像素,并且必须允许条形高度被**缩放为inputData项的形式。

Bar [] bars = new Bar [];
int pixelBetweenBars = 25;
int width = 800 + 2 * OUTER_MARGIN;
int height = 600 + 2 * OUTER_MARGIN;



private void drawBars(final Graphics g)
{
int OUTER_MARGIN = 20,
WIDTH = 800 + 2 * OUTER_MARGIN ,
HEIGHT = 600 + 2 * OUTER_MARGIN;


g.setColor(BACKGROUND_COLOR);
g.fillRect(0,0,WIDTH,HEIGHT);

g.setColor(BAR_COLOR);
final int barWidth = 20;
for(int itemIndex = 0; itemIndex< inputData.length; itemIndex ++){
final int x = OUTER_MARGIN + 25 * itemIndex;
final int barHeight = 10 * inputData [itemIndex];
final int y = barHeight;
g.fillRect(x,y,barWidth,barHeight);



$ b public static void main(String [] args)
{
new SimpleBarchart;
}


解决方案

我同意 Uttesh Kumar that JFreeChart 是一个优秀的图表库,它投入时间学习它是非常值得的。但是,由于您正在执行此项目以了解更多关于图形的信息,因此最好自己编写图形。



首先几个一般性评论:




  • Bar 类被定义了两次,并且两个实现都没有被使用;
  • createImage([...],[...])。getGraphics()构造看起来相当奇特;
  • readData 方法读取空格分隔的数字列表,分配内存,但不存储数字(可以使用 Bar class here);
  • createBars 方法当前声明了三个尚未使用的局部变量(并且不执行任何操作 /painting/index.htmlrel =nofollow noreferrer>执行 Ma已推荐的自定义绘画教程dProgrammer ,定制绘画的常用方法是通过继承 JPanel 类并重写 paintComponent 方法。 学习这个简短的教程会让你的速度变得非常快,所以我非常同意这个建议!



    readData 方法,您可以添加几行来存储数字(并在之后切换到使用 Bar 类):

      for(int itemIndex = 0; itemIndex< inputItems.length; itemIndex ++)
    inputData [itemIndex] = [... get a来自inputItems字符串的数字在这里...];

    在构造函数中调用 readData 之后,你可以添加:
    $ b $ pre $ getContentPane()。add(new SimpleBarPanel(inputData),BorderLayout.CENTER);
    setVisible(true);

它使用一个新的 SimpleBarPanel 类,关心自定义绘画。 (如果要显示 SimpleBarPanel 绘画,< setVisible 的调用应该最后一次。)



SimpleBarPanel 类可能如下所示:

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

公共类SimpleBarPanel扩展JPanel {
private static final颜色BACKGROUND_COLOR = Color.white;
private static final Color BAR_COLOR = Color.red;

private int [] inputData;

public SimpleBarPanel(final int [] inputData){
this.inputData = inputData;

$ b @Override
protected void paintComponent(final Graphics g){
super.paintComponent(g);

drawBars(g);
}

private void drawBars(final Graphics g){
int / * i,* / OUTER_MARGIN = 20,
WIDTH = 800 + 2 * OUTER_MARGIN,
HEIGHT = 600 + 2 * OUTER_MARGIN;
/ * SPACE_BETWEEN_BARS = 10,SPACE_ON_TOP_BOTTOM = 25; * /

g.setColor(BACKGROUND_COLOR);
g.fillRect(0,0,WIDTH,HEIGHT);

g.setColor(BAR_COLOR);
final int barWidth = 20;
for(int itemIndex = 0; itemIndex< inputData.length; itemIndex ++){
final int x = OUTER_MARGIN + 25 * itemIndex;
final int barHeight = 10 * inputData [itemIndex];
final int y = [... y使用barHeight进行计算;酒吧越高,y越低];
g.fillRect(x,y,barWidth,barHeight);
}
}
}

祝您的项目顺利。

Im required to create a simple bar chart for one of my projects. This program requires an input of 1 to 9 integers that are greater than zero. The program is then required to display a very simple bar graph with the integers displayed above the bars. My professor did not explain this program very well to me and this is the first time working with graphics.

The program requires:

A class "SimpleBarChart" (which will extend Frame) with private variables Bar[] bars and int [] inputData among others (like private Graphics g, private int windowWid, windowHt, etc) and the following functions. It also uses an auxiliary class Bars as shown:

class Bar
{ public int height, width, value, nix, nwy;
  public Bar() {}
  public Bar(int height, int width, int value, int nix, int nwy)
  { this.height = height; etc }
}

Next a constructor SimpleBarChart(), which calls readData(), createBars(), and drawBars().

A function private void readData(), which reads inputData for the bar-chart. Use the code given below, which uses JOptionPane.

A function private void createBars() to create the bars array on assigning width, height, value (bars[i].value = inputData[i]), nix, and nwy of each bar. Requires 25 pixels of space on top and bottom of the display-window, 10 pixels between the bars, and has to allow bar-heights to be scaled to the form of inputData items.

Finally a function private void drawBars() to draw the bars, one at a time with a suitable sleep-time between bars, with two different colors. Requires the use of g.drawString("" +b.value, nix + b.width/2, nwy - 10) to label each bar in black b its value at 10 pixel above its top.

Ive been trying to figure this out all day and I'm lost. Any help would be greatly appreciated!

Heres what code I have so far:

package simplebarchart;

import java.awt.*;
import java.awt.event.*;
import java.awt.Toolkit.*;
import javax.swing.*;
import java.io.*;
import java.util.*;


public class SimpleBarchart extends JFrame
{
    private final int OUTER_MARGIN = 20;
    private static final Color BACKGROUND_COLOR = Color.white;
    private static final Color BAR_COLOR = Color.red; 
    private int SPACE_ON_LEFT_RIGHT;
    private Image fImageBuffer;
    private Insets fInsets;
    private Graphics g;
    private Bar[] bars;
    private static int SLEEP = 500;
    private int[] inputData;


class Bar
{
    private int height, value;
    public int width;
    public int nwx;
    public int nwy;
    public Color color;

    public Bar() {}
    public Bar(int height, int width, int value, int nwx, int nwy)
    {
        this.height = height;
        this.width = width; 
        this.value = value; 
        this.nwx = nwx;
        this.nwy = nwy;
    }

}


public SimpleBarchart(final int[] inputData)
{
    this.inputData = inputData;
    addWindowListener(new WindowCloser());
    fInsets = getInsets();
    setSize(WIDTH + fInsets.left + fInsets.right, HEIGHT + fInsets.top + fInsets.bottom);
    setTitle("Bar Chart");
    if (((fImageBuffer = createImage(WIDTH, HEIGHT)) == null) ||
            ((g = fImageBuffer.getGraphics()) == null))
            System.exit(1);
    readData();
    createBars();
    getContentPane().add(new SimpleBarchart(inputData), BorderLayout.CENTER);
    setVisible(true);
}

/**
 *
 * @param g
 */
protected void paintComponent(final Graphics g) {
    g.drawImage(fImageBuffer, fInsets.left, fInsets.top, null);
}

class WindowCloser extends WindowAdapter
{
    @Override
    public void windowClosing(WindowEvent e)
    {
        System.exit(0);
    }
}

private void readData()
{
    String[] inputItems = JOptionPane.showInputDialog("Enter 1 to 9 integers > 0").trim().split(" +");
    int numData = inputItems.length;
    inputData = new int[numData];

    for (int itemIndex = 0; itemIndex < inputItems.length; itemIndex++)
        inputData[itemIndex] = numData;


}

private void createBars()
{

//Im confused on how to create the bars for this program. 
//This function requires 25 pixels of space on top and bottom of the display-    window, 10 pixels between the bars, and has to allow bar-heights to be **scaled to the form of inputData items.** 

    Bar[] bars = new Bar[];
    int pixelBetweenBars = 25;
    int width = 800 + 2*OUTER_MARGIN;
    int height = 600 + 2*OUTER_MARGIN;

}

private void drawBars(final Graphics g)
{
            int OUTER_MARGIN = 20,
            WIDTH = 800 + 2 * OUTER_MARGIN,
            HEIGHT = 600 + 2 * OUTER_MARGIN;


    g.setColor(BACKGROUND_COLOR);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    g.setColor(BAR_COLOR);
    final int barWidth = 20;
    for (int itemIndex = 0; itemIndex < inputData.length; itemIndex++) {
        final int x = OUTER_MARGIN + 25 * itemIndex;
        final int barHeight = 10 * inputData[itemIndex];
        final int y = barHeight;
        g.fillRect(x, y, barWidth, barHeight);
    }
}


public static void main(String[] args) 
{
    new SimpleBarchart;
}

解决方案

I agree with Uttesh Kumar that JFreeChart is an excellent chart library and it really pays off to invest time into learning it. But since you are doing this project to learn more about graphics, it is probably better to code the drawing yourself.

First a few general remarks:

  • the Bar class is defined two times and both implementations are not used yet;
  • the createImage([...], [...]).getGraphics() construction looks rather exotic;
  • the readData method reads a space separated list of numbers, allocates memory, but does not store the numbers (you could use the Bar class here);
  • the createBars method currently declares three local variables that are not used yet (and does nothing else).

As shown in the Performing Custom Painting tutorial that was already recommended by MadProgrammer, a common approach to custom painting is by subclassing the JPanel class and overriding the paintComponent method. Studying this short tutorial will get you up to speed pretty quickly, so I really agree with this recommendation!

In the readData method, you could add a few lines to store the numbers (and switch to using the Bar class later):

for (int itemIndex = 0; itemIndex < inputItems.length; itemIndex++)
    inputData[itemIndex] = [...get a number from the inputItems string here...];

After the call to readData in the constructor, you could add:

getContentPane().add(new SimpleBarPanel(inputData), BorderLayout.CENTER);
setVisible(true);

This uses a new SimpleBarPanel class that takes care of the custom painting. (The call to setVisible should go last if you want the SimpleBarPanel painting to be shown.)

The SimpleBarPanel class could look like this:

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

public class SimpleBarPanel extends JPanel {
    private static final Color BACKGROUND_COLOR = Color.white;
    private static final Color BAR_COLOR = Color.red;

    private int[] inputData;

    public SimpleBarPanel(final int[] inputData) {
        this.inputData = inputData;
    }

    @Override
    protected void paintComponent(final Graphics g) {
        super.paintComponent(g);

        drawBars(g);
    }

    private void drawBars(final Graphics g) {
        int /*i,*/ OUTER_MARGIN = 20,
                WIDTH = 800 + 2 * OUTER_MARGIN,
                HEIGHT = 600 + 2 * OUTER_MARGIN;
                /*SPACE_BETWEEN_BARS = 10, SPACE_ON_TOP_BOTTOM = 25;*/

        g.setColor(BACKGROUND_COLOR);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        g.setColor(BAR_COLOR);
        final int barWidth = 20;
        for (int itemIndex = 0; itemIndex < inputData.length; itemIndex++) {
            final int x = OUTER_MARGIN + 25 * itemIndex;
            final int barHeight = 10 * inputData[itemIndex];
            final int y = [...y is calculated using barHeight; the higher the bar, the lower y should be...];
            g.fillRect(x, y, barWidth, barHeight);
        }
    }
}

Good luck with your project.

这篇关于用Java创建简单的条形图 - 读取数据和输出条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆