Results 1 to 3 of 3
  1. #1
    cahyadiakbar is offline Member
    Join Date
    Aug 2010
    Posts
    5
    Rep Power
    0

    Default change panel background at runtime

    Please help me. I want to change my panel background at runtime but the image isn't show directly. this is my snippet code:

    public class GpanelBack extends JPanel {

    private Image image;

    public GpanelBack() {
    image = new ImageIcon("last/back.jpg").getImage();
    }

    public void setImgBack() {
    image = new ImageIcon("last/back.jpg").getImage();
    repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D gd = (Graphics2D) g.create();
    gd.drawImage(image, 0, 0, getWidth(), getHeight(), null);
    gd.dispose();
    }
    }

    , in jframe I have created the methode to read image from disk and saving it to "last/back.jpg" . after that I use this code to repaint the panel background:
    jback.setImgBack();
    jback.repaint();

    NB: jback is instant of GPanelBack.

    is anything wrong with my code ??

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default

    An easier way to display an image is as an ImageIcon set to a JLabel. If you really need to use a JPanel and a paintComponent(...) override, try loding the image using ImageIO#read(...) which blocks until the image is fully read from file, unlike the Toolkit method used by ImageIcon to load the image.

    All else aside, it's rather silly to construct an ImageIcon just to extract its image when there are other classes (ImgeIO, Toolkit) which have methods to load an image without incurring the overhead of ImageIcon.

    db

  3. #3
    cahyadiakbar is offline Member
    Join Date
    Aug 2010
    Posts
    5
    Rep Power
    0

    Default

    Ok. Thanx for your advice. I will try to use ImageIO in my code.

Similar Threads

  1. Change JPanel background after its been set once
    By mevets in forum AWT / Swing
    Replies: 4
    Last Post: 04-14-2010, 01:07 AM
  2. unable to change the TextArea.background !
    By Y. Progammer in forum New To Java
    Replies: 2
    Last Post: 02-28-2010, 04:55 PM
  3. change Panel Color
    By aadi_j in forum AWT / Swing
    Replies: 2
    Last Post: 11-16-2009, 10:12 AM
  4. run command in the background ( useing runtime)
    By itaipee in forum New To Java
    Replies: 7
    Last Post: 03-17-2009, 04:08 PM
  5. when muse pressed the background change
    By pcman in forum Java Applets
    Replies: 1
    Last Post: 03-17-2008, 11:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •