File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Problem in reloading graphics object. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Problem in reloading graphics object." Watch "Problem in reloading graphics object." New topic

Problem in reloading graphics object.

Mumtaz Khan
Ranch Hand

Joined: Feb 21, 2008
Posts: 53

I am very new to swing and java awt. I am trying an application where I have 2 panels in main container. First panel (p1)contains some data and a button , upon click of button, Second panel (p2) has to draw a graph based on the content of first panel.
To draw the graph I am creating another class called secondPanel and passing p2 in the constructor, to get the graphics object of p2 to draw the graph.
The problem I am getting is when I change the data and redo the graph it retains the old graph. As I understand it is because of the graphics object that I am getting from p2.
before passing object p2 to the constructor of SecondPanel, I am calling removeAll() and validate() on p2, however my graphics object is not recreated.
Really appreciate if someone can help me here. Here is the code snippet of SecondPanel.

In the main container here is my code of reloading p2
How can I reload the graphics. while using super.paintComponent(g), I am getting null pointer exception and I don't know whether graphics object obtained by super will fit my requirement.
Thanks in advance!!!.

SCJP 5.0 -- 97%
Rok Štelcer
Ranch Hand

Joined: Nov 03, 2009
Posts: 101

I'm not sure what are you trying to achive.
Let me summirize it:
  • SecondPanel extends JPanel
  • It's only member is JPanel
  • When SecondPanel is created, you add the ref from a foo JPanel
  • Afterwards you add the SecondPanel to foo

  • A bit complicated, don't you think? ;)
    You should use a CardLayout (p1 vs. p2).

    Anyhow ... usually an invalidate() and repaint() on the component should do the trick.


    Mumtaz Khan
    Ranch Hand

    Joined: Feb 21, 2008
    Posts: 53
    Yeah it was a bit complicated . So I changed my approach instead of using another class, I am using an inner class that extends JPanel and it works. The code posted above was not working even with invalidate and repaint may be because I was not calling super.paintComponent(g); .I think this needs to be called for repainting graphics object.
    I agree. Here's the link:
    subject: Problem in reloading graphics object.
    It's not a secret anymore!