Repaint does not call paintComponent.

Asked 1 years ago, Updated 1 years ago, 77 views

public class BI2DPv extensions javax.swing.JPanel{
    BufferedImage bi;// Draw to this and then transfer to g2
    @ Override
    public void paintComponent (Graphics g) {
        // super.paintComponent(g);
        Graphics 2D g2=(Graphics 2D)g;
        logger.log(Level.INFO, "Entered in paintComponent");
        // paintComponent (repaint) simply transcribes bi to g2.
        if(bi!=null)g2.drawImage(bi,null,this);
    }
    //bi is generated by a different method.
}

We have prepared a class for Java 2D drawing that inherits JPanel.Generating an instance of BI2DPv in the main class and running bi2dpv.repaint(); does not run paintComponent; I have seen in the log that bi2dpv.repaint(); is called.

java swing

2022-09-29 22:20

1 Answers

I don't know what BI2DPv#repaint() is called, so I guess that JPanel has not been added to top-level containers such as JFrame or Japplet.

Note: Top-Level Containers and Containment Hierarchies (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

For example, the following sample code runs bi2dpv.repaint(); every second, but comments out return bi2dpv; and runs return new JPanel(); and hides bi2dpv in JFrame.

Sample Code Edit:Change to add bi2dpv to JTabbedPane

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class BI2DPv extensions JPanel {
  BufferedImage bi;// Draw to this and then transfer to g2
  @ Override
  public void paintComponent (Graphics g) {
    super.paintComponent(g);
    Graphics 2D g2=(Graphics 2D)g;
    // logger.log(Level.INFO, "Entered in paintComponent");
    System.out.println("paintComponent");
    // paintComponent (repaint) simply transcribes bi to g2.
    if(bi!=null){
      g2.drawImage(bi, null, this);
    }
  }
  //bi is generated by a different method.

  private static JComponent makeUI() {
    JPanel bi2dpv = new BI2DPv();
    new Timer (1000, e->{
      System.out.println("\nbi2dpv.repaint()");
      System.out.println("isDisplayable?"+bi2dpv.isDisplayable());
      System.out.println("isShowing?"+bi2dpv.isShowing());
      System.out.println("isVisible?"+bi2dpv.isVisible());
      bi2dpv.repaint();
    }).start();

    JTabbedPane tabbedPane=new JTabbedPane();
    tabbedPane.addTab("aaa", newJPanel());
    tabbedPane.addTab("bbb", bi2dpv);
    return tabbedPane;
    // return new JPanel();
  }
  public static void main(String...args) {
    EventQueue.invokeLater(()->{
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(makeUI());
      f.setSize (320,240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}


2022-09-29 22:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.