1. 程式人生 > >怎麼用java swing製作一個柱狀圖

怎麼用java swing製作一個柱狀圖

第一步必須新增好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);
        
    }
}