怎么用java swing制作一个柱状图

来源:互联网 发布:什么自拍软件最好 编辑:程序博客网 时间:2024/04/29 12:40

第一步必须添加好jfreechart插件,然后把jar包导入工程中

第二步明确柱状图的横坐标和纵坐标

第三步开始使用jfreechart模板例子

程序如下

package curent;
import java.awt.Font;


import javax.swing.JPanel;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;


public class JFreeChartTest2 extends ApplicationFrame
{
    public JFreeChartTest2(String title)
    {
        super(title);
        this.setContentPane(createPanel()); //构造函数中自动创建Java的panel面板
    }
    
    public static CategoryDataset createDataset() //创建柱状图数据集
    {
        DefaultCategoryDataset dataset=new DefaultCategoryDataset();
        dataset.setValue(10,"1","一次");
        dataset.setValue(20,"2","二次");
        dataset.setValue(30,"3","三次");
        dataset.setValue(15,"4","四次");
        dataset.setValue(10,"5","五次");
        dataset.setValue(20,"6","六次");
        dataset.setValue(30,"7","七次");
        dataset.setValue(15,"8","八次");
        dataset.setValue(10,"9","九次");
        dataset.setValue(20,"10","十次");
  
        return dataset;
    }
    
    public static JFreeChart createChart(CategoryDataset dataset) //用数据集创建一个图表
    {
        JFreeChart chart=ChartFactory.createBarChart("hi", "谐波次数", 
                "谐波电压值", dataset, PlotOrientation.VERTICAL, true, true, false); //创建一个JFreeChart
        chart.setTitle(new TextTitle("谐波显示画面",new Font("宋体",Font.BOLD+Font.ITALIC,40)));//可以重新设置标题,替换“hi”标题
        CategoryPlot plot=(CategoryPlot)chart.getPlot();//获得图标中间部分,即plot
        CategoryAxis categoryAxis=plot.getDomainAxis();//获得横坐标
        categoryAxis.setLabelFont(new Font("微软雅黑",Font.BOLD,10));//设置横坐标字体
        categoryAxis.setMaximumCategoryLabelWidthRatio(2f);
        categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
        return chart;
    }
    
    public static JPanel createPanel()
    {
        JFreeChart chart =createChart(createDataset());
        return new ChartPanel(chart); //将chart对象放入Panel面板中去,ChartPanel类已继承Jpanel
    }
    
    public static void main(String[] args)
    {
        JFreeChartTest2 chart=new JFreeChartTest2("显示界面");
        chart.pack();//以合适的大小显示
        chart.setVisible(true);
        
    }
}

原创粉丝点击