paintComponent on JPanel, image flashes and then disappears


December 2018


1.2k time


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();

chartwindow has a Grafico instance.

it's the ChartWindow's paintComponent (override)

paintComponent(Graphics g)
    Image immagineGrafico=createImage(grafico.pannelloGrafico.getWidth()
     Image immagineVolumi=createImage(grafico.pannelloVolumi.getWidth()
  Graphics2D imgGrafico=(Graphics2D)immagineGrafico.getGraphics();
  Graphics2D imgVolumi=(Graphics2D)immagineVolumi.getGraphics();


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

grafico=new Grafico()

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

1 answers


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

     class PanelloVolumi extends JPanel{
         //some code

         public void paintComponent(Graphics g){

             //paint one image here


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

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