java 如何更改 JFreeChart 的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10274357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:20:15  来源:igfitidea点击:

How do I change a JFreeChart's size

javaswinglayoutjfreechartsizing

提问by R Doolabh

I've added a JFreeChartto a JPanel(using a BorderLayout), and it's huge. Is there something I can do to make it smaller?

我已将 a 添加JFreeChart到 a JPanel(使用 a BorderLayout),并且它很大。有什么我可以做的让它变小吗?

public void generateChart()
{
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    //set the values of the chart
    for(int i=0; i<8; i++)
    {
        dataset.setValue(income_array[i], "Income",
            Double.toString(percent_array[i]));
    }

    JFreeChart chart = ChartFactory.createBarChart(
        "Required Annual Income for a Variety of Interest Rates",
        "Percent", "Income", dataset, PlotOrientation.VERTICAL,
        false,true, false);
    ChartPanel cp = new ChartPanel(chart);

    chart.setBackgroundPaint(Color.white);
    chart.getTitle().setPaint(Color.black); 
    CategoryPlot p = chart.getCategoryPlot(); 
    p.setRangeGridlinePaint(Color.blue); 

    //cp.setMaximumDrawHeight(5);
    //cp.setMaximumDrawWidth(5);
    //cp.setZoomOutFactor(.1);
    JPanel graph = new JPanel();
    graph.add(cp);
    middle.add(graph, BorderLayout.CENTER);
}   

回答by trashgod

When you create your ChartPanel, you have several options that affect the result:

创建 时ChartPanel,您有几个影响结果的选项:

  1. Accept the DEFAULT_WIDTHand DEFAULT_HEIGHT: 680 x 420.

  2. Specify the preferred widthand heightin the constructor.

  3. Invoke setPreferredSize()explicitly if appropriate.

  4. Override getPreferredSize()to calculate the size dynamically.

    @Override
    public Dimension getPreferredSize() {
        // given some values of w & h
        return new Dimension(w, h);
    }
    
  5. Choose the layoutof the container to which the ChartPanelwill be added. Note that the default layout of JPanelis FlowLayout, while that of JFrameis BorderLayout. As a concrete example, ThermometerDemouses both preferred values in the constructor and a GridLayoutfor the container to allow dynamic resizing.

  1. 接受DEFAULT_WIDTHDEFAULT_HEIGHT:680 x 420。

  2. 在构造函数中指定首选widthheight

  3. setPreferredSize()如果合适,显式调用。

  4. 覆盖getPreferredSize()以动态计算大小。

    @Override
    public Dimension getPreferredSize() {
        // given some values of w & h
        return new Dimension(w, h);
    }
    
  5. 选择将添加到的容器的布局ChartPanel。请注意,默认布局JPanelFlowLayout,而默认布局JFrameBorderLayout。作为一个具体的例子,ThermometerDemo在构造函数中使用首选值并GridLayout在容器中使用a以允许动态调整大小。

image

图片

回答by Paul Efford

In addition to answer "4" of @trashgod, I had the same problem and managed to solve it like this: (1) create a custom class which extends JPanel (2) get the size somehow, that you would like to pass to your chart (3) create a method which returns a "ChartPanel" object like this:

除了回答@trashgod 的“4”之外,我也遇到了同样的问题并设法解决了这个问题:(1)创建一个扩展 JPanel 的自定义类(2)以某种方式获取大小,你想传递给你的图表 (3) 创建一个返回“ChartPanel”对象的方法,如下所示:

ChartPanel chart() {
    //... custom code here
    JFreeChart chart = ChartFactory.createPieChart(title, pieDataset, false, false, false );`enter code here`
    // Now: this is the trick to manage setting the size of a chart into a panel!:
    return new ChartPanel(chart) { 
        public Dimension getPreferredSize() {
            return new Dimension(width, height);
        }
    };
}

I prepared a SSCCE to let you know how it works:

我准备了一个 SSCCE 让你知道它是如何工作的:

import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

public class MyPieChart extends JPanel {

    public static void main(String[] args) {
        example1();
        example2();
        example3();
    }

    public static void example1() {
        JPanel panel = new JPanel();
        panel.setBounds(50, 80, 100, 100);
        MyPieChart piePanel = new MyPieChart("Example 1", dataset(), panel);
        panel.add(piePanel);
        JFrame frame = new JFrame();
        frame.setLayout(null); 
        frame.setBounds(10, 10, 200, 300);
        frame.add(panel);
        frame.setVisible(true);
    }

    public static void example2() {
        MyPieChart piePanel = new MyPieChart("Example 2", dataset(), 30, 50, 100, 100);
        JFrame frame = new JFrame();
        frame.setLayout(null); 
        frame.setBounds(210, 10, 200, 300);
        frame.add(piePanel);
        frame.setVisible(true);
    }

    public static void example3() {
        MyPieChart piePanel = new MyPieChart("Example 3", dataset(), 100, 100);
        piePanel.setLocation(0,0);
        JFrame frame = new JFrame();
        frame.setLayout(null); 
        frame.setBounds(410, 10, 200, 300);
        frame.add(piePanel);
        frame.setVisible(true);
    }

    static ArrayList<ArrayList<String>> dataset() {
        ArrayList<ArrayList<String>> dataset = new ArrayList<ArrayList<String>>();
        dataset.add(row( "Tom", "LoggedIn", "Spain" ));
        dataset.add(row( "Jerry", "LoggedOut", "England" ));
        dataset.add(row( "Gooffy", "LoggedOut", "France" ));
        return dataset;
    }

    static ArrayList<String> row(String name, String actualState, String country) {
        ArrayList<String> row = new ArrayList<String>();
        row.add(name); row.add(actualState); row.add(country); 
        return row;
    }

    ArrayList<ArrayList<String>> dataset;
    DefaultPieDataset pieDataset = new DefaultPieDataset(); 
    int width, height, posX, posY;
    int colState = 1;
    String title;
    String LoggedIn = "LoggedIn";
    String LoggedOut = "LoggedOut";

    public MyPieChart(String title, ArrayList<ArrayList<String>> dataset, int...args) {

        if(args.length==2) {
            this.width = args[0];
            this.height = args[1];
            this.setSize(width, height);
        }
        else if(args.length==4) {
            this.posX = args[0];
            this.posY = args[1];
            this.width = args[2];
            this.height = args[3];
            this.setBounds(posX, posY, width, height);
        }
        else {
            System.err.println("Error: wrong number of size/position arguments");
            return;
        }

        this.title = title;
        this.dataset = dataset;
        this.add(chart());
    }

    public MyPieChart(String title, ArrayList<ArrayList<String>> dataset, JPanel panel) {
        this.title = title;
        this.dataset = dataset;
        this.width = panel.getWidth();
        this.height = panel.getHeight();
        this.setBounds(panel.getBounds());
        this.add(chart());
    }

    ChartPanel chart() {

        int totalLoggedIn = 0;
        int totalLoggedOut = 0;

        for(ArrayList<String> user : dataset) {
            if(user.get(colState).equals(LoggedIn)) totalLoggedIn++;
            else totalLoggedOut++;
        }
        pieDataset.clear();
        pieDataset.setValue(LoggedIn +": "+ totalLoggedIn, totalLoggedIn);
        pieDataset.setValue(LoggedOut +": "+ totalLoggedOut, totalLoggedOut);

        JFreeChart chart = ChartFactory.createPieChart(title, pieDataset, false, false, false );

        return new ChartPanel(chart) { // this is the trick to manage setting the size of a chart into a panel!
            public Dimension getPreferredSize() {
                return new Dimension(width, height);
            }
        };
    }
}

I really hope it helps!

我真的希望它有帮助!

回答by StarSweeper

I had a problem with my pie chart being too big with BorderLayout too. I ended up solving my problem by converting the chart to an image instead.

我的饼图在 BorderLayout 上也太大了。我最终通过将图表转换为图像来解决我的问题。

Beforeenter image description here

在此处输入图片说明

Afterenter image description here

在此处输入图片说明

Code

代码

 private PieDataset updateCSFDataSet(){
        DefaultPieDataset dataSet = new DefaultPieDataset();
            dataSet.setValue("Clear(" + clearCount + ")" , clearCount);
            dataSet.setValue("Smoky(" + smokyCount + ")", smokyCount);
            dataSet.setValue("Foggy(" + foggyCount + ")", foggyCount);
            dataSet.setValue("Skipped(" + skipCount + ")", skipCount);
            dataSet.setValue("Unlabeled(" + unlabeledCount + ")", unlabeledCount);
        return dataSet;
    }

    private ImageIcon createChart(String title, PieDataset dataSet){
        JFreeChart chart = ChartFactory.createPieChart(
                title,
                dataSet,
                true,
                false,
                false
        );

        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
        plot.setNoDataMessage("No data available");
        plot.setCircular(true);
        plot.setIgnoreZeroValues(true);
        plot.setLabelGap(0.02);

        return new ImageIcon(chart.createBufferedImage(400,300));
    }

回答by Brendan Cutajar

Try setting the size of the Panel your chart is in.

尝试设置图表所在面板的大小。

You might need to set both JPanel middle and ChartPanel cp

您可能需要同时设置 JPanel middle 和 ChartPanel cp