¿Cómo insertar un gráfico JFreeChart en un panel en una GUI separada?
Quiero poner un gráfico dentro de un panel específico en una GUI usando JFreeChart. Tengo 2 archivos java (uno con la GUI y otro que crea el gráfico) y me gustaría, si es posible, mantenerlo de esta manera.
En la GUI principal tengo un panel llamado panelGraph:
JPanel panelGraph = new JPanel();
panelGraph.setBounds(220, 64, 329, 250);
panelMain.add(panelGraph); //it is inside the main panel
panelGraph.setLayout(null);
Y también tengo un botón que activa la apariencia del gráfico:
Button btnGetGraph = new JButton("Draw Graph");
btnGetGraph.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
XYLineChart_AWT.runGraph("Cenas", "Titulo", "XLABEL", "YLABEL", panelGraph);
}
});
btnGetGraph.setFont(new Font("Tahoma", Font.BOLD, 13));
btnGetGraph.setBounds(323, 327, 128, 34);
panelMain.add(btnGetGraph);
Y como sigue, es el archivo java que crea el gráfico:
public class XYLineChart_AWT extends JFrame {
public XYLineChart_AWT( String applicationTitle, String chartTitle, String xLabel, String yLabel, JPanel panel) {
JFreeChart xylineChart = ChartFactory.createXYLineChart(
chartTitle ,
xLabel ,
yLabel ,
createDataset() ,
PlotOrientation.VERTICAL ,
true , false , false);
ChartPanel chartPanel = new ChartPanel( xylineChart );
chartPanel.setPreferredSize( panel.getSize() );
final XYPlot plot = xylineChart.getXYPlot( );
plot.setBackgroundPaint(new Color(240, 240, 240));
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true,false);
renderer.setSeriesPaint( 0 , Color.BLACK );
renderer.setSeriesStroke( 0 , new BasicStroke( 4.0f ) );
plot.setRenderer( renderer );
setContentPane(chartPanel);
panel.add(chartPanel);
}
private XYDataset createDataset( ){
final XYSeries seno = new XYSeries ("Sin");
for(double i=0;i<=1440;i++){
double temp=Math.sin(i*((2*Math.PI)/640) + Math.PI) + 1;
seno.add(i/60, temp);
}
final XYSeriesCollection dataset = new XYSeriesCollection( );
dataset.addSeries(seno);
return dataset;
}
public static void runGraph(String appTitle, String chartTitle, String xLabel, String yLabel, JPanel panel) {
XYLineChart_AWT chart = new XYLineChart_AWT(appTitle, chartTitle, xLabel, yLabel, panel);
chart.pack();
chart.setVisible(true);
panel.setVisible(true);
}
}
Esto crea el gráfico y lo coloca en el panel especificado (que envío a través del método runGraph ()). Sin embargo, crea un segundo JFrame (sé que hice chart.setVisible (verdadero) y puedo decir que es falso) que no quiero que se cree fuera del panel que envío.
¿Hay alguna forma de implementar esto que no cree ese jFrame adicional?
P.S .: Otra pregunta: el método setBackgroundPaint () cambia la parte posterior de donde se muestra el gráfico. Sin embargo, las partes donde están el título y la leyenda no cambian. ¿Cómo puedo cambiar esas partes?
Gracias por tu ayuda,
Nhekas