Link to home
Start Free TrialLog in
Avatar of Predikshon
Predikshon

asked on

Refreshing the panel

i have a simple paint component method to display an image middle of the frame.
public void paintComponent(Graphics g)
{
   super.paintComponent(g);
   g.drawImage(img.getImage(),(this.getWidth()-img.getIconWidth())/2,(this.getHeight() - img.getIconHeight())/2,null);
}
This method is called when a menu item is clicked and drawn into a panel. The picture doesnt appear immediately when the menu option is clicked. It appears only when i resize the frame. The other problem is that when i resize the frame the picture gets displayed in the new center with the old one still remaining. How do i remove the old one and make the picture appear when i click the menu option itself.

                   
                     
Avatar of Mick Barry
Mick Barry
Flag of Australia image

You should not call paintComponent() directly.
can u post the code that is invoked when the menu item is pressed?
Avatar of Predikshon
Predikshon

ASKER

In the JFrame constructor i create the menu "view" and add the item "center" in it,
then i add an ActionListener,
centerItem.addActionListener(this);

overriding the actionPerformed i did this,


if (source == centerItem)
{
  JPanel panel = new JPanel(){
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    g.drawImage(img.getImage(),(this.getWidth()-img.getIconWidth())/2,(this.getHeight() - img.getIconHeight())/2,null);
      };
  }
  panel.setOpaque(false);
  this.setContentPane(panel3);
}

i'm implementing the actionListener() and this refers to the frame.
sorry its,
this.setContentPane(panel);
in the last line

cheers
Try this:

...
this.setContentPane(panel3);
this.revalidate();
}
the revalidate method helped me in displaying the image when i clicked on the menu item. thx. but still the image doesnt go when i resize, the old image in the old position is still there. I need the old image to go and the new position in its new center.

cheers
try clearing the background of your panel when it repaints.

 public void paintComponent(Graphics g)
 {
   super.paintComponent(g);
   g.setColor(getBackground());
   g.fillRect(0, 0, getWidth(), getHeight());
   g.drawImage(img.getImage(),(this.getWidth()-img.getIconWidth())/2,(this.getHeight() - img.getIconHeight())/2,null);
     };
 }
thanks a lot man it works..:-)
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you :-)