How to have an image as JPanel Background?

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 2136 Views - Last Post: 04 April 2013 - 07:16 PM Rate Topic: -----

#1 DarrenKingUS  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 02-April 13

How to have an image as JPanel Background?

Posted 02 April 2013 - 07:38 AM

Hello all,
I'm very new to this site, as you may say the same for my Java experience. I just started Java 4 months ago and have been striving up until this point. I'm selve teaching my selve through many resources, the main one is a Java book handed down by my IT Instructor, "Java Fundamentals - Data Structures" Yadadadada, and its primaily getting you started with the language. Just a week ago it touched on GUI, I longed for more after the chapter and learned a good deal of the basics. What I'm trying to achieve is a background image and then all my components on top of it. Sort of like a Kiosk Feel it takes up the whole screen. I retrieve the screen size and set that as the height and width, I then setDecorations to false and set visible. My plan was to make a JPanel named masterPanel that would hold the image, then have a componentPanel that would lay over top of it using a gridLayout or borderLayout. I create a JLabel for the masterPanel that holds the image. I dont quite understand the code I use for retrieving the image, but it works. I will get back to it later in understanding it. The issue then comes along when I set the gridLayout manager to the componentLayout, by then adding more panels(having their own grid layout) to accomodate more components. I then add these panels which contain panels to the componentPanel, which then finally gets layered on top(added) to the masterPanel. When I run the program, components show and everything! Sadly no background image. I know though for a fact that its retrieving the image, as I ran the program once with just the masterPanel. Please explain your reasoning as some of your programming methods I might not even have come accross upon. Or is what I'm trying to do way over my head?

Is This A Good Question/Topic? 0
  • +

Replies To: How to have an image as JPanel Background?

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How to have an image as JPanel Background?

Posted 02 April 2013 - 07:44 AM

You have to overload the paint(Graphics g) method of the JPanel
- draw the image
- set the JPanel opaque to false before calling the super.paint() so the standard paint() won't redraw the background
- call suoper.paint();
- reset opaque to true
- do your own drawing if you have your own to do (not only JComponent in your JPanel)

Happy coding
Was This Post Helpful? 1
  • +
  • -

#3 DarrenKingUS  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 02-April 13

Re: How to have an image as JPanel Background?

Posted 02 April 2013 - 08:02 AM

That comes so close to making sense to me,
First off, Thanks for the fast reply,
but could you explain to me this paint(Graphics g) method of the JPanel, are you reffering to the masterPanel or the componentPanel?
and how do I call super.paint()?
Whats this term of drawing and drawing an image?
Thanks!
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How to have an image as JPanel Background?

Posted 02 April 2013 - 08:14 AM

All JPanel have a public void paint(Graophics g) method which is called when the JPanel needs to be repaint
This method:
- draws the background
- calls the paintComponent() method of all the JComponent included in the JPanel
- draws the Border of the JPanel

So you first have to have a class that extends JPanel so you can overlead its paint() method
Then you'll have to add in your class that extends JPanel

    public void paint(Graphics g) {
       g.drawImage(image, ... comes in multiple flavors looks at the Graphics class in the API
       setOpaque(false);
       super.paint(g);
       setOpaque(true);
   }


http://docs.oracle.c...t/Graphics.html
Was This Post Helpful? 0
  • +
  • -

#5 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,534
  • Joined: 29-July 11

Re: How to have an image as JPanel Background?

Posted 02 April 2013 - 02:37 PM

Hmmmmm. You should not even have to worry about setOpaque, as the background is going to draw every pixel inside the JPanel anyway. You should be able to just override paintComponent and use drawimage to draw it in there. There's even no need to call up to super.paintComponent. Then you should also be able to add components to the panel as usual.
Was This Post Helpful? -1
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How to have an image as JPanel Background?

Posted 02 April 2013 - 06:44 PM

View Postfarrell2k, on 02 April 2013 - 05:37 PM, said:

Hmmmmm. You should not even have to worry about setOpaque, as the background is going to draw every pixel inside the JPanel anyway. You should be able to just override paintComponent and use drawimage to draw it in there. There's even no need to call up to super.paintComponent. Then you should also be able to add components to the panel as usual.

Male Cattle Excrement... to be polite
I think you miss some points here
Try it if you are so clever.
.. or use Eclipse or NetBeans GUI designers and see how they implement this :v:/>


*Edited: yes, my mistake, it will work for JPanel
My algorithme works for any JComponent though and this is why I also applied it to a JPanel which is a JComponent any other

This post has been edited by pbl: 04 April 2013 - 01:54 PM

Was This Post Helpful? 0
  • +
  • -

#7 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,534
  • Joined: 29-July 11

Re: How to have an image as JPanel Background?

Posted 03 April 2013 - 01:27 AM

You sure about that pbl? :)

What is really neat is that if I load the background Image with ImageIcon.getImage() and use a timer to repaint() every 100ms, I can even watch the animated gif. I've included it in case anyone wants to try it.

public class ImageBackgroundPanel extends JPanel { 
    private Image background;
    
    private JButton button;
    private JList<String> list;
    private JTextField textField;
    private JLabel label;
    private JTextArea textArea;
    private JComboBox<Integer> comboBox;
    
    public ImageBackgroundPanel() {
        loadImage();
        setPreferredSize(new Dimension(background.getWidth(null), background.getHeight(null)));
        buildGui();
    }
    
    @SuppressWarnings("CallToThreadDumpStack")
    private void loadImage() {
        try {
            Image temp = ImageIO.read(getClass().getResource("galagaanimated.gif"));
            //image is too small, so let's resize it.
            background = temp.getScaledInstance(temp.getWidth(null) * 2, temp.getHeight(null) * 2, Image.SCALE_SMOOTH);
        } catch(IOException e) {
            e.printStackTrace();
        } 
    }
    
    private void buildGui() {
        //instantiate ui components.
        button = new JButton("Click");
        list = new JList<>(new String[] {"Does", "it", "work?"});
        textField = new JTextField();
        textField.setText("Yes it does!");
        label = new JLabel("I rule, as usual.");
        textArea = new JTextArea(10,10);
        comboBox = new JComboBox<>(new Integer[] {0,1,2,3,4,5,6,7,8,9});
        add(button);
        add(list);
        add(textField);
        add(label);
        add(textArea);
        add(comboBox);
    }

      @Override
    public void paintComponent(Graphics g) {
        g.drawImage(background, 0, 0 , getWidth(), getHeight(), null);
    }
}



JFrame:

public class PBLGrumpy extends JFrame {

    public PBLGrumpy() {
        setTitle("PBL is Grumpy!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setBackground(Color.green);
        add(new ImageBackgroundPanel());
        pack();
        setVisible(true);
        setLocationRelativeTo(null);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PBLGrumpy();
            }
        });
    }
}


This post has been edited by farrell2k: 03 April 2013 - 01:42 AM

Was This Post Helpful? 1
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How to have an image as JPanel Background?

Posted 03 April 2013 - 03:43 AM

Try it with a BorderLayout

*Edited: my bad. Yes it will work with a JPanel

This post has been edited by pbl: 04 April 2013 - 01:55 PM

Was This Post Helpful? 0
  • +
  • -

#9 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,534
  • Joined: 29-July 11

Re: How to have an image as JPanel Background?

Posted 03 April 2013 - 04:52 AM

No problem. Let's animate it to make it a little more fun though.

public class ImageBackgroundPanel extends JPanel implements ActionListener { 
    private Image background;
    
    private JButton button;
    private JList<String> list;
    private JTextField textField;
    private JLabel label;
    private JTextArea textArea;
    private JComboBox<Integer> comboBox;
    
    private Timer timer;
    
    public ImageBackgroundPanel() {
        loadImage();
        setPreferredSize(new Dimension(800,800));
        buildGui();
        timer = new Timer(100, this);
        timer.start();
    }
    
    @SuppressWarnings("CallToThreadDumpStack")
    private void loadImage() {
        //loads asynchronously, so let's use a timer to repaint and do some animation with the gif.
        background = new ImageIcon(getClass().getResource("galagaanimated.gif")).getImage();
    }
    
    private void buildGui() {
        //instantiate ui components.
        button = new JButton("Click");
        list = new JList<>(new String[] {"Does", "it", "work?"});
        textField = new JTextField();
        textField.setText("Yes it does!");
        label = new JLabel("I rule, as usual.");
        textArea = new JTextArea(10,10);
        textArea.setText("Yeah, it works...");
        comboBox = new JComboBox<>(new Integer[] {0,1,2,3,4,5,6,7,8,9});
        
        setLayout(new BorderLayout());
        
        JPanel northPanel = new JPanel() {
            {
                setOpaque(false);
                ((FlowLayout)getLayout()).setHgap(10);
                add(button);
                add(list);
            }
        };
        
        JPanel southPanel = new JPanel() {
            {
                setOpaque(false);
                ((FlowLayout)getLayout()).setHgap(10);
                add(textField);
                add(label);
            }
        };
        
        JPanel eastPanel = new JPanel() {
            {
                setOpaque(false);
                ((FlowLayout)getLayout()).setHgap(10);
                add(textArea);
                add(comboBox);
            }
        };

        JPanel westPanel = new JPanel() {
            {
                setOpaque(false);
                ((FlowLayout)getLayout()).setHgap(10);
                add(new JButton("Button 1"));
                add(new JButton("Button 2"));
            }
        };
        
        JPanel centerPanel = new JPanel() {
            {
                setPreferredSize(new Dimension(100,100));
            }
            
            public void paintComponent(Graphics graphics) {
                Graphics2D g = (Graphics2D)graphics;
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, .25f));
                g.setColor(Color.green);
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        
        add(centerPanel, BorderLayout.CENTER);
        add(northPanel, BorderLayout.NORTH);
        add(southPanel, BorderLayout.SOUTH);
        add(eastPanel, BorderLayout.EAST);
        add(westPanel, BorderLayout.WEST);
    }

      @Override
    public void paintComponent(Graphics g) {
       if(background != null) {  
            g.drawImage(background, 0, 0 , getWidth(), getHeight(), null);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}


This post has been edited by farrell2k: 03 April 2013 - 04:55 AM

Was This Post Helpful? 1
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How to have an image as JPanel Background?

Posted 04 April 2013 - 05:01 AM

+1 in the previous post to cancel the one on post #5

farrell2k I must admit that you puzzled me.

Years ago, I worked hard for the trick of:
- drawImage
- setOpaque(false)
- super.paint()
- setOpaque(true)

I even wrote a snippet about it, snippet toward which I would have re-direct the OP if the Snippet Section has been opened.

How come you came here with a solution that easy ? I was really wandering, where did I go wrong ? How conme I complicated my life during so many years ?

Just found it :)/> Yes your solution works for JPanel because there is nothing in a JPanel so the drawComponent() method has nothing to draw but the backgound. My solution works for any JComponent and this is what my code snippet explained.

import javax.swing.*;
import java.io.*;
import java.awt.*;
import javax.imageio.*;

public class ImageBackgroundPanel extends JPanel { 
	private Image background;

	private JButton button;
	private JList list;
	private JTextField textField;
	private JLabel label;
	private JTextArea textArea;
	private JComboBox comboBox;

	public ImageBackgroundPanel() {
		loadImage();
		setPreferredSize(new Dimension(background.getWidth(null), background.getHeight(null)));
		buildGui();
	}

	@SuppressWarnings("CallToThreadDumpStack")
	private void loadImage() {
		try {
			Image temp = ImageIO.read(getClass().getResource("back.jpg"));
			//image is too small, so let's resize it.
			background = temp.getScaledInstance(temp.getWidth(null) * 2, temp.getHeight(null) * 2, Image.SCALE_SMOOTH);
		} catch(IOException e) {
			e.printStackTrace();
		} 
	}

	private void buildGui() {
		//instantiate ui components.
		button = new JButton("Click");
		list = new JList(new String[] {"Does", "it", "work?"});
		textField = new JTextField();
		textField.setText("Yes it does!");
		label = new MyLabel("I rule, as usual.");
		textArea = new JTextArea(10,10);
		comboBox = new MyCombo (new Integer[] {0,1,2,3,4,5,6,7,8,9});
		add(button);
		add(list);
		add(textField);
		add(label);
		add(textArea);
		add(comboBox);
	}

	class MyCombo extends JComboBox {
		MyCombo(Integer[] array) {
			super(array);
		}
		@Override
		public void paintComponent(Graphics g) {
			g.drawImage(background, 0, 0 , getWidth(), getHeight(), null);
		}
	}
	
	class MyLabel extends JLabel {
		MyLabel(String title) {
			super(title);
		}
		@Override
		// no need for the setOpaque() here as JLabel are not opaque by default
		public void paint(Graphics g) {
			g.drawImage(background, 0, 0 , getWidth(), getHeight(), null);
			super.paint(g);
		}
	}
}



So sorry I apologise for the "Male cattle excrement" and yes when using JPanel overloading paintComponent() is enough, for other JComponent (and JPanel if you which to uniformize your method) you'll need my solution

:^:/>

This post has been edited by pbl: 04 April 2013 - 01:57 PM
Reason for edit:: Explaining the +1 on the previous post

Was This Post Helpful? 0
  • +
  • -

#11 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,534
  • Joined: 29-July 11

Re: How to have an image as JPanel Background?

Posted 04 April 2013 - 05:47 AM

No worries, dude. I never took offense. I am glad I got to push your buttons. :lol:/>

EDIT: Not really. I didn't mean to aggravate you. I was only joking. It was a fun exercise, which is why I did it.

It will also work just fine with JComponent.

This post has been edited by farrell2k: 04 April 2013 - 06:08 AM

Was This Post Helpful? 0
  • +
  • -

#12 DarrenKingUS  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 02-April 13

Re: How to have an image as JPanel Background?

Posted 04 April 2013 - 07:44 AM

Thanks all,
While I understand some of the code,
I'm still faced with an issue...
I'm going for a full screen undecorated look.
I can achieve the no decorations part.
But when I retrieve the screen size and setExtendedState(mainFrame.true)
errors galore appear...I just want it to take up the entire screen with no visuals of the desktop unless you hit the start key.
Was This Post Helpful? 0
  • +
  • -

#13 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,534
  • Joined: 29-July 11

Re: How to have an image as JPanel Background?

Posted 04 April 2013 - 08:00 AM

My example works fine for me if I replace

pack();



with

setUndecorated(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);


Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How to have an image as JPanel Background?

Posted 04 April 2013 - 08:49 AM

View Postfarrell2k, on 04 April 2013 - 08:47 AM, said:

It will also work just fine with JComponent.

:) :) No it won't as my posted code shows
It works with JPanel because they do not display anything
but a JLabel or JCombo box it is it's paintComponent() that draws the displayed text
if you overload it, you'll have your image in the background but not the text that should be displayed
Was This Post Helpful? 0
  • +
  • -

#15 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,534
  • Joined: 29-July 11

Re: How to have an image as JPanel Background?

Posted 04 April 2013 - 12:49 PM

My example, not yours, works just fine with JComponent.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2