1

Possible Duplicate:
How to set an image as a background for Frame in Swing GUI of java?

I'm having trouble figuring out how to set a background image on my window. I'm not sure whats wrong with my code. The image is called Background.jpg
Does anyone know what I'm doing wrong with my code and how it can be fixed

//apples code  

import javax.swing.JFrame;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;

class  Apples{

public static void main(String[] args) {
  gui go = new gui();
  go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  go.setSize(200,290);
  go.setVisible(true);



 }
}



 //Gui Code

    import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class gui extends JFrame{
     private JButton A;
     private JButton B;
     private JButton C;
     private JButton D;
     private JButton E;
     private JButton F;
     private JButton G;
     private JButton H;
     private JButton I;
     private JButton J;
     private JButton K;
     private JButton L;
     private JButton M;
     private JButton N;
     private JButton O;
     private JButton P;
     private JButton Q;
     private JButton R;
     private JButton S;
     private JButton T;
     private JButton U;
     private JButton V;
     private JButton W;
     private JButton X;
     private JButton Y;
     private JButton Z;

     public gui(){
        super("APUSH ABCs");
        setLayout(new FlowLayout());

        A = new JButton("A");
        add(A);
        B = new JButton("B");
        add(B);
        C = new JButton("C");
        add(C);
        D = new JButton("D");
        add(D);
        E = new JButton("E");
        add(E);
        F = new JButton("F");
        add(F);
        G = new JButton("G");
        add(G);
        H = new JButton("H");
        add(H);
        I = new JButton("I");
        add(I);
        J = new JButton("J");
        add(J);
        K = new JButton("K");
        add(K);
        L = new JButton("L");
        add(L);
        M = new JButton("M");
        add(M);
        N = new JButton("N");
        add(N);
        O = new JButton("O");
        add(O);
        P = new JButton("P");
        add(P);
        Q = new JButton("Q");
        add(Q);
        R = new JButton("R");
        add(R);
        S = new JButton("S");
        add(S);
        T = new JButton("T");
        add(T);
        U = new JButton("U");
        add(U);
        V = new JButton("V");
        add(V);
        W = new JButton("W");
        add(W);
        X = new JButton("X");
        add(X);
        Y = new JButton("Y");
        add(Y);
        Z = new JButton("Z");
        add(Z);

        HandlerClass handler = new HandlerClass();
        A.addActionListener(handler);
        B.addActionListener(handler);
        C.addActionListener(handler);
        D.addActionListener(handler);
        E.addActionListener(handler);
        F.addActionListener(handler);
        G.addActionListener(handler);
        H.addActionListener(handler);
        I.addActionListener(handler);
        J.addActionListener(handler);
        K.addActionListener(handler);
        L.addActionListener(handler);
        M.addActionListener(handler);
        N.addActionListener(handler);
        O.addActionListener(handler);
        P.addActionListener(handler);
        Q.addActionListener(handler);
        R.addActionListener(handler);
        S.addActionListener(handler);
        T.addActionListener(handler);
        U.addActionListener(handler);
        V.addActionListener(handler);
        W.addActionListener(handler);
        X.addActionListener(handler);
        Y.addActionListener(handler);
        Z.addActionListener(handler);
    }
      private class HandlerClass implements ActionListener{
  public void actionPerformed(ActionEvent event){

     Object button = event.getSource();

     if(button == A){
String text = "asaasas ";
  JTextArea textArea = new JTextArea(text);

  textArea.setColumns(30);
  textArea.setLineWrap( true );
  textArea.setWrapStyleWord( true );
  textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
  JOptionPane.showMessageDialog(
   null, textArea, "Appomattox Court House", JOptionPane.PLAIN_MESSAGE);

     }else if(button == B){
     String text = "Duriing the last days of the Civil War, Robert E. Lee had abandoned the Confederate capital of Richmond and city of Petersburg, hoping to escape with the remnants of his Army of Northern Virginia to meet up with additional Confederate forces in North Carolina and resume fighting. Union Forces cut him off and finally the Continental army had to surrender. The Appomattox Courthouse is the locaiton where General Robert E. Lee of the Confederate Army surrendered his approximately 28,000 troops to Ulysses S. Grant and the Union Army on April 9, 1865, ending the American Civil War. ";
  JTextArea textArea = new JTextArea(text);

  textArea.setColumns(30);
  textArea.setLineWrap( true );
  textArea.setWrapStyleWord( true );
  textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
  JOptionPane.showMessageDialog(
   null, textArea, "Appomattox Court House", JOptionPane.PLAIN_MESSAGE);
     } else if(button == C){

String text = "Duriing the last days of the Civil War, Robert E. Lee had abandoned the Confederate capital of Richmond and city of Petersburg, hoping to escape with the remnants of his Army of Northern Virginia to meet up with additional Confederate forces in North Carolina and resume fighting. Union Forces cut him off and finally the Continental army had to surrender. The Appomattox Courthouse is the locaiton where General Robert E. Lee of the Confederate Army surrendered his approximately 28,000 troops to Ulysses S. Grant and the Union Army on April 9, 1865, ending the American Civil War. ";
  JTextArea textArea = new JTextArea(text);

  textArea.setColumns(30);
  textArea.setLineWrap( true );
  textArea.setWrapStyleWord( true );
  textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
  JOptionPane.showMessageDialog(
   null, textArea, "Appomattox Court House", JOptionPane.PLAIN_MESSAGE);     
       }

      }
}
Community
  • 1
  • 1
user1911773
  • 51
  • 1
  • 1
  • 5
  • 2
    I am not seeing where you are putting BackgroundPanel on your GUI? And what is GUI? Is it a JFrame? – Vincent Ramdhanie Dec 19 '12 at 02:50
  • 1
    Try this link. It could help you sort your problem. [Link](http://stackoverflow.com/questions/1466240/how-to-set-an-image-as-a-background-for-frame-in-swing-gui-of-java) – Smit Dec 19 '12 at 02:57
  • Yes, GUI is a JFrame. I took some source code I found and copied it and some things so it fit my application. Where should I put BackgroundPanel? I'm really struggling. This is my first java program. I'm not sure how to use that code in the link and put it in my project. I tried changing the names of everything, but I still had a lot of errors. – user1911773 Dec 19 '12 at 03:39

1 Answers1

1

This...

public void paint(Graphics g)
{
    // Draws the img to the BackgroundPanel.
    g.drawImage(img, 0, 0, null);
}

Is never a good idea. You've failed to honor the paint chain. The paint chain is a complex set of methods that does a lot of important work.

A better idea would be to use paintComponent

protected void paintComponent(Graphics g)
{
    super.paintComponent(g);
    // Draws the img to the BackgroundPanel.
    g.drawImage(img, 0, 0, null);
}

Another issue you will have is that your not giving the component a chance to monitor the state of the image. Because you are using Toolkit.getDefaultToolkit().createImage("Background.jpg") it is possible method will use a background thread to the load the image. You need some way to tell the component that the image has completed loading and is ready for painting...

g.drawImage(img, 0, 0, this);

This will let the component monitor the state of the image and update itself as required.

Toolkit#createImage is probably not the best choice for loading images. The method will not throw an exception if it is not able to load the image.

Better to use ImageIO#read. This will not only throw an exception if the class is unable to load the image, it's guaranteed to return a fully qualified image (that is, it will block until the image is actually loaded).

You've not enlightened us to the location of Background.jpg. If the image is a embedded resource or not. If the image is just a file (within the execution context of the application), then you attempt to the load the file is fine, if it's a embedded resource (contained within the application Jar), then you need to use Class#getResource instead...

img = ImageIO.read(getClass().getResource("/Background.jpg"));

You've not specified a preferred size for the BackgroundPanel. Some layout managers will not be able to layout this container the way you expected it to be laid out.

public Dimension getPreferredSize() {
    return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(this), img.getHeight(this));
}

Also, as has already begin mentioned, don't forget to add the panel to your UI ;)

Updated with example

I also noticed that you seem to be mixing Swing and AWT components, this is never a good idea, and if you can avoid it, do so (Panel is a AWT/heavy weight component).

enter image description here

public class Apples {

    public static void main(String[] args) {
        new Apples();
    }

    public Apples() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new BackgroundPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class BackgroundPanel extends JPanel {

        Image img;

        public BackgroundPanel() {
            try {
                img = ImageIO.read(getClass().getResource("/Background.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Draws the img to the BackgroundPanel.
            if (img != null) {
                g.drawImage(img, 0, 0, null);
            }
        }

        public Dimension getPreferredSize() {
            return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(this), img.getHeight(this));
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Ok I updated the program with the code you gave me (also updated my first post so you can see it) , but I'm still getting a lot of errors. I definitely feel like I didn't put the new code you gave me in the right spot. I'm sorry. I should know this stuff, but I'm just trying to make this for my english project and I've never really done guis before (previous experience robot programming). How and where do I add the panel in my gui class? – user1911773 Dec 19 '12 at 04:17
  • Updated with working example – MadProgrammer Dec 19 '12 at 04:41
  • Thank you so much for writing that! I really appreciate it! I have a couple of problems when trying to post that code. I posted my GUI code above, but anyways when I put my cursor over a button, the background of the button fades out. You'll see what I mean when you try it out with my Gui Code. Also the program you posted must've screwed with the dimensions of the message box because now its stretched vertically and the exit on close no longer appears. Run the gui code along with the program you made and you'll see what I mean. – user1911773 Dec 19 '12 at 05:46
  • The frame is been stretched hortizontally, because that's it's preferred size (`JFrame#pack` packs the frame to the preferred size of it's content). Not sure what you mean by *"the background of the button fades out"* - That could be a look and feel issue. The main reason that the message dialog is might be stretching, is because I chose to override the `getPreferredSize` method and return the size of the background imaeg – MadProgrammer Dec 19 '12 at 06:58
  • Oh ok thanks.I'm not by my program right now, but would i solve this just by setting dimensions instead of using pack? Also when you tried the program (with gui), did your background image work? Mine didn't because I believe I have my path wrong. I'll tell you exactly what I did. I downloaded the image from Google and saved it in my desktop. I changed the name to Background. Shouldn't my file path be C:/Users/John/Desktop/Background.jpg ? When I tried just using /Background.jpg , it didn't work either – user1911773 Dec 19 '12 at 14:42
  • Or if it would be easier, the image could just be added below the buttons, it doesnt necessarily have to be a background. Actually it might be better if the image is added below the buttons – user1911773 Dec 19 '12 at 21:43
  • You're example code didn't have any background code within in it... – MadProgrammer Dec 19 '12 at 22:20
  • That is the gui class I posted. I put the code in the apples class. Is this wrong? – user1911773 Dec 19 '12 at 22:27
  • The problem is your asking me evaluate a problem for which you've not provided suitable code that represents the problem. The answer I posted works. As my answer stated, you've not specified where the image is located, if you're reading it off the file system or from an embedded resource – MadProgrammer Dec 19 '12 at 22:44
  • I'm sorry. I just updated the code. I'm not sure what an embedded resource is, but I can tell you that my file is from the file system on my computer – user1911773 Dec 19 '12 at 22:53
  • I fixed my problem. Thank you so much for your help! I really appreciate it. Hopefully when I'm better, I can pass on the favor! – user1911773 Dec 19 '12 at 23:35