在将CategoryDataset的零值设置为非常大的数字后,我遇到了刷新/重新绘制BarChart的问题。
private class Test
extends ApplicationFrame {
private DefaultCategoryDataset set;
public Test(
String newTitle) {
super(newTitle);
set = new DefaultCategoryDataset();
set.addValue(0, "Test", "1");
JFreeChart barChart = ChartFactory.createBarChart(
"Test",
"Category",
"Score",
set,
PlotOrientation.VERTICAL,
true,
true,
false);
JPanel mainPanel = new JPanel(new GridLayout());
ChartPanel chartPanel = new ChartPanel(barChart);
chartPanel.setPreferredSize(new java.awt.Dimension(560, 367));
mainPanel.add(chartPanel);
JButton b = new JButton();
createDataset();
b.addActionListener(e -> {
set.setValue(Integer.MAX_VALUE, "Test", "1");
});
mainPanel.add(b);
setContentPane(mainPanel);
pack();
setVisible(true);
}
这是一个零值的图表。
将值设置为非常大的数字。
点击图表内部。
如何正确刷新图表?我试图重新绘制ChartPanel,但它没有用。
答案 0 :(得分:1)
确保在event dispatch thread上构建和操作仅的Swing GUI对象。此外,覆盖getPreferredSize()
,如图here所示,以确定图表的初始大小。在下面的变体中,请注意重复点击清除,零和更新按钮如何保持图表本身不变,同时更新数据集,绘图,范围轴和图例。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
/**
* @see https://stackoverflow.com/q/50854965/230513
*/
public class Test {
private final DefaultCategoryDataset set = new DefaultCategoryDataset();
private int i;
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
set.addValue(0, "Test", "1");
JFreeChart barChart = ChartFactory.createBarChart(
"Test", "Category", "Score", set,
PlotOrientation.VERTICAL, true, true, false);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new ChartPanel(barChart) {
@Override
public Dimension getPreferredSize() {
return new Dimension(567, 345);
}
});
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("Clear") {
@Override
public void actionPerformed(ActionEvent e) {
set.clear();
i = 0;
}
}));
p.add(new JButton(new AbstractAction("Zero") {
@Override
public void actionPerformed(ActionEvent e) {
set.setValue(0, "Test", "1");
i = 0;
}
}));
p.add(new JButton(new AbstractAction("Update") {
@Override
public void actionPerformed(ActionEvent e) {
set.setValue(i += 10, "Test", "1");
}
}));
mainPanel.add(p, BorderLayout.SOUTH);
f.add(mainPanel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}