5

I had a friend make a background for the program I made so that it wouldn't look so plain, and I thought the best way to place the images would be to make a JLabel, fill it with an image, and set it to the size of the screen. This worked fine, except there is a small border around the JFrame and I can't get the JLabel to touch the edges of the frame. Thoughts? I have attached a picture.

Border Problem

public class ProgramDriver extends JFrame {

private JPanel contentPane;
private static CardLayout cardLayout;
private JTextField addGradeN;
private JTextField addGradeD;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ProgramDriver frame = new ProgramDriver();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

//Global Variables 
...
    manager = new StateManager(gb);

    //JFrame Settings
    setTitle("Grade Book");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 656, 530);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    cardLayout = new CardLayout(0,0);
    contentPane.setLayout(cardLayout);
    setResizable(false);

    //Home Panel 
    final JPanel Home = new JPanel();
    contentPane.add(Home, "Home");
    Home.setLayout(null);

    JButton btnSeeGrades = new JButton("See Grades");
    ...

    //Grades Panel
    JPanel Grades = new JPanel();
    contentPane.add(Grades, "Grades");
    Grades.setLayout(null);'
kleopatra
  • 51,061
  • 28
  • 99
  • 211
flyinghigh
  • 235
  • 3
  • 11
  • Are you sure that the size of the image matches that of the screen? Are you allowing the image to expand or contract if not? Consider creating and posting an [sscce](http://sscce.org) demonstrating your problem for us. – Hovercraft Full Of Eels Oct 06 '12 at 19:12
  • `JLabel background = new JLabel("New label"); background.setIcon(new ImageIcon(ProgramDriver.class.getResource("/Pictures/GB_Blue.jpg"))); background.setBounds(0, 0, 652, 496); Preferences.add(background);` – flyinghigh Oct 06 '12 at 19:26
  • Please don't post code in comments as they're nigh near unreadable. Post it as an edit to your question. But it seems that the code you've posted you don't seem to be expanding the *image*, so it is no surprise to me that you have a border. Eng's answer will probably work best, 1+ to him. – Hovercraft Full Of Eels Oct 06 '12 at 19:28
  • By expanding, I assume you mean this is a limitation of the JLabel and I must use drawImage, as "expanding" is not just a simple modification to the label. As for the code, you're absolutely right. I can't read it at all. Sorry, didn't realize it would come out like that. Noted for the future. ;) – flyinghigh Oct 06 '12 at 21:31
  • possible duplicate of [Java White Edge (Buffer) in Mac JFrame](http://stackoverflow.com/questions/12591892/java-white-edge-buffer-in-mac-jframe) – trashgod Oct 06 '12 at 22:07

5 Answers5

4

The problem isn't with the JFrame, the problem is with your code. We can spend the rest of our natural life at guessing what's wrong or you can post some example code.

Now it's up to you, we can keep trying to throw wrong guess after wrong guess at you, frustrating us all, or you can help us help you...

Here are two examples I did. The first uses a JLabel as the primary content for a JPanel, where the child components are placed on it. Nice and simple.

The second uses a custom JPanel which paints the image onto the background of the component. I then use this to replace the frames content pane. This is a little more involved, but it has the added benefit of been easily updated (replacing the content pane won't effect the rest of the program)

Example 1: JLabel used as background

JLabel as background

public class TestBackground {

    public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";

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

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

                JFrame frame = new JFrame("Testing");
                frame.setLayout(new BorderLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new LabelPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

            }
        });

    }

    protected class LabelPane extends JPanel {

        public LabelPane() {

            BufferedImage bg = null;
            try {
                bg = ImageIO.read(new File(BACKGROUND_PATH));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            JLabel label = new JLabel(new ImageIcon(bg));
            setLayout(new BorderLayout());

            add(label);

            label.setLayout(new GridBagLayout());

            JLabel lblMessage = new JLabel("Look at me!");
            lblMessage.setForeground(Color.WHITE);
            lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));

            label.add(lblMessage);

        }
    }
}

Example 2: Image used as background, replacing content pane...

Background Content Pane

public class TestBackground {
    public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";

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

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

                JFrame frame = new JFrame("Testing");
                frame.setLayout(new BorderLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new BackgroundPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected class BackgroundPane extends JPanel {

        private BufferedImage bg = null;

        public BackgroundPane() {
            try {
                bg = ImageIO.read(new File(BACKGROUND_PATH));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            setLayout(new GridBagLayout());

            JLabel lblMessage = new JLabel("Look at me!");
            lblMessage.setForeground(Color.WHITE);
            lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));

            add(lblMessage);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1153, 823);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (bg != null) {
                g.drawImage(bg, 0, 0, this);
            }
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
3

To expand on Eng.Fouad's answer, you'll want to use the drawImage(...) method that takes 6 parameters, image, x and y location, image width and height, and image observer, and draw it like so from within a JPanel:

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

For example, my sscce:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class ExpandingImage extends JPanel {
   public static final String GUITAR = "http://duke.kenai.com/Oracle/OracleStrat.png";
   BufferedImage img;

   public ExpandingImage(String imgUrlPath) throws IOException {
      URL imgUrl = new URL(imgUrlPath);
      img = ImageIO.read(imgUrl);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (img != null) {
         g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
      }
   }


   private static void createAndShowGui() {
      ExpandingImage mainPanel;
      try {
         mainPanel = new ExpandingImage(GUITAR);
         JFrame frame = new JFrame("ExpandingImage");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add(mainPanel);
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
         frame.setVisible(true);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Edit
I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks, going to try this. How do I get a BufferedImage form the file. I have one in the package. – flyinghigh Oct 06 '12 at 20:49
  • @user1419623: You can use ImageIO.read which can take an InputStream, and you can get the File as an InputStream by calling `getClass().getResourceAsStream(pathToImage)`. Note that pathToImage will be relative to the class files. This is *very* important. – Hovercraft Full Of Eels Oct 06 '12 at 20:53
  • I'm a little confused as how your example format fits with my format. I've posted my code above with only the necessary lines (obviously), as as you can see I'm basically creating panels and panels and panels... – flyinghigh Oct 06 '12 at 21:50
  • @user1419623: I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present? – Hovercraft Full Of Eels Oct 06 '12 at 22:04
  • Oh my goodness. That would fix the problem with the JLabel. I had that there from reading a tutorial on the internet, since I'm in data structures this year I haven't had any formal training in graphics. But as you pointed out, the devil is in the details. However, I have opted for your painting method which works great now. I figured out the implementation. Thanks for all of your help and Eng's. – flyinghigh Oct 06 '12 at 22:17
  • 1
    @user1419623 I told you there was some kind of border the last time you posted this question! – MadProgrammer Oct 06 '12 at 22:28
2

As an alternative, you can override the method paintComponent(Graphics g) of JPanel (the contentPane) and use drawImage() on the Graphics object g as in this example.

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

have you tried JFrame function setUndecorated() ?

Matias Morant
  • 513
  • 2
  • 5
  • 12
0

Make the frame undecorated. frame.setUndecorated(true)

If you want to make it move, you can use the ComponentMover of the Java2S.

Make sure that it is undecorated before it is visible.

Next, use setContentPane(new JLabel(new ImageIcon("myimage.jpg")));

After, that you can add contents as usual.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Asker
  • 11
  • 2
  • The link to your blog is not on the precise topic of the question, and you have failed to indicate it is your own blog to which you have linked. I am removing the link, as it does not seem relevant to understanding your answer. If you add it back in, you must disclose that it is your website, and include a description of why it is *directly* related to the topic of the question. – Andrew Barber Oct 31 '12 at 19:59