在Java GUI中动态调整2D绘图框的大小

时间:2012-11-28 01:08:06

标签: java swing user-interface awt

我正在通过Java GUI编写图形计算器(是的,我知道已经存在这样的库),当用户键入函数I.E. x ^ 6,我希望drawbox根据最小值和最大值自动调整大小。

例如,如果用户从-4到4输入x ^ 2,我的最小值为0,最大值为16,所以我想在框中显示整个图形,并正确调整大小。现在图表非常小,如果我使用x ^ 6作为多项式,它看起来非常狭窄。

这就是我在的地方。

    Graphics2D g2 = (Graphics2D) g;
    double myStart1 = Double.parseDouble(myStart);
    double myEnd1 = Double.parseDouble(myEnd);
    g2.translate(getWidth() / 2, getHeight() / 2);
    g2.scale(5.0, 5.0);
    g2.draw(new Line2D.Double( -myStart1 * 100,0,  -myEnd1 * 100,0));
    if (min < 0) {
        g2.draw(new Line2D.Double(0, -min * 100, 0, -max * 100));
    } else {
        g2.draw(new Line2D.Double(0, min * 100, 0, -max * 100));
    }
    g2.setColor(Color.RED);
    for (int i = 0; i < x.length; i++) {
        if (i + 1 < x.length) {
            g2.draw(new Line2D.Double(x[i], -y[i], x[i + 1], -y[i + 1]));

        } else {
            break;
        }
    }

}

1 个答案:

答案 0 :(得分:2)

至少考虑JFreeChart,它会缩放以填充封闭ChartPanel的首选大小,并支持通过右键单击或鼠标滚轮进行缩放。

附录:如果外部图书馆被禁止,SineTest,引用here,可能是一种方法。

enter image description here

import java.awt.Dimension;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/** @see https://stackoverflow.com/a/13597045/230513 */
public class ChartPanelTest {

    private static final Random random = new Random();

    private static XYDataset createDataset() {

        final XYSeries series = new XYSeries("Data");
        for (double x = -4; x < 4.01; x += 0.1) {
            series.add(x, Math.pow(x, 6d));
        }
        return new XYSeriesCollection(series);
    }

    private static JFreeChart createChart(final XYDataset dataset) {
        JFreeChart chart = ChartFactory.createXYLineChart(
            "f(x) = x^6", "x", "y", dataset,
            PlotOrientation.VERTICAL, false, false, false);
        return chart;
    }

    public static void main(String[] args) {

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        XYDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart) {

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
        chartPanel.setMouseWheelEnabled(true);
        f.add(chartPanel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}