我有一个使用jfreechart API显示网站登录的JFrame。它是一个条形图,数据集来自SQL数据库。
java项目加载图表,图表显示当前的网站登录。由于数据集每秒都在变化,因此条形图应该是动态的。我使用Timer类来做到这一点。它每10秒运行一次loadLogonChart()。到目前为止,我没有遇到任何问题。但问题是它确实在10秒内更新了图表。但是,在20秒后,它会在我首先运行表单时将值加载回来。然后这个过程一遍又一遍地重复。我使用的代码如下。我无法弄清楚它有什么问题。
public final class MainForm extends javax.swing.JFrame implements ActionListener{
private static int AUTO_UPDATE_CHARTS = 10000;
public MainForm() throws SQLException {
//Timer for the barchart
Timer timerChart = new Timer(AUTO_UPDATE_CHARTS, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
loadLogonChart();
} catch (SQLException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
timerChart.start();
//LOAD THE FORM
loadForm();
}
public void loadForm() throws SQLException{
initComponents();
loadLogonChart();
}
public void loadLogonChart() throws SQLException{
//database class that I need for the barchart datasets
Database db = new Database();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
JFreeChart chart = ChartFactory.createBarChart("Web Site Activity Chart", "Days", "# of visits", dataset, PlotOrientation.VERTICAL, false, true, false);
CategoryPlot catPlot = chart.getCategoryPlot();
try {
dataset.setValue(db.showMonday(), "logon", "Monday");
dataset.setValue(db.showTuesday(), "logon", "Tuesday");
dataset.setValue(db.showWednesday(), "logon", "Wednesday");
dataset.setValue(db.showThursday(), "logon", "Thursday");
dataset.setValue(db.showFriday(), "logon", "Friday");
dataset.setValue(db.showSaturday(), "logon", "Saturday");
dataset.setValue(db.showSunday(), "logon", "Sunday");
chart = ChartFactory.createBarChart("Web Site Activity Chart", "Days", "# of visits", dataset, PlotOrientation.VERTICAL, false, true, false);
ChartPanel myChart = new ChartPanel(chart);
myChart.setMouseWheelEnabled(true);
BarRenderer renderer = (BarRenderer) catPlot.getRenderer();
DecimalFormat decimalFormat = new DecimalFormat("##.##");
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",decimalFormat));
catPlot.setRenderer(renderer);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_LEFT));
renderer.setItemLabelsVisible(true);
chart.getCategoryPlot().setRenderer(renderer);
//renderer.setBaseItemLabelGenerator(CategoryItemLabelGenerator generator)
chartPanel.setLayout(new java.awt.BorderLayout());
chartPanel.add(myChart,BorderLayout.CENTER);
chartPanel.revalidate();
chartPanel.validate();
} catch (SQLException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:1)
chartPanel.add(myChart,BorderLayout.CENTER);
chartPanel.revalidate();
chartPanel.validate();
在我看来,您试图继续向chartPanel添加不同的组件。添加组件不会删除以前的组件。
Swing绘制最后添加的组件,以便旧面板显示在新面板的顶部。尝试:
chartPanel.removeAll();
chartPanel.add(myChart,BorderLayout.CENTER);
chartPanel.revalidate();
chartPanel.validate(); // not needed since you do revalidate
chartPanel.repaint();