1

It's my first post here and my English isn't pretty well so i hope you guy's understand what problem i have and also i hope i do nothing wrong here.

My Problem:

I'm learning atm Swing and how it works, but i have always some problems with picture which doesnt show up. Maybe i dont understand some part of Swing so i hope you can explain me why the picture doesnt loading so i can learn it and do a better work : )

i tried much variatons but i really only failed and i dont know why. i tried it also with graphics.

My Program:

JFrame -> JPanel -> JLabel (which have the picture and should put it on JPanel or maybe there is a direct way on JPanel)

test2.jpg is in my package folder and eclipse dont shout an error.

also i would JPanel in an separate class like it is and dont would extend JFrame to Gui class.

Here are my 3 classes:

Start:

package verwaltungssoftware;

public class Start

{

    //Start der Applikation

    public static void main(String[] args)

    {
        System.out.println("Willkommen bei der Verwaltungssoftware fuer die Jobsuche");
        new Gui();
    }

}

Gui:

package verwaltungssoftware;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;


public class Gui
{
    //Importiert Auflösung des Bildschirms
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();

    //Setzt Variablen für die Auflösung
    public int aufloesungBreite = screenSize.width;
    public int aufloesungHoehe = screenSize.height;

    //Setzt die Berechnung des JFrame hauptfenster Location
    private int breite = aufloesungBreite/2 - 640;
    private int hoehe = aufloesungHoehe/2 - 400;


    public Gui()

    {
        JFrame hauptfenster = new JFrame("Verwaltungssoftware fuer die Jobsuche");
        hauptfenster.setDefaultCloseOperation(hauptfenster.EXIT_ON_CLOSE);
        hauptfenster.setResizable(false);
        hauptfenster.setLocation(breite, hoehe);
        hauptfenster.setSize(1280,800);
        hauptfenster.setLayout(new BorderLayout(5,5));

        //Addet hauptpanel zum JFrame
        Panel hauptpanel = new Panel();
        hauptfenster.add(hauptpanel);   
        hauptpanel.setVisible(true);
        hauptfenster.setVisible(true);
    }


}

and Panel:

package verwaltungssoftware;
import java.awt.BorderLayout;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Panel extends JPanel
{
    private static final long serialVersionUID = 6769810448979262470L;

    //Variablen

    Image icon1;


    //Konstruktor
    public Panel()

    {
        try 
        {
            icon1  = ImageIO.read(getClass().getResource("test2.jpg"));
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

        JPanel panelhauptfenster = new JPanel();
        panelhauptfenster.setLayout(new BorderLayout (5,5));
        panelhauptfenster.setSize(1280,800);
        panelhauptfenster.setLocation(0,0);
        panelhauptfenster.setVisible(true);

        JLabel myLabel=new JLabel();
        myLabel.setLocation(0,0);
        myLabel.setSize(panelhauptfenster.getWidth(),panelhauptfenster.getHeight());
        myLabel.setIcon(new ImageIcon(icon1));
        myLabel.setVisible(true);

        panelhauptfenster.add(myLabel);
    }
}

Thank you very much in advance for your help.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Cronical
  • 34
  • 8
  • `getClass().getResource("test2.jpg")` ..is the image located in the `verwaltungssoftware` directory/path where `getResource` would be expecting to find it? – Andrew Thompson Nov 04 '14 at 05:33
  • the path i correct when i change it it gives me an error: Exception in thread "main" java.lang.IllegalArgumentException: input == null! at javax.imageio.ImageIO.read(ImageIO.java:1388) at verwaltungssoftware.Panel.(Panel.java:25) at verwaltungssoftware.Gui.(Gui.java:34) at verwaltungssoftware.Start.main(Start.java:13) picture is in package verwaltungssoftware – Cronical Nov 04 '14 at 05:37
  • Good-oh. Factor `getClass().getResource("test2.jpg")` into the source I put in an answer and try it. The approach in the code above had a number of flaws I corrected. – Andrew Thompson Nov 04 '14 at 05:56

2 Answers2

1

The source below works. Changes include:

  • Returning a sensible preferred size. Removing all calls to setSize(..).
  • Factoring out the panel to which the image was added, and instead adding it directly to the Panel instance.
  • But Panel was renamed ImagePanel so that is not the same name as an existing AWT class!
  • Removing the calls to setVisible(..). The only thing that applies to is top level containers like JFrame or JDialog. For the rest, add them to a container that is itself made visible.

import java.awt.*;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;

class Gui {
    //Importiert Auflösung des Bildschirms
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();

    //Setzt Variablen für die Auflösung
    public int aufloesungBreite = screenSize.width;
    public int aufloesungHoehe = screenSize.height;

    //Setzt die Berechnung des JFrame hauptfenster Location
    private int breite = aufloesungBreite/2 - 640;
    private int hoehe = aufloesungHoehe/2 - 400;


    public Gui() {
        JFrame hauptfenster = new JFrame("Verwaltungssoftware fuer die Jobsuche");
        hauptfenster.setDefaultCloseOperation(hauptfenster.EXIT_ON_CLOSE);
        hauptfenster.setResizable(false);
        hauptfenster.setLocation(breite, hoehe);
        hauptfenster.setSize(1280,800);
        hauptfenster.setLayout(new BorderLayout(5,5));

        //Addet hauptpanel zum JFrame
        ImagePanel hauptpanel = new ImagePanel();
        hauptfenster.add(hauptpanel);   
        hauptpanel.setVisible(true);
        hauptfenster.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new Gui();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

class ImagePanel extends JPanel {
    //Variablen
    Image icon1;

    //Konstruktor
    public ImagePanel() {
        try  {
            URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
            icon1  = ImageIO.read(url);
        } catch (Exception e)  {
            e.printStackTrace();
        }

        setLayout(new BorderLayout (5,5));
        JLabel myLabel=new JLabel(new ImageIcon(icon1));
        add(myLabel);
    }

    // very important!
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(icon1.getWidth(this), icon1.getHeight(this));
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • good job picture is loading but i dont know how i get the panel to the frame. when preferedsize take width and length from this i must set somewhere the size of the panel because i add it to the gui JFrame. when i understand that correctly icon has the size of the panel after getpreferedsize – Cronical Nov 04 '14 at 06:03
  • If you would like further help, prepare an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) like I posted. Notably it needs to be one source file (with perhaps more than one class, though only one **`public`** class) and should hot-link to the image. – Andrew Thompson Nov 04 '14 at 06:06
  • I did a mistake, it works but i cant do it with an URL like you in the example because i have a PATH. I think i need to do it like Kandy written down below. But there is the problem that java cannot convert from Imageicon to image. – Cronical Nov 04 '14 at 06:20
  • *"i cant do it with an URL like you in the example because i have a PATH"* You do realize that `getResource(..)` returns an URL, right? Don't think about how your app. is going to look eventually or what image it will use. I am suggesting to hot-link to an image simply so that (when you run the code) you can see it, we can see it, and anybody in the future can see it. The image I linked to is mentioned in [Example images for code and mark-up Q&As](http://stackoverflow.com/q/19209650/418556). I asked it specifically to ***have*** example images we might hot-link to. And don't bother .. – Andrew Thompson Nov 04 '14 at 06:29
  • .. with the advice of Kandy. I read the answer, and they are on the wrong track (gave advice that would not work). – Andrew Thompson Nov 04 '14 at 06:30
  • 1
    Ok its working now i was really stupid when i look at the code now :) Thank you really much Thompson. Sorry i didnt understand first what you was meaning by hot linked. – Cronical Nov 04 '14 at 06:37
  • Glad you got it sorted. :) – Andrew Thompson Nov 04 '14 at 06:40
0

try like this. icon1= new ImageIcon(getClass().getResource("/test2.jpg"))

Kandy
  • 673
  • 9
  • 21