⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 superdemo.java

📁 jfreechart帮助文档
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/* --------------
 * SuperDemo.java
 * --------------
 * (C) Copyright 2004-2006, by Object Refinery Limited.
 *
 */

package demo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.RefineryUtilities;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.FontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

/**
 * A demo for JFreeChart.
 */
public class SuperDemo extends ApplicationFrame 
                       implements ActionListener, TreeSelectionListener {

    /** Exit action command. */
    public static final String EXIT_COMMAND = "EXIT";

    private JPanel displayPanel;
    
    private JPanel chartContainer;
    
    private JPanel descriptionContainer;
    
    private JTextPane descriptionPane;
    
    /**
     * Creates a new demo instance.
     * 
     * @param title  the frame title.
     */
    public SuperDemo(String title) {
        super(title);
        setContentPane(createContent());
        setJMenuBar(createMenuBar());
    }

    /**
     * Creates a panel for the main window.
     * 
     * @return A panel.
     */
    private JComponent createContent() {
        JPanel content = new JPanel(new BorderLayout());
        
        JTabbedPane tabs = new JTabbedPane();
        JPanel content1 = new JPanel(new BorderLayout());
        content1.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        JSplitPane splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        JTree tree = new JTree(createTreeModel());
        tree.addTreeSelectionListener(this);
        splitter.setLeftComponent(new JScrollPane(tree));
        splitter.setRightComponent(createChartDisplayPanel());
        content1.add(splitter);
        tabs.add("Demos", content1);
        MemoryUsageDemo memUse = new MemoryUsageDemo(300000);
        memUse.new DataGenerator(1000).start();
        tabs.add("Memory Usage", memUse);
        tabs.add("Source Code", createSourceCodePanel());
        tabs.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        content.add(tabs);
        return content;
    }
    
    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        // first the file menu
        JMenu fileMenu = new JMenu("File", true);
        fileMenu.setMnemonic('F');

        JMenuItem exportToPDF = new JMenuItem("Export to PDF...", 'p');
        exportToPDF.setActionCommand("EXPORT_TO_PDF");
        exportToPDF.addActionListener(this);
        fileMenu.add(exportToPDF);
        
        fileMenu.addSeparator();
        
        JMenuItem exitItem = new JMenuItem("Exit", 'x');
        exitItem.setActionCommand(EXIT_COMMAND);
        exitItem.addActionListener(this);
        fileMenu.add(exitItem);

        // finally, glue together the menu and return it
        menuBar.add(fileMenu);

        return menuBar;
    }
    
    private JPanel createSourceCodePanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        JEditorPane editorPane = new JEditorPane();
        editorPane.setEditable(false);
        java.net.URL sourceURL = SuperDemo.class.getResource("source.html");
        if (sourceURL != null) {
            try {
                editorPane.setPage(sourceURL);
            } 
            catch (IOException e) {
                System.err.println("Attempted to read a bad URL: " + sourceURL);
            }
        } 
        else {
            System.err.println("Couldn't find file: source.html");
        }

        JScrollPane editorScrollPane = new JScrollPane(editorPane);
        editorScrollPane.setVerticalScrollBarPolicy(
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
        );
        editorScrollPane.setPreferredSize(new Dimension(250, 145));
        editorScrollPane.setMinimumSize(new Dimension(10, 10));
        
        panel.add(editorScrollPane);
        return panel;
    }
    
    /**
     * Handles menu selections by passing control to an appropriate method.
     *
     * @param event  the event.
     */
    public void actionPerformed(ActionEvent event) {

        String command = event.getActionCommand();
        if (command.equals("EXPORT_TO_PDF")) {
            exportToPDF();
        }
        else if (command.equals(EXIT_COMMAND)) {
            attemptExit();
        }
    }
    
    /**
     * Opens a "Save As..." dialog, inviting the user to save the selected 
     * chart to a file in PDF format.
     */
    private void exportToPDF() {
        Component c = this.chartContainer.getComponent(0);
        if (c instanceof ChartPanel) {
            JFileChooser fc = new JFileChooser();
            fc.setName("untitled.pdf");
            fc.setFileFilter(new FileFilter() {

                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".pdf");
                }

                public String getDescription() {
                    return "Portable Document Format (PDF)";
                }});
            int result = fc.showSaveDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                ChartPanel cp = (ChartPanel) c;
                try {
                    JFreeChart chart = (JFreeChart) cp.getChart().clone();
                    PDFExportTask t = new PDFExportTask(chart, cp.getWidth(), 
                            cp.getHeight(), fc.getSelectedFile());
                    SwingUtilities.invokeLater(t);
                }
                catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
        }
        else {
            String message = "Unable to export the selected item.  There is ";
            message += "either no chart selected,\nor else the chart is not ";
            message += "at the expected location in the component hierarchy\n";
            message += "(future versions of the demo may include code to ";
            message += "handle these special cases).";
            JOptionPane.showMessageDialog(this, message, "PDF Export", 
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    static class PDFExportTask implements Runnable {

        JFreeChart chart;
        
        int width;
        
        int height;
        
        File file;
        
        /**
         * A task that exports a chart to a file in PDF format using iText.
         * 
         * @param chart  the chart.
         * @param width  the width.
         * @param height  the height.
         * @param file  the file.
         */
        public PDFExportTask(JFreeChart chart, int width, int height, 
                File file) {
            this.chart = chart;
            this.file = file;
            this.width = width;
            this.height = height;
            chart.setBorderVisible(true);
            chart.setPadding(new RectangleInsets(2, 2, 2, 2));
        }
        
        public void run() {
            try {
                SuperDemo.saveChartAsPDF(this.file, chart, width, height, 
                        new DefaultFontMapper());
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    /**
     * Writes a chart to an output stream in PDF format using iText.
     * 
     * @param out  the output stream.
     * @param chart  the chart.
     * @param width  the chart width.
     * @param height  the chart height.
     * @param mapper  the font mapper.
     * 
     * @throws IOException if there is an I/O problem.
     */
    public static void writeChartAsPDF(OutputStream out,
            JFreeChart chart,
            int width,
            int height,
            FontMapper mapper) throws IOException {
        Rectangle pagesize = new Rectangle(width, height);
        Document document = new Document(pagesize, 50, 50, 50, 50);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.addAuthor("JFreeChart");
            document.addSubject("Demonstration");
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, mapper);
            Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
            chart.draw(g2, r2D);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        catch (DocumentException de) {
            System.err.println(de.getMessage());
        }
        document.close();
    }

    /**
     * Saves a chart to a file in PDF format using iText.
     * 
     * @param file  the file.
     * @param chart  the chart.
     * @param width  the chart width.
     * @param height  the chart height.
     * @param mapper  the font mapper.
     * 
     * @throws IOException if there is an I/O problem.
     */
    public static void saveChartAsPDF(File file,
            JFreeChart chart,
            int width,
            int height,
            FontMapper mapper) throws IOException {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        writeChartAsPDF(out, chart, width, height, mapper);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -