JFreeChart in JavaApplet?

N

NickPick

How can I put a JFreeChart into a JavaApplet so that it doesn't open
another window? Any help is appreciated.

package chart;

import java.awt.Color;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.RefineryUtilities;

public class RandomWalkChart extends ApplicationFrame {

public RandomWalkChart(String title) {
super(title);
XYDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(chartPanel);
}

private static XYDataset createDataset() {
double r;
double[] p = new double[1001];
p[0]=10;
XYSeries series1 = new XYSeries("Share Price");
for (int x = 0; x < 1000; x++) {
r=Math.random()*2-1;
p[x+1]=p[x]+r;
System.out.println (p[x]);
series1.add(x, p[x+1]);
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series1);
return dataset;
}

private static JFreeChart createChart(XYDataset dataset) {
// create the chart...
JFreeChart chart = ChartFactory.createXYLineChart(
"Ramdom Walk", // chart title
"Days", // x axis label
"Price", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
false, // include legend
true, // tooltips
false // urls
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
chart.setBackgroundPaint(Color.white);
// get a reference to the plot for further customisation...
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
XYLineAndShapeRenderer renderer
= (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setShapesVisible(true);
renderer.setShapesFilled(true);
// change the auto tick unit selection to integer units only...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// OPTIONAL CUSTOMISATION COMPLETED.
return chart;
}/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* @return A panel.
*/
public static JPanel createDemoPanel() {
JFreeChart chart = createChart(createDataset());
return new ChartPanel(chart);
}
}






package chart;
import org.jfree.ui.RefineryUtilities;

public class NewApplet extends java.applet.Applet {

/** Initializes the applet NewApplet */
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}


RandomWalkChart demo = new RandomWalkChart("Line Chart Demo
2");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);

}

/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();

setLayout(new java.awt.BorderLayout());

jButton1.setText("jButton1");
add(jButton1, java.awt.BorderLayout.SOUTH);
}// </editor-fold>


// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration

}
 
A

Arne Vajhøj

NickPick said:
How can I put a JFreeChart into a JavaApplet so that it doesn't open
another window?

What errors do you get in Java console ?

Wild guess: have you a Class-Path directive to the two
JFreeChart jar files in your manifest ?

Arne
 
N

NickPick

What errors do you get in Java console ?

Wild guess: have you a Class-Path directive to the two
JFreeChart jar files in your manifest ?

Arne

I'm not getting eny errors, but what I want is that the chart is being
displayed in the main window of the browser instead of opening a new
window. As far as I can tell the problem lies in
ChartPanel chartPanel = new ChartPanel(chart);

How can I define where ChartPanel is located?
 
A

Arne Vajhøj

NickPick said:
I'm not getting eny errors, but what I want is that the chart is being
displayed in the main window of the browser instead of opening a new
window. As far as I can tell the problem lies in
ChartPanel chartPanel = new ChartPanel(chart);

How can I define where ChartPanel is located?

Sorry - I did not read your post carefully enough.

I have used:

ChartPanel chartPanel = new ChartPanel(chart);
getContentPane().add(chartPanel);

to add the ChartPanel to the applets content panel.

Arne
 
N

NickPick

Sorry - I did not read your post carefully enough.

I have used:

ChartPanel chartPanel = new ChartPanel(chart);
getContentPane().add(chartPanel);

to add the ChartPanel to the applets content panel.

Arne

Unfortunately that doesn't work. I'm using Netbeans and when I start
the applet there are two different windows opening. One with a button
(which I designed with NetBeans) and the other one is opened from
JFreeChart through
ChartPanel chartPanel = new ChartPanel(chart);

There should be a way to define that ChartPanel is on the original
window, no?
tx
 
A

Arne Vajhøj

NickPick said:
Unfortunately that doesn't work. I'm using Netbeans and when I start
the applet there are two different windows opening. One with a button
(which I designed with NetBeans) and the other one is opened from
JFreeChart through
ChartPanel chartPanel = new ChartPanel(chart);

There should be a way to define that ChartPanel is on the original
window, no?

I believe what I described is the way.

I made an example a long time ago.

Try look at:

http://www.vajhoej.dk/arne/eksperten/jfreechart/curvehardcoded.html

Source at:

http://www.vajhoej.dk/arne/eksperten/jfreechart/CurveApplet.java

Arne
 
J

John B. Matthews

Arne Vajhøj said:
NickPick wrote: [...]
Unfortunately that doesn't work. I'm using Netbeans and when I start
the applet there are two different windows opening. One with a button
(which I designed with NetBeans) and the other one is opened from
JFreeChart through
ChartPanel chartPanel = new ChartPanel(chart);

There should be a way to define that ChartPanel is on the original
window, no?

I believe what I described is the way.

I made an example a long time ago.

Try look at:

http://www.vajhoej.dk/arne/eksperten/jfreechart/curvehardcoded.html

Source at:

http://www.vajhoej.dk/arne/eksperten/jfreechart/CurveApplet.java

I think Arne's right; here's a similar example, tested with 1.0.12:

<http://supertomate.wikispaces.com/JFreeChart+And+Applet>

Does your button specify target="new"?
 
N

NickPick

Sorry - I did not read your post carefully enough.

I have used:

ChartPanel chartPanel = new ChartPanel(chart);
getContentPane().add(chartPanel);

to add the ChartPanel to the applets content panel.

Arne

But when I use this:

XYDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
getContentPane().add(chartPanel);

The second line: JFreeChart chart = createChart(dataset); already
opens a new window. How can I prevent this from happening and add it
to the original java Applet panel which is generated with a code that
looks like this:

....
javax.swing.GroupLayout jDialog1Layout = new
javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
....
 
J

John B. Matthews

NickPick said:
XYDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
getContentPane().add(chartPanel);

To which top-level container are you adding the chartPanel:
an instance of JDialog or JApplet?
The second line: JFreeChart chart = createChart(dataset); already
opens a new window. How can I prevent this from happening and add it
to the original java Applet panel which is generated with a code that
looks like this: [...]
jDialog1.getContentPane().setLayout(jDialog1Layout);
[...]

You appear to have two top-level containers:

<http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html>

An sscce <http://pscode.org/sscce.html> would clarify the matter.
 
N

NickPick

I've been trying this for a while now and still didn't find the
answer, so let's try to start from the beginning. Let's forget about
the applet for the moment and do everything in a normal Java
Application:

1. Im creating a GUI with NetBeans, which takes away some flexibility
as the code which is automatically generated when I draw buttons and
JPanels in NetBeans cannot be edited.

2. I'm using jFreeChart to generate a chart and I'd like to put this
chart into a panel (which is on a JFrame) that I drew on the automatic
GUI designer of Netbeans rather than having it in a separate window

Below you find first the code of Main.java, which firstly opens the
NewJFrame (which is generated with NetBeans) and then the jFreeChart
(all in Main.java with some static methods).

Secondly you find the code of the NewJFrame.java (which cannot be
edited as it is generated by NetBeans!!!). My question now is, how do
I put the JFreeCharts into the JPanel? All suggestions so far did not
work.
many thanks!


package javaapplication15;

import java.awt.Container;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;

public class Main {

static private PieDataset createSampleDataset() {
// some random data
final DefaultPieDataset result = new DefaultPieDataset();
result.setValue("Java", new Double(43.2));
result.setValue("Visual Basic", new Double(10.0));
result.setValue("C/C++", new Double(17.5));
result.setValue("PHP", new Double(32.5));
result.setValue("Perl", new Double(1.0));
return result;

}
static private JFreeChart createChart(final PieDataset dataset) {
// generate the Chart
final JFreeChart chart = ChartFactory.createPieChart3D(
"Pie Chart 3D Demo 1", // chart title
dataset, // data
true, // include legend
true,
false
);

final PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);
plot.setNoDataMessage("No data to display");
return chart;

}

public static void main(String[] args) {
// Generate the NewJFrame
NewJFrame f = new NewJFrame();
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setLocationRelativeTo( null ); // null = center on screen
f.setVisible( true );


PieDataset dataset = createSampleDataset();
// create the chart...
JFreeChart chart = createChart(dataset);

// add the chart to a panel...
ChartPanel chartPanel = new ChartPanel(chart);

// !!!!!!!HERE COMES THE CODE THAT NEEDS TO BE EDITED!!!!!!!
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
PieChart3DDemo1 demo = new PieChart3DDemo1("Pie Chart 3D Demo
1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
// !!!!!!!HERE ENDS THE CODE THAT NEEDS TO BE EDITED!!!!!!!
}
}


-----------------------------------------------------------------------------
THE FOLLOWING CODE IS AUTOMATICALLY GENERATED BY NETBEANS AND CANNOT
BE EDITED. All it does is generate a JFrame with a Button, a TextField
and a JPanel in which I'd like to have the JFreechart to appear.

package javaapplication15;

/**
*
*/
public class NewJFrame extends javax.swing.JFrame {

/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jTextField1 = new javax.swing.JTextField();

setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent
evt) {
jButton1ActionPerformed(evt);
}
});

jPanel1.setAutoscrolls(true);

javax.swing.GroupLayout jPanel1Layout = new
javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 280, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE)
);

jTextField1.setText("jTextField1");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout
(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(114, 114, 114)
.addGroup(layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 175,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)))
.addGroup(layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(64, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jButton1)
.addPreferredGap
(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 51,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(24, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent
evt) {
//jTextField1.setText("Pressed");
int i=jTextField1.getX();
jTextField1.setText(Integer.toString(i));
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration

}
 
J

John B. Matthews

NickPick said:
I've been trying this for a while now and still didn't find the
answer, so let's try to start from the beginning. Let's forget about
the applet for the moment and do everything in a normal Java
Application:

1. Im creating a GUI with NetBeans, which takes away some flexibility
as the code which is automatically generated when I draw buttons and
JPanels in NetBeans cannot be edited.

Sorry, I am unfamiliar with the NetBeans GUI editor.
2. I'm using jFreeChart to generate a chart and I'd like to put this
chart into a panel (which is on a JFrame) that I drew on the automatic
GUI designer of Netbeans rather than having it in a separate window
[...]

PieChartDemo1 extends ApplicationFrame, which derives from JFrame. The
latter's default content pane has a BorderLayout. Just add your new
components, as shown in the constructor below. Note also that Swing
applications should start on the EDT:

<http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html>

<sscce>
/*
* Adapted from http://jfreechart.svn.sourceforge.net/
* /trunk/source/org/jfree/chart/demo/PieChartDemo1.java
*
* More than 150 demo applications are included with the
* JFreeChart Developer Guide...for more information, see:
*
* http://www.object-refinery.com/jfreechart/guide.html
*/

package chart;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

import javax.swing.JTextField;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

/**
* A simple demonstration application showing how to create
* a pie chart using data from a {@link DefaultPieDataset}.
*/
public class PieChartDemo extends ApplicationFrame {

/**
* Default constructor.
*
* @param title the frame title.
*/
public PieChartDemo(String title) {
super(title);
this.add(createDemoPanel());
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JTextField("JTextField"));
panel.add(new JButton("JButton"));
this.add(panel, BorderLayout.SOUTH);
}

/**
* Creates a sample dataset.
*
* @return A sample dataset.
*/
private static PieDataset createDataset() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("One", new Double(43.2));
dataset.setValue("Two", new Double(10.0));
dataset.setValue("Three", new Double(27.5));
dataset.setValue("Four", new Double(17.5));
dataset.setValue("Five", new Double(11.0));
dataset.setValue("Six", new Double(19.4));
return dataset;
}

/**
* Creates a chart.
*
* @param dataset the dataset.
*
* @return A chart.
*/
private static JFreeChart createChart(PieDataset dataset) {

JFreeChart chart = ChartFactory.createPieChart(
"Pie Chart Demo 1", // chart title
dataset, // data
true, // include legend
true,
false
);

PiePlot plot = (PiePlot) chart.getPlot();
plot.setSectionOutlinesVisible(false);
plot.setNoDataMessage("No data available");

return chart;

}

/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* @return A panel.
*/
public static JPanel createDemoPanel() {
JFreeChart chart = createChart(createDataset());
return new ChartPanel(chart);
}

/**
* Starting point for the demonstration application.
*
* @param args ignored.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
PieChartDemo demo = new PieChartDemo("Pie Chart Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
});
}

}
</sscce>
 
N

Nigel Wade

NickPick said:
I've been trying this for a while now and still didn't find the
answer, so let's try to start from the beginning. Let's forget about
the applet for the moment and do everything in a normal Java
Application:

1. Im creating a GUI with NetBeans, which takes away some flexibility
as the code which is automatically generated when I draw buttons and
JPanels in NetBeans cannot be edited.

There are many hooks which allow you to insert code pre-/post- creation,
initialization etc. and to control the code which is automatically generated.
2. I'm using jFreeChart to generate a chart and I'd like to put this
chart into a panel (which is on a JFrame) that I drew on the automatic
GUI designer of Netbeans rather than having it in a separate window

Below you find first the code of Main.java, which firstly opens the
NewJFrame (which is generated with NetBeans) and then the jFreeChart
(all in Main.java with some static methods).

Secondly you find the code of the NewJFrame.java (which cannot be
edited as it is generated by NetBeans!!!). My question now is, how do
I put the JFreeCharts into the JPanel? All suggestions so far did not
work.
many thanks!


package javaapplication15;

import java.awt.Container;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;

public class Main {

static private PieDataset createSampleDataset() {
// some random data
final DefaultPieDataset result = new DefaultPieDataset();
result.setValue("Java", new Double(43.2));
result.setValue("Visual Basic", new Double(10.0));
result.setValue("C/C++", new Double(17.5));
result.setValue("PHP", new Double(32.5));
result.setValue("Perl", new Double(1.0));
return result;

}
static private JFreeChart createChart(final PieDataset dataset) {
// generate the Chart
final JFreeChart chart = ChartFactory.createPieChart3D(
"Pie Chart 3D Demo 1", // chart title
dataset, // data
true, // include legend
true,
false
);

final PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);
plot.setNoDataMessage("No data to display");
return chart;

}

public static void main(String[] args) {
// Generate the NewJFrame
NewJFrame f = new NewJFrame();

This should be performed by the EDT. If you are using NetBeans you presumably
used the "New JFrame Form" (the class name suggests this) which automatically
creates the code necessary to ensure this is done on the EDT. Why did you
delete that and replace it with your incorrect code?
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setLocationRelativeTo( null ); // null = center on screen
f.setVisible( true );


PieDataset dataset = createSampleDataset();
// create the chart...
JFreeChart chart = createChart(dataset);

// add the chart to a panel...
ChartPanel chartPanel = new ChartPanel(chart);

// !!!!!!!HERE COMES THE CODE THAT NEEDS TO BE EDITED!!!!!!!
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
PieChart3DDemo1 demo = new PieChart3DDemo1("Pie Chart 3D Demo
1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
// !!!!!!!HERE ENDS THE CODE THAT NEEDS TO BE EDITED!!!!!!!
}
}

Again, this should all be performed on the EDT, not the main thread.

What is PieChart3DDemo1 in the Swing hierarchy? Is it a panel, a frame, or what?
If it's a JFrame, or any derivative of awt.Window, then I don't think it can't
be added to a JFrame because it is its own window.

My suggestion would be to move the above code, which should be in the EDT
anyway, to the NewJFrame constructor, immediately after initComponents() and,
if demo is a non-window component, add it to your frame.

In the design window, select the Code tab and for the "Form Size Policy"
select "No Resize Code". This will prevent the generated code from including
the pack(). Insert your code in initComponents() and then add a pack().

Alternatively, select the final component in the NewJFrame design window, and in
the Code tab for that component click on the ellipsis (...) for "Post Adding
Code". In the dialog which opens enter your code. This will insert you code
into the non-editable section of the generated code immediately after the last
component is added to the frame.
 
N

NickPick

NickPick said:
I've been trying this for a while now and still didn't find the
answer, so let's try to start from the beginning. Let's forget about
the applet for the moment and do everything in a normal Java
Application:
1. Im creating a GUI with NetBeans, which takes away some flexibility
as the code which is automatically generated when I draw buttons and
JPanels in NetBeans cannot be edited.

There are many hooks which allow you to insert code pre-/post- creation,
initialization etc. and to control the code which is automatically generated.




2. I'm using jFreeChart to generate a chart and I'd like to put this
chart into a panel (which is on a JFrame) that I drew on the automatic
GUI designer of Netbeans rather than having it in a separate window
Below you find first the code of Main.java, which firstly opens the
NewJFrame (which is generated with NetBeans) and then the jFreeChart
(all in Main.java with some static methods).
Secondly you find the code of the NewJFrame.java (which cannot be
edited as it is generated by NetBeans!!!). My question now is, how do
I put the JFreeCharts into the JPanel? All suggestions so far did not
work.
many thanks!
package javaapplication15;
import java.awt.Container;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;
public class Main {
    static private PieDataset createSampleDataset() {
        // some random data
        final DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("Java", new Double(43.2));
        result.setValue("Visual Basic", new Double(10.0));
        result.setValue("C/C++", new Double(17.5));
        result.setValue("PHP", new Double(32.5));
        result.setValue("Perl", new Double(1.0));
        return result;
    }
    static private JFreeChart createChart(final PieDataset dataset) {
        // generate the Chart
        final JFreeChart chart = ChartFactory.createPieChart3D(
            "Pie Chart 3D Demo 1",  // chart title
            dataset,                // data
            true,                   // include legend
            true,
            false
        );
        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        plot.setNoDataMessage("No data to display");
        return chart;
    public static void main(String[] args) {
       // Generate the NewJFrame
         NewJFrame f = new NewJFrame();

This should be performed by the EDT. If you are using NetBeans you presumably
used the "New JFrame Form" (the class name suggests this) which automatically
creates the code necessary to ensure this is done on the EDT. Why did you
delete that and replace it with your incorrect code?


         f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         f.setLocationRelativeTo( null );  // null = center on screen
         f.setVisible( true );
        PieDataset dataset = createSampleDataset();
        // create the chart...
        JFreeChart chart = createChart(dataset);
        // add the chart to a panel...
        ChartPanel chartPanel = new ChartPanel(chart);
        // !!!!!!!HERE COMES THE CODE THAT NEEDS TO BE EDITED!!!!!!!
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        PieChart3DDemo1 demo = new PieChart3DDemo1("Pie Chart 3D Demo
1");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);
        // !!!!!!!HERE ENDS THE CODE THAT NEEDS TO BE EDITED!!!!!!!
    }
}

Again, this should all be performed on the EDT, not the main thread.

What is PieChart3DDemo1 in the Swing hierarchy? Is it a panel, a frame, or what?
If it's a JFrame, or any derivative of awt.Window, then I don't think it can't
be added to a JFrame because it is its own window.

My suggestion would be to move the above code, which should be in the EDT
anyway, to the NewJFrame constructor, immediately after initComponents() and,
if demo is a non-window component, add it to your frame.

In the design window, select the Code tab and for the "Form Size Policy"
select "No Resize Code". This will prevent the generated code from including
the pack(). Insert your code in initComponents() and then add a pack().

Alternatively, select the final component in the NewJFrame design window, and in
the Code tab for that component click on the ellipsis (...) for "Post Adding
Code". In the dialog which opens enter your code. This will insert you code
into the non-editable section of the generated code immediately after the last
component is added to the frame.

I have simplified my example a bit:
Let's assume I instantiate a NewJFrame which contains a JPannel

// JFrame containing a JPannel with the name JPanel1
NewJFrame f = new NewJFrame();


Would it then be possible to add the chartPanel into the JPannel with
something similar to this?

ChartPanel chartPanel = new ChartPanel(chart); // create chart
f.JPanel1.add(chartPanel); // HOW DO I DO THIS?

Obviously it doesn't work, but is there something similar to the last
line I wrote that works?

thanks
 
A

Arne Vajhøj

NickPick said:
I have simplified my example a bit:
Let's assume I instantiate a NewJFrame which contains a JPannel

// JFrame containing a JPannel with the name JPanel1
NewJFrame f = new NewJFrame();


Would it then be possible to add the chartPanel into the JPannel with
something similar to this?

ChartPanel chartPanel = new ChartPanel(chart); // create chart
f.JPanel1.add(chartPanel); // HOW DO I DO THIS?

Obviously it doesn't work, but is there something similar to the last
line I wrote that works?

It does not ?

Arne
 
J

John B. Matthews

NickPick said:
NickPick wrote: [edited]
I have simplified my example a bit: Let's assume I instantiate a
NewJFrame which contains a JPanel
      // JFrame containing a JPanel with the name JPanel1
      NewJFrame f = new NewJFrame();
Would it then be possible to add the chartPanel into the JPanel
with something similar to this?
 ChartPanel chartPanel = new ChartPanel(chart); // create chart
 f.JPanel1.add(chartPanel); // HOW DO I DO THIS?
Obviously it doesn't work, but is there something similar to the
last line I wrote that works?

It does not ?

It says it doesn't know the symbol

What symbol? Why not just add the result of createDemoPanel()), as
shown in a previous post?

<http://groups.google.com/group/comp.lang.java.programmer/msg/3e0781c060697229>
 
A

Arne Vajhøj

NickPick said:
It says it doesn't know the symbol

You can add a ChartPanel to a JPanel.

f seems to exist, but does NewJFrame have a public field
by the name JPanel1 ?

Arne
 
N

NickPick

You can add a ChartPanel to a JPanel.

f seems to exist, but does NewJFrame have a public field
by the name JPanel1 ?

Arne

Ok, I'm getting closer. I now put everything into the same class
called NewJFrameApp and the chart should be added to the jPanel1 once
the button is pressed. The program compiles without any error but the
chart doesn't appear to be visible.
In jButton1ActionPerformed you can see the relevant code where I think
the problem is. Below the full listing. jButton1ActionPerformed is
almost at the bottom.

thanks for your help!



import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;

public class NewJFrameApp extends javax.swing.JFrame {

static private PieDataset createSampleDataset() {

final DefaultPieDataset result = new DefaultPieDataset();
result.setValue("Java", new Double(43.2));
result.setValue("Visual Basic", new Double(10.0));
result.setValue("C/C++", new Double(17.5));
result.setValue("PHP", new Double(32.5));
result.setValue("Perl", new Double(1.0));
return result;

}
static private JFreeChart createChart(final PieDataset dataset) {

final JFreeChart chart = ChartFactory.createPieChart3D(
"Pie Chart 3D Demo 1", // chart title
dataset, // data
true, // include legend
true,
false
);

final PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);
plot.setNoDataMessage("No data to display");
return chart;

}

/** Creates new form NewJFrameApp */
public NewJFrameApp() {
initComponents();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();

setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);

javax.swing.GroupLayout jPanel1Layout = new
javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 256, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 155, Short.MAX_VALUE)
);

