我使用了垃圾邮件建议的 getPreferredSize() 方法。我扩展org.jfree.chart.MouseWheelHandler
并实现了一个新的 handleZoomable 方法,如下所示。
package org.jfree.chart;
import java.awt.Dimension;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Point2D;
import java.io.Serializable;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.Zoomable;
/** http://stackoverflow.com/questions/17908498/jfreechart-auto-resize-on-zoom */
class MouseWheelHandlerResize extends MouseWheelHandler {
/** The chart panel. */
private ChartPanel chartPanel;
/** The zoom factor. */
double zoomFactor;
/** minimum size */
final int MIN_SIZE = 300;
/** maximal size */
final int MAX_SIZE = 20000;
public MouseWheelHandlerResize(ChartPanel chartPanel) {
super(chartPanel);
this.chartPanel = chartPanel;
this.zoomFactor = 0.05;
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
JFreeChart chart = this.chartPanel.getChart();
if (chart == null) {
return;
}
Plot plot = chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable zoomable = (Zoomable) plot;
handleZoomable(zoomable, e);
}
else if (plot instanceof PiePlot) {
PiePlot pp = (PiePlot) plot;
pp.handleMouseWheelRotation(e.getWheelRotation());
}
}
private void handleZoomable(Zoomable zoomable, MouseWheelEvent e) {
// don't zoom unless the mouse pointer is in the plot's data area
ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();
PlotRenderingInfo pinfo = info.getPlotInfo();
Point2D p = this.chartPanel.translateScreenToJava2D(e.getPoint());
if (!pinfo.getDataArea().contains(p)) {
return;
}
Plot plot = (Plot) zoomable;
// do not notify while zooming each axis
boolean notifyState = plot.isNotify();
plot.setNotify(false);
int clicks = e.getWheelRotation();
double zf = 1.0 + this.zoomFactor;
if (clicks < 0) {
zf = 1.0 / zf;
}
final Dimension dim = this.chartPanel.getPreferredSize();
this.chartPanel.setPreferredSize(new Dimension((int)(Math.min(Math.max(MIN_SIZE, dim.width)*zf, MAX_SIZE)), (int)(dim.height)));
this.chartPanel.validate();
this.chartPanel.updateUI();
plot.setNotify(notifyState); // this generates the change event too
}
}
在org.jfree.chart.ChartPanel
课堂上,我刚刚将setMouseWheelEnabled
方法修改为:
public void setMouseWheelEnabled(boolean flag) {
if (flag && this.mouseWheelHandler == null) {
this.mouseWheelHandler = new MouseWheelHandlerResize(this);
}
else if (!flag && this.mouseWheelHandler != null) {
removeMouseWheelListener(this.mouseWheelHandler);
this.mouseWheelHandler = null;
}
}
现在,位于滚动视图中的 CharPanel 会调整大小并放大。