paintComponent on JPanel, image flashes and then disappears

Refresh

December 2018

Views

1.2k time

3

I have a JApplet (MainClass extends JApplet), a JPanel (ChartWindow extends JPanel) and a Grafico class.

The problem is that the Grafico class instance has 2 JPanel that should show 2 images (1 for each panel) but the images are shown and after a little while they disappears: instead of them i get a gray background (like an empty JPanel). This happens for every repaint() call (that are made in the ChartWindow class)

the MainClass init() contains

chartwindow=new ChartWindow();
add(chartwindow)

chartwindow has a Grafico instance.

it's the ChartWindow's paintComponent (override)

paintComponent(Graphics g)
{
    super.paintComponent(g);
    Image immagineGrafico=createImage(grafico.pannelloGrafico.getWidth()
          ,grafico.pannelloGrafico.getHeight()); 
     Image immagineVolumi=createImage(grafico.pannelloVolumi.getWidth()
      ,grafico.pannelloVolumi.getHeight());
  Graphics2D imgGrafico=(Graphics2D)immagineGrafico.getGraphics();
  Graphics2D imgVolumi=(Graphics2D)immagineVolumi.getGraphics();
  grafico.draw(imgGrafico,imgVolumi,mouseX,mouseY);

  ((Graphics2D)grafico.pannelloGrafico.getGraphics()).drawImage(immagineGrafico,0,0,this);
  ((Graphics2D)grafico.pannelloVolumi.getGraphics()).drawImage(immagineVolumi,0,0,this);
}

grafico's JPanels are added this way in the ChartWindow's constructor

grafico=new Grafico()
................
add(grafico.pannelloGrafico);
add(grafico.pannelloVolumi);

Tell me if you need more information, thank you very much :-)

1 answers

2

Вы должны переопределить paintComponent в JPanel, а не окно графика, если вы хотите, чтобы рисовать на них. Что происходит, что каждый JPanel краски сама краска по умолчанию будет перезаписывать ваши изображения.

     class PanelloVolumi extends JPanel{
         //some code

         public void paintComponent(Graphics g){

             //paint one image here
         }

     }

И сделать то же самое для других JPanel.

Затем добавьте экземпляры этих JPanel, на ваш апплет.