我是java的新手。我正在尝试使用带按钮的swing创建一个简单的GUI,它可以从JFreeChart库中更改图表的字体。但是,当我使用chart.setFont时,它会使GUI冻结几秒钟。我读到我应该在其他线程中使用setFont来避免这个问题,但它对我来说似乎不起作用 - 可能我做错了。我把我的代码放在下面:
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();
}
});
}
}
在这种情况下,有人可以帮我解决或提供任何提示吗?
答案 0 :(得分:3)
您的代码在我的实现上运行良好。您可以尝试使用此变体来查看使用现有字体是否有帮助。正如@camickr所建议的,EDT上不需要invokeLater()
。
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));
}
});
}