Como inserir um gráfico JFreeChart em um painel em uma GUI separada?
Quero colocar um gráfico dentro de um painel específico em uma GUI usando o JFreeChart. Eu tenho 2 arquivos java (um com a GUI e outro que cria o gráfico) e gostaria, se possível, de mantê-lo dessa maneira.
Na GUI principal, tenho um painel chamado panelGraph:
JPanel panelGraph = new JPanel();
panelGraph.setBounds(220, 64, 329, 250);
panelMain.add(panelGraph); //it is inside the main panel
panelGraph.setLayout(null);
E também tenho um botão que aciona a aparência do 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);
E da seguinte forma, é o arquivo java que cria o 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);
}
}
Isso cria o gráfico e o coloca no painel especificado (que eu envio através do método runGraph ()). No entanto, ele cria um segundo JFrame (eu sei que criei chart.setVisible (true) e posso apenas colocá-lo como false)) que não quero ser criado fora do painel que envio.
Existe alguma maneira de implementar isso que não crie esse jFrame extra?
P.S .: Outra pergunta: o método setBackgroundPaint () altera a parte traseira de onde o gráfico é mostrado. No entanto, as partes onde o título e a legenda estão não mudam. Como posso alterar essas partes?
Obrigado pela ajuda,
Nhekas