How can I update a JLabel?

0

I need to update a JLabel every time I press a particular button that looks for a database form to generate a chart, but this only works the first time. My idea was this: if JLabel is empty it adds the graph generated by the search, if it is filled it would remove the graph and put the new one. This way my JFrame looks like this:

public class MyFrame extends JFrame {

    private JPanel contentPane;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyFrame frame = new MyFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblMeuIcone = new JLabel("");
        lblMeuIcone.setBounds(23, 11, 363, 205);
        contentPane.add(lblMeuIcone);

        JButton btnTrocarI = new JButton("TrocarImagem");
        btnTrocarI.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                GeradorDeGraficos graficos = new GeradorDeGraficos();
                int[] valores = {1,1,2,23,3};
                graficos.graficoPeriodoDeCrescimento(valores, "grafico 01", "valores", "valores");
                try {
                    graficos.salvarGrafico(new FileOutputStream("MyChart01.png"));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(lblMeuIcone.getIcon() == null) {
                    File file = new File("MyChart01.png");
                    ImageIcon icon = new ImageIcon(file.getAbsolutePath());
                    lblMeuIcone.setIcon(icon);
                    }else {
                        lblMeuIcone.setIcon(null);
                        File file = new File("MyChart01.png");
                        ImageIcon icon = new ImageIcon(file.getAbsolutePath());
                        lblMeuIcone.setIcon(icon);
                    }
            }
        });
        btnTrocarI.setBounds(70, 227, 89, 23);
        contentPane.add(btnTrocarI);

        JButton btnTrocarII = new JButton("Trocar nova");
        btnTrocarII.setBounds(311, 227, 89, 23);
        btnTrocarII.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                GeradorDeGraficos graficos = new GeradorDeGraficos();
                int[] valores = {10,5,6,23,33};
                graficos.graficoPeriodoDeCrescimento(valores, "grafico 02", "valores", "valores");
                try {
                    graficos.salvarGrafico(new FileOutputStream("MyChart01.png"));
                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                if(lblMeuIcone.getIcon() == null) {
                File file = new File("MyChart01.png");
                ImageIcon icon = new ImageIcon(file.getAbsolutePath());
                lblMeuIcone.setIcon(icon);
                }else {
                    lblMeuIcone.setIcon(null);
                    File file = new File("MyChart01.png");
                    ImageIcon icon = new ImageIcon(file.getAbsolutePath());
                    lblMeuIcone.setIcon(icon);
                }
                }

        });
        contentPane.add(btnTrocarII);
    }

}

Class that generates the graph

public class GeradorDeGraficos {
    private double[] valores;
    private int inicio;
    private int fim;

    float dash[] = { 10.f };

    private DefaultCategoryDataset data;
    private JFreeChart grafico;
    private JFreeChart graficoDeLinha;

    public JFreeChart graficoPeriodoDeCrescimento(int[] lista, String titulo, String labelBottom, String labelLeft) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        try {
            for (int i = 0; i < lista.length; i++) {
                dataset.addValue(lista[i], "Média", "valor" + i);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "deu pau no grafico");
        }

        graficoDeLinha = ChartFactory.createLineChart(titulo, labelBottom, labelLeft, dataset, PlotOrientation.VERTICAL,
                true, true, false);

        // fonte
        Font fonteNova = new Font("TimesRoman", Font.PLAIN, 18);

        CategoryItemRenderer renderer = graficoDeLinha.getCategoryPlot().getRenderer();

        CategoryPlot plot = graficoDeLinha.getCategoryPlot();

        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.GREEN);
        plot.setAxisOffset(new RectangleInsets(12.0, 12.0, 5.0, 5.0));
        plot.setRangeGridlinePaint(Color.RED);
        // cor e linha das séries
        renderer.setSeriesPaint(0, Color.BLUE);
        renderer.setSeriesStroke(0,
                new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.f, dash, 0.0f));
        renderer.setSeriesPositiveItemLabelPosition(0,
                new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_CENTER));
        renderer.setSeriesOutlineStroke(0,
                new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.f, dash, 0.0f));
        renderer.setSeriesOutlinePaint(0, Color.GREEN);

        // legendas
        LegendItemCollection legendas = new LegendItemCollection();
        LegendItem legenda1 = new LegendItem("Crescimento");
        legenda1.setSeriesIndex(0);
        legenda1.setFillPaint(Color.BLUE);
        legenda1.setLabelPaint(Color.BLUE);
        legenda1.setLabelFont(fonteNova);
        legendas.add(legenda1);

        plot.setFixedLegendItems(legendas);

        return graficoDeLinha;

    }

    public void salvarGrafico(OutputStream out) throws IOException {
        ChartUtilities.writeChartAsPNG(out, graficoDeLinha, 300, 200);
    }

}

Any doubt is just to speak

    
asked by anonymous 27.03.2018 / 01:47

1 answer

0

By ImageIcon documentation, the constructor used in code - ImageIcon(String) - uses MediaTracker to load the image. The 'MeidaTracker saves the image in a cache and uses this image instead of reading again from the same file - as the file name has not changed, it is assumed that the image has not changed.

Workaround: Use ImageIO to read image and constructor ImageIcon(Image) :

// gerar gráfico e salvar em 'file'

BufferedImage img;
try {
    img = ImageIO.read(file);
} catch (IOException ex) {
    ex.printStackTrace();
    return;
}
ImageIcon icon = new ImageIcon(img);
label.setIcon(icon);
    
27.03.2018 / 14:02