Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / April 2006

Tip: Looking for answers? Try searching our database.

Best way to set an image to a background

Thread view: 
BugFree - 23 Apr 2006 22:24 GMT
Hi again i'm posting to ask the question what is the best way to put an
image on a gui background but still have the ability to place buttons
and text fields on top of it.  My program has a map and I want to place
buttons on each region of the map and some text fields here is how i
did it currently:

((JPanel)getContentPane()).setOpaque(false);
ImageIcon image = new ImageIcon("usamap.gif");
JLabel backlabel = new JLabel(image);
getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0,0,image.getIconWidth(), image.getIconHeight());

But this does not allow me to place buttons or text fields on top of
it.  Any ideas would be greatly apreciated.

Thanks
Konstantinos Dermitzakis - 24 Apr 2006 00:41 GMT
> Hi again i'm posting to ask the question what is the best way to put an
> image on a gui background but still have the ability to place buttons
> and text fields on top of it.  My program has a map and I want to place

read up on overriding paint and paint component before using this code.

[code]
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JPanel{

   private Image img;
   private Dimension dim;
   private JButton button;
   private JButton button2;
   private JButton button3;

   /** New instance of Test */
   public Test(String filename) {
       try{
           img = ImageIO.read(new File(filename));
           dim = new Dimension(img.getWidth(this), img.getHeight(this));

       }catch(IOException ioe){dim = new Dimension(320, 240);}
       init();

       button = new JButton("This is a button on top of the image");
       add(button);

       button2 = new JButton("Another button");
       add(button2);

       button3 = new JButton("Last one");
       add(button3);
   }

   private void init(){
       setSize(dim);
       setMinimumSize(dim);
       setMaximumSize(dim);
       setPreferredSize(dim);
   }

   public void paintComponent(Graphics g){
       super.paintComponent(g);

       if(img != null){
           // This is what you want
           g.drawImage(img, 0, 0, this);
       }
   }

   public static void main(String[] args){
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               JFrame f = new JFrame("test");

               // Change this to a path of your liking
               Test t = new Test("test.jpg");

               f.add(t);
               f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               f.pack();
               f.setVisible(true);
           }
       });
   }
}

[/code]
BugFree - 24 Apr 2006 00:42 GMT
I guess I should tell you that I have found out that the JLabel will
supposrt the textfields but now comes the new problem I have multiple
JPanels that need the same background image but with different text
fields the way i am displaying the image it makes it permanent.... any
help is apreciated.

thanks
BugFree - 24 Apr 2006 01:00 GMT
Konstantinos Dermitzakis thanks for your reply I used that example and
tried something but wasn't sure if I was able to put that to a JPanel
because I couldn't get the image to show up when I did.  The reason for
the JPanel is because i have 4 of them that i have a menu bar to
navigate through i can post my code but it might be very messy and
excuse my variable names not the best ones:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import java.awt.*;

public class GUIUsa extends JFrame implements ActionListener{
    private JButton start, check;
    private JButton[] mapButtons;
    private JLabel title, correct, incorrect;
    private JRadioButton states, capitals, sAC;
    private ButtonGroup group;
    private static JMenuBar bar;
    private JMenu file;
    private JMenuItem oStates, oCaps, statesAndCaps, quit, main;
    private JPanel sel, pState, pCap, pStateCap;
    private JTextField txtState, txtCaps;

    public GUIUsa(){
        start = new JButton("Start");
        states = new JRadioButton("Only States");
        capitals = new JRadioButton("Only Capitals");
        sAC = new JRadioButton("States and Capitals");
        group = new ButtonGroup();

        title = new JLabel(" Welcome, please select the type of game. Then
click start.");

        bar = new JMenuBar();
        file = new JMenu("File");
        oStates = new JMenuItem("Only States");
        oCaps = new JMenuItem("Only Capitals");
        statesAndCaps = new JMenuItem("States and Capitals");
        quit = new JMenuItem("Quit");
        main = new JMenuItem("Main Menu");

        sel = new JPanel();

        pState = new JPanel();
        pState.setLayout(null);

        pCap = new JPanel();
        pCap.setLayout(null);

        pStateCap = new JPanel();
        pStateCap.setLayout(null);

        mapButtons = new JButton[50];

        for(int i=0; i<50; i++)
        {
            mapButtons[i] = new JButton();
        }

        check = new JButton("Check");

        txtState = new JTextField();
        txtCaps = new JTextField();

        Container mainWindow = getContentPane();
        mainWindow.setLayout(null);

        this.setTitle("USA States and Capitals Game");

        sel.setBackground(Color.CYAN);
        sel.setLayout(null);
        sel.setBounds(0, 0, 768, 652);

        sel.add(start);
        sel.add(title);
        sel.add(states);
        sel.add(capitals);
        sel.add(sAC);

        mainWindow.add(sel);
        mainWindow.add(pState);
        mainWindow.add(pCap);
        mainWindow.add(pStateCap);

        sel.setVisible(true);
        pState.setVisible(false);
        pCap.setVisible(false);
        pStateCap.setVisible(false);

        group.add(sAC);
        group.add(states);
        group.add(capitals);

        title.setBounds(10, 15, 400, 20);

        start.setBounds(200, 55, 100, 70);

        sAC.setBounds(10, 50, 130, 20);
        sAC.setBackground(Color.CYAN);

        states.setBounds(10, 80, 130, 20);
        states.setBackground(Color.CYAN);

        capitals.setBounds(10, 110, 130, 20);
        capitals.setBackground(Color.CYAN);

        bar.setBounds(0, 0, 768, 14);

        bar.add(file);
        file.add(main);
        file.add(oStates);
        file.add(oCaps);
        file.add(statesAndCaps);
        file.add(quit);

        sAC.setSelected(true);

        start.addActionListener(this);
        check.addActionListener(this);

        quit.addActionListener(this);
        oStates.addActionListener(this);
        oCaps.addActionListener(this);
        statesAndCaps.addActionListener(this);
        main.addActionListener(this);

        for(int j=0; j<50; j++)
        {
            mapButtons[j].addActionListener(this);
        }

        bar.setVisible(true);
    }

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frm = new GUIUsa();
        frm.setJMenuBar(bar);
        frm.setBounds(400, 300, 768, 652);
        frm.setVisible(true);
        frm.setResizable(false);

    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource().equals((JButton)start))
        {
            JButton jb2 = (JButton)e.getSource();

        if(states.isSelected())
        {
            if(jb2==start)
            {
                sel.setVisible(false);
                pState.setVisible(true);
                pCap.setVisible(false);
                pStateCap.setVisible(false);

                Panel p = new Panel("usamap.gif");
                pState.add(p);
                for(int i=0; i<50; i++)
                {
                    pState.add(mapButtons[i]);
                }

                pState.add(txtState);

                //mapButtons[0].setBounds(50,50,100,100);

                txtState.setBounds(300,150,100,100);

            }

        }
        else if(capitals.isSelected())
        {
            if(jb2==start)
            {
                sel.setVisible(false);
                pState.setVisible(false);
                pCap.setVisible(true);
                pStateCap.setVisible(false);

                ((JPanel)getContentPane()).setOpaque(false);
                ImageIcon i = new ImageIcon("usamap.gif");
                JLabel backlabel = new JLabel(i);
                getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
                backlabel.setBounds(0,0,i.getIconWidth(), i.getIconHeight());

        }
        }
        else
        {
            if(jb2==start)
            {
                sel.setVisible(false);
                pState.setVisible(false);
                pCap.setVisible(false);
                pStateCap.setVisible(true);

                //((JPanel)getContentPane()).setOpaque(false);
                ImageIcon i = new ImageIcon("usamap.gif");
                JLabel backlabel = new JLabel(i);
                getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
                backlabel.setBounds(0,0,i.getIconWidth(), i.getIconHeight());
            }

        }
        }
        else if(e.getSource().equals((JMenuItem)main)){
            sel.setVisible(true);
            pState.setVisible(false);
            pCap.setVisible(false);
            pStateCap.setVisible(false);
        }
        else if(e.getSource().equals((JMenuItem)oStates)){
            sel.setVisible(false);
            pState.setVisible(true);
            pCap.setVisible(false);
            pStateCap.setVisible(false);

            //((JPanel)getContentPane()).setOpaque(false);
            ImageIcon i = new ImageIcon("usamap.gif");
            JLabel backlabel = new JLabel(i);
            getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
            backlabel.setBounds(0,0,i.getIconWidth(), i.getIconHeight());
        }
        else if(e.getSource().equals((JMenuItem)oCaps)){
            sel.setVisible(false);
            pState.setVisible(false);
            pCap.setVisible(true);
            pStateCap.setVisible(false);

            //((JPanel)getContentPane()).setOpaque(false);
            ImageIcon i = new ImageIcon("usamap.gif");
            JLabel backlabel = new JLabel(i);
            getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
            backlabel.setBounds(0,0,i.getIconWidth(), i.getIconHeight());
        }
        else if(e.getSource().equals((JMenuItem)statesAndCaps)){
            sel.setVisible(false);
            pState.setVisible(false);
            pCap.setVisible(false);
            pStateCap.setVisible(true);

            //((JPanel)getContentPane()).setOpaque(false);
            ImageIcon i = new ImageIcon("usamap.gif");
            JLabel backlabel = new JLabel(i);
            getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
            backlabel.setBounds(0,0,i.getIconWidth(), i.getIconHeight());
        }
        else if(e.getSource().equals((JMenuItem)quit)){
            System.exit(0);
        }

    }

}

Please remember I'm a newbie at gui's so i'm sorry if its confusing

Thanks
BugFree
Konstantinos Dermitzakis - 24 Apr 2006 01:53 GMT
...

Sorry, i dont have time to check all the code just now. What i advise you to
do is:

Add a ioe.printStackTrace() as such:

catch(IOException ioe){
dim = new Dimension(320, 240);
ioe.printStackTrace();
}

in the Test.java i gave you (that i presume you renamed as Panel.java (?)).

This will notify you if the image could not be loaded off the disk.

Then test the class itself by running it by itself with the image you want
displayed in the same folder.

After you make sure the class works by itself, what you want to
check/replace:

-  remove all the JLabels with the images you have at the moment,
-  replace all the JPanels you want to contain the image with the Panel
class and the appropriate image,
-  check if you have what you want,

by then maybe someone else can help you or i might have finished my exam,

best of luck

 - exe
Thomas Weidenfeller - 24 Apr 2006 08:20 GMT
> Hi again i'm posting to ask the question what is the best way to put an
> image on a gui background but still have the ability to place buttons
> and text fields on top of it.  My program has a map and I want to place
> buttons on each region of the map and some text fields here is how i
> did it currently:

Forget about the JLabels and draw everything with the Java 2D API (part
of the SE). You anyhow have to override a JPanel's paintComponent()
method to draw the background. So instead of messing with Components and
2D drawing, just use 2D drawing.

/Thomas
Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/

BugFree - 24 Apr 2006 14:40 GMT
i'm not sure how to use the 2d graphics is there examples of something
like that on how i should do that.

BugFree


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.