我是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();
            }
        });
    }
}

任何人都可以帮助我解决该问题或提供任何提示,在这种情况下我应该如何使用线程?

最佳答案

您的代码在我的实施中工作正常.您可以尝试使用此变体,以查看使用现有字体是否有帮助.如@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));
        }
    });
}