jButton1.setText("Show Chart");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent
evt) {
jButton1ActionPerformed(evt);
}
});

jTextField1.setText("jTextField1");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout
(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(154, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(157, 157, 157))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(73, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(51, Short.MAX_VALUE)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 294,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55))
);
layout.setVerticalGroup(
layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 32,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap
(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10,
Short.MAX_VALUE)
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent
evt) {
PieDataset dataset = createSampleDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
jPanel1.add(chartPanel);
jPanel1.setVisible(true);
jTextField1.setText("The Chart has been added to JPanel1 and
should be visible now - but it isn't");
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {



new NewJFrameApp().setVisible(true);

}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration

}
 
N

NickPick

You can add a ChartPanel to a JPanel.
f seems to exist, but does NewJFrame have a public field
by the name JPanel1 ?

Ok, I'm getting closer. I now put everything into the same class
called NewJFrameApp and the chart should be added to the jPanel1 once
the button is pressed. The program compiles without any error but the
chart doesn't appear to be visible.
In jButton1ActionPerformed you can see the relevant code where I think
the problem is. Below the full listing. jButton1ActionPerformed is
almost at the bottom.

thanks for your help!

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;

public class NewJFrameApp extends javax.swing.JFrame {

        static private PieDataset createSampleDataset() {

        final DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("Java", new Double(43.2));
        result.setValue("Visual Basic", new Double(10.0));
        result.setValue("C/C++", new Double(17.5));
        result.setValue("PHP", new Double(32.5));
        result.setValue("Perl", new Double(1.0));
        return result;

    }
    static private JFreeChart createChart(final PieDataset dataset) {

        final JFreeChart chart = ChartFactory.createPieChart3D(
            "Pie Chart 3D Demo 1",  // chart title
            dataset,                // data
            true,                   // include legend
            true,
            false
        );

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        plot.setNoDataMessage("No data to display");
        return chart;

    }

    /** Creates new form NewJFrameApp */
    public NewJFrameApp() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation
(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new
javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 256, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 155, Short.MAX_VALUE)
        );

        jButton1.setText("Show Chart");
        jButton1.addActionListener(new java.awt.event.ActionListener()
{
            public void actionPerformed(java.awt.event.ActionEvent
evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout
(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
                .addContainerGap(154, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(157, 157, 157))
            .addGroup(layout.createSequentialGroup()
                .addGap(71, 71, 71)
                .addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(73, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
                .addContainerGap(51, Short.MAX_VALUE)
                .addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 294,
javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(55, 55, 55))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup
(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 32,
javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap
(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10,
Short.MAX_VALUE)
                .addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent
evt) {
        PieDataset dataset = createSampleDataset();
        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart);
        jPanel1.add(chartPanel);
        jPanel1.setVisible(true);
        jTextField1.setText("The Chart has been added to JPanel1 and
should be visible now - but it isn't");
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new NewJFrameApp().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

}

Finally! I found the solution how to add jFreeCharts to graphical
Objects created with Netbeans:
http://web.uconn.edu/~cdavid/netBeansJavajFreeChartpart1.pdf

The trick is to add it to JLabels and not JPanels:

ChartPanel chartPanel = new ChartPanel(chart);
BufferedImage image = chart.createBufferedImage(400,500);
jLabel1.setIcon(new ImageIcon(image));
 
J

John B. Matthews

NickPick said:
Finally! I found the solution how to add jFreeCharts to graphical
Objects created with Netbeans:
http://web.uconn.edu/~cdavid/netBeansJavajFreeChartpart1.pdf

The trick is to add it to JLabels and not JPanels:

ChartPanel chartPanel = new ChartPanel(chart);
BufferedImage image = chart.createBufferedImage(400,500);
jLabel1.setIcon(new ImageIcon(image));

This is one solution, but not required; others approaches are possible:

<http://groups.google.com/group/comp.lang.java.gui/msg/850bf557f54cff90>

I wonder if your reliance on the NetBeans GUI editor is confounding your
understanding of Swing components. You might return to the tutorial with
this in mind:

<http://java.sun.com/docs/books/tutorial/uiswing/components/index.html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top