简体   繁体   中英

How to make JFreeChart to keep aspect ratio?

Is it possible to keep some aspect ratio of units? For example, is it possible to make them square?

In the following example a rectangle draw. Unfortunately, it is possible to make it square by resizing window. Is it possible to tell JFreeChart to keep ratio while resizing?

package tests.org.jfree.chart;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.DefaultXYDataset;

public class Runner_JFreeChart_01 {

    public static class MyChartPanel extends ChartPanel {

        private static final long serialVersionUID = 8474384653351996554L;

        DefaultXYDataset dataset = new DefaultXYDataset();
        {
            dataset.addSeries("key", new double[][]{{10, 300, 300, 10, 10},{10, 10, 50, 50, 10}});
        }

        JFreeChart chart = ChartFactory.createXYLineChart("", "", "", dataset);

        public MyChartPanel() {
            super(null);
            setChart(chart);
        }

    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Runner_JFreeChart_01");
                frame.add(new MyChartPanel());

                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

            }
        });


    }

}

result:

在此处输入图片说明

In your main try adding the following code and see if it works.

 public static void main(String[] args) { 
     MyChartPanel myChart = new MyChartPanel();
     myChart.setMinimumDrawWidth(0);
     myChart.setMaximumDrawWidth(Integer.MAX_VALUE);
     myChart.setMinimumDrawHeight(0);
     myChart.setMaximumDrawHeight(Integer.MAX_VALUE);

      // Other code here

Then where you add your chart to the JFrame: replace the following code:

frame.add(new MyChartPanel());

with

frame.add(myChart);

Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM