0

Basically I've created two classes; Main and JFrameOptions. However, it seems that I cannot draw a background whether I use JLabels, setContentPane or setBackground all of them doesn't work. What am I doing wrong?

Main:

package game;

public class Main{

public static void main(String[] args) {
JFrameOptions.Options();
TSDTDir.Directory();
}
}

JFrameOptions:

package game;

import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JFrame;


public class JFrameOptions{

 static String setTitle = ("Game");;

 public static int width = 920;
 public static int height = 517;

public static void Options() {
    JFrame window = new JFrame(setTitle);
    window.setSize(width, height);
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setResizable(false);
    window.setLocationRelativeTo(null);
    window.toFront();
    window.setBackground(Color.black);
}
}

Edit:

I got the fundamental thing to work through your answers: window.getContentPane().setBackground( Color.PINK );

But how can I load an image that has to function to have a login field for example?

Edit 2: It is not working. The background doesn't draw.

public static void Options() {

        //Displays the title 
        JFrame window = new JFrame(setTitle);
        window.setSize(width, (int) height);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setIconImage(favIcon);
        window.setResizable(false);
        window.setLocationRelativeTo(null);
        window.toFront();

        //window.getContentPane().setBackground(Color.black);


        BufferedImage img = null;
    try {
        img = ImageIO.read(new File("Background.png"));
        window.setContentPane(new JLabel(new ImageIcon(img)));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

And of course the Background.png file is in the directory of the game folder: http://prntscr.com/9kxc4i

Image of image file location:
enter image description here

Console image:
enter image description here

Running GUI image:
enter image description here

Rakozay
  • 169
  • 2
  • 14
  • In the future, please search on your problem before posting because 9 times out of 10, it's been asked and answered before. – Hovercraft Full Of Eels Jan 01 '16 at 15:11
  • Links: [JFrame set background color not working](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=jframe+set+background+color+not+working+site:http:%2F%2Fstackoverflow.com%2F), and [JFrame set background image](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=jframe+set+background+image+site:http:%2F%2Fstackoverflow.com%2F). – Hovercraft Full Of Eels Jan 01 '16 at 15:22
  • `"But how can I load an image that has to function to have a login field for example?"` -- again look it up -- see links above. As for "login field" you'll have to describe what you mean as that doesn't make sense, but perhaps you mean to show a modal JDialog as a login window, and if so, look that up. There is nothing new under the sun. – Hovercraft Full Of Eels Jan 01 '16 at 15:23
  • Alright let me explain more in depth: I want to draw an image: http://i.imgur.com/Nr9PVYl.png - Which in the bottom of course loads the content.. after that I want to have another image: http://i.imgur.com/93A8N98.png - Which has to be drawn and have these login input fields to function ( I know there is something about positioning etc.) Also I have looked on every single article and seems to I cannot figure it out as it didn't draw the image.. - I am new into Java btw.. – Rakozay Jan 01 '16 at 15:30
  • Again, the links will explain how to draw images. You will want to check them and try. If still stuck, then come back **with your new attempt** code. Else we're being forced to give the same answers that have already been given before. – Hovercraft Full Of Eels Jan 01 '16 at 15:32
  • Fully understandable I will try again and come back if it isn't working! – Rakozay Jan 01 '16 at 15:32
  • Updated the above post – Rakozay Jan 01 '16 at 16:43
  • Your new problem is likely due to another common problem -- not being able to read in an image file, which is usually due to looking in the wrong place. Have you checked the path to the user's working directory? This can be obtained by printing `System.out.println(System.getProperty("user.dir"));`. Then check to see where your image path is in relation to this path, and then correct your path. Also when debugging, try to avoid having such long compressed lines of code. Read the image on one line, create the Icon on another, check for nulls. – Hovercraft Full Of Eels Jan 01 '16 at 16:51
  • Just outprinted the code you gave me and it is the correct path; "C:\Users\hp1\Desktop\Game" and the background's path is located at : "C:\Users\hp1\Desktop\Game\Background.png" That's why I do not get why it is not displayed. Also I do not quite get the last part with the "debugging" though I think I know what you mean with the long compressed lines of code. – Rakozay Jan 01 '16 at 17:00
  • I'll re-open your question given the efforts you're putting in, but your problem now vexes me. Are you getting an IIOException with this attempt? Show all exceptions, show by image (post a link to an image) the location of your image relative to your code please. – Hovercraft Full Of Eels Jan 01 '16 at 17:20
  • I really do understand it vexes me as well but I have learned that patience is key and I really appreciate that you are helping! Alright the fact is with this problem is that it recognizes the file however doesn't draw it. No exceptions occurs at the console. Location of image: http://prntscr.com/9kxc4i - Console output: http://prntscr.com/9kxsag - Screen of the frame: http://prntscr.com/9kxsgs - JFrameOptions class: http://pastebin.com/eBmYJTwU - Main class: http://pastebin.com/NKWCMy2D – Rakozay Jan 01 '16 at 17:27
  • I tested it if I remove the file at the location a IIOException will occur: http://prntscr.com/9kxtl8 – Rakozay Jan 01 '16 at 17:29
  • Images uploaded. In the future, please post links to the images, not to the web pages that hold the images. – Hovercraft Full Of Eels Jan 01 '16 at 17:31
  • Hovercraft or anyone else is the way I am calling a method on OK? Like the main args calls the options method from another class? Also do i've to do that every single time i want something to be runned? – Rakozay Jan 01 '16 at 19:23
  • Start by using `ImageIO.read` to load the image instead of `ImageIcon`, it will through an error if the image can't be loaded for some reason – MadProgrammer Jan 01 '16 at 21:18
  • I think the case is that it is not being drawn into the frame. No exception occur as said earlier. Also I do use ImageIO.read? – Rakozay Jan 01 '16 at 21:28
  • Sorry, reading on the phone, move `window.setVisible(true);` so it is the last call – MadProgrammer Jan 01 '16 at 23:04

1 Answers1

1

This is a common problem, you are calling setVisible before the UI is established. Swing is lazy when it comes to laying out changes to the UI, requiring you to decide when the UI should be updated, this is deliberate and done in order to maintain efficiency (imagine adding a dozen new components to the UI, you wouldn't want the UI to be revalidated and updated until you're done, otherwise you'd be wasting a lot of time)

The simple solution is, call setVisible last...

public static void Options() {

    //Displays the title 
    JFrame window = new JFrame(setTitle);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setIconImage(favIcon);

    //window.getContentPane().setBackground(Color.black);
    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("Background.png"));
        window.setContentPane(new JLabel(new ImageIcon(img)));
    } catch (IOException e) {
        e.printStackTrace();
    }
    window.setResizable(false);
    window.pack();
    window.setLocationRelativeTo(null);
    window.setVisible(true);
    window.toFront();
}

Remember though, a JLabel has no layout manager by default and even when you apply one, it won't use it to calculate its preferredSize, relying only on the icon and text properties.

Have a look at this discussion for more details and alternatives

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Dang, that is a nice explanation. Though I came up with another solution which I actually do not get why it works? I simply added after e.printStackTrace(); } Graphics g = window.getGraphics(); g.drawImage(img, 0, 0, null); And it draw the image to the frame? – Rakozay Jan 01 '16 at 23:20
  • Don't (ever) use `getGraphics`, it's simply a snapshot of what was last painted to the component and will be overriden the next time the component is repainted – MadProgrammer Jan 01 '16 at 23:29
  • Oh I see, so basically that means if I drag the frame to right then the dragged area would become white as it gets overriden? – Rakozay Jan 01 '16 at 23:32
  • Assuming you didn't also add the label, yes (resizing the frame with the label would invalidate the container, causing it to be re-laid out and repainted) – MadProgrammer Jan 01 '16 at 23:34
  • I understand now, though it is working properly now with your code. It happended before with the getGraphics. Definitely this has being a lot useful. – Rakozay Jan 01 '16 at 23:38