开发者

Graphing Applet is not running on Web browser

I got the source code from JFreeCharts of DynamicTimeSeriesCollection display.

It works fine when I run it as a simple java application, but then I wanted it as applet.

So I made the Applet code, and inserted all the code in start(), paint() and init() functions.

This runs well when I do "Run File", but when I try opening the generated HTML page on a webbrowser (Java SE 6 enabled) it gives a blank screen. I am using Netbeans 7.0.

The code is as follows,

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.DynamicTimeSeriesCollection;
import org.jfree.data.time.Second;
import org.jfree.data.xy.XYDataset;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GraphTest extends JApplet {

    private static final String TITLE = "ECG of the Patient";
    private static final String START = "Start";
    private static final String STOP = "Stop";
    private static final float MINMAX = 100;
    private static final int COUNT = 2 * 60;
    private static final int FAST = 100;
    private static final int SLOW = FAST * 5;
    private Timer timer;
    // private Object random;
    //private static final Random random = new Random();
    ReadAFile file_reader = new ReadAFile();
    byte[] values = file_reader.Readfile();
    float[] temp = new float[120];

    public GraphTest() {
        //super(title);
        final DynamicTimeSeriesCollection dataset =
                new DynamicTimeSeriesCollection(1, COUNT, new Second());
        dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2011));

        dataset.addSeries(temp, 0, "ECG Plot");
        JFreeChart chart = createChart(dataset);

        final JButton run = new JButton(STOP);
        run.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String cmd = e.getActionCommand();
                if (STOP.equals开发者_如何学Python(cmd)) {
                    timer.stop();
                    run.setText(START);
                } else {
                    timer.start();
                    run.setText(STOP);
                }
            }
        });

        final JComboBox combo = new JComboBox();
        combo.addItem("Fast");
        combo.addItem("Slow");
        combo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if ("Fast".equals(combo.getSelectedItem())) {
                    timer.setDelay(FAST);
                } else {
                    timer.setDelay(SLOW);
                }
            }
        });

        this.add(new ChartPanel(chart), BorderLayout.CENTER);
        JPanel btnPanel = new JPanel(new FlowLayout());
        btnPanel.add(run);
        btnPanel.add(combo);
        this.add(btnPanel, BorderLayout.SOUTH);


        timer = new Timer(FAST, new ActionListener() {

            float[] newData = new float[1];
            int i = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                newData[0] = values[i];
                dataset.advanceTime();
                dataset.appendData(newData);
                i++;

            }
        });
    }

    /**
     * Initialization method that will be called after the applet is loaded
     * into the browser.
     */
    @Override
    public void init() {
        EventQueue.invokeLater(new Runnable() {

            private String TITLE;
            //  this.setLayout(new FlowLayout());

            @Override
            public void run() {

                //DTSCTest demo = new DTSCTest(TITLE);
                // DTSCTest demo = new DTSCTest(TITLE);
                // pack();
                //RefineryUtilities.centerFrameOnScreen();
                //RefineryUtilities.centerFrameOnScreen(demo);
                setVisible(true);
                //demo.start();
            }
        });
        // TODO start asynchronous download of heavy resources
    }

    @Override
    public void paint(Graphics g) {
    }

    private JFreeChart createChart(final XYDataset dataset) {
        final JFreeChart result = ChartFactory.createTimeSeriesChart(
                TITLE, "hh:mm:ss", "Magnitude", dataset, true, true, false);
        final XYPlot plot = result.getXYPlot();
        ValueAxis domain = plot.getDomainAxis();
        domain.setAutoRange(true);
        ValueAxis range = plot.getRangeAxis();
        range.setRange(-MINMAX, MINMAX);
        return result;
    }

    @Override
    public void start() {
        timer.start();
    }
}

Here is another java file that is called by this class

import java.io.*;

public class ReadAFile {

    float[] datavalues = new float[300];

    /**
     * @param args the command line arguments
     */
    public byte[] Readfile() {
        StringBuilder contents = new StringBuilder();
        try {
            // use buffering, reading one line at a time
            // FileReader always assumes default encoding is OK!
            BufferedReader input = new BufferedReader(new FileReader("Desktop/Mytest.txt"));

            try {
                String line = null; // not declared within while loop
                /*
                 * readLine is a bit quirky : it returns the content of a line
                 * MINUS the newline. it returns null only for the END of the
                 * stream. it returns an empty String if two newlines appear in
                 * a row.
                 */
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                }
            } finally {
                input.close();
            }
        } catch (IOException ex) { System.out.println("Exception coming ");
        }
        byte[] finalarray = new byte[contents.length()];
        for (int ch = 0; ch < contents.length(); ++ch) {
            char co = contents.charAt(ch);
            int j = (int) co;
            finalarray[ch] = (byte) j;

        }
        return finalarray;
    }
}


It may look like I repeat myself (if you look at other answers of mine), but: Never override the paint() method in Swing!

If you really need to paint something, override paintComponent(). But in your case, you should simply put one of JFreeChart's components inside the applet (what you did in the constructor), and be done.

(Just for completeness: All GUI related stuff should be done in the AWT event dispatch thread, like using EventQueue.invokeLater (or SwingUtilities.invokeLater). The Applet's constructor will not be invoked in this thread, which means that you should not do the GUI initializations in the constructor. Better put this in your invokeLater called from the init method.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