Reputation: 33
I'm new to java. I'm trying to create a simple GUI with swing with button, which change the font of chart from JFreeChart library. However when I use chart.setFont, it makes a GUI freezed for a couple of seconds. I read that I should use setFont in other thread to avoid the problem but it doesn't seem work for me - probably I'm doing it wrong. I put my code below:
package javaapplication2;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
public final class Main{
Main(){
JFrame frame=new JFrame();
DefaultCategoryDataset data=new DefaultCategoryDataset();
JFreeChart chart=ChartFactory.createBarChart("Title", "Name", "Grade", data, PlotOrientation.VERTICAL,
true, false, false);
ChartPanel chartPanel=new ChartPanel(chart);
JPanel subPanel=new JPanel();
JPanel panel=new JPanel();
JButton button=new JButton("Click");
setButton(chart, button);
setChart(data);
setSubPanel(subPanel, chartPanel);
setPanel(panel, button, subPanel);
setFrame(frame);
frame.setContentPane(panel);
frame.validate();
frame.setVisible(true);
}
public void setFrame(JFrame frame){
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
}
public void setPanel(JPanel panel, JButton button, JPanel subPanel){
panel.add(button);
panel.add(subPanel);
}
public void setSubPanel(JPanel subPanel, ChartPanel chartPanel){
subPanel.add(chartPanel);
}
public void setButton(final JFreeChart chart, JButton button){
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chart.getTitle().setFont(new Font("Sans-Serif", Font.PLAIN, 18));
}
}
);
}
});
}
public void setChart(DefaultCategoryDataset data){
data.addValue(1, "abc", "");
data.addValue(2, "def", "");
data.addValue(3, "ghi", "");
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
Main frame=new Main();
}
});
}
}
Could anyone help me to solve it or give any tip how should I use thread in that case?
Upvotes: 3
Views: 1494
Reputation: 205795
Your code works fine on my implementation. You might try this variation to see if using the existing font helps. As suggested by @camickr, the invokeLater()
is not needed on the EDT.
public void setButton(final JFreeChart chart, JButton button) {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TextTitle title = chart.getTitle();
Font font = title.getFont();
float size = font.getSize();
title.setFont(font.deriveFont(size + 2));
}
});
}
Upvotes: 3