Search code examples
javajwindow

How to display a jpeg on a JWindow in this code?


I'm trying to display the introduction window with the welcome image when my application starts. Everything loads just fine but the image does not display. When the application is loaded, this is what I see.

public class Window extends JWindow
{
  //java.net.URL imgIntro = getClass().getResource("/images/intro.jpg");
  ImageIcon imIntro = new ImageIcon("/images/intro.jpg");


  //java.net.URL imgRegles = getClass().getResource("/images/rules.jpg");
  ImageIcon imRules = new ImageIcon("/images/rules.jpg");

  static Thread t = new Thread();
  static int thread = 0;
  static JButton bouton;
  static int X;
  static int Y;



  public Window( int X, int Y, int type) {

    super();
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(X,Y);
    setLocation( (dim.width - X)/2 , (dim.height - Y)/2);
    setVisible(true);
    Container fen = getContentPane();

    if (type == 1 ) bouton = new JButton(imIntro);
    else            bouton = new JButton(imRules);
    bouton.setPreferredSize(new Dimension(X, Y) );
    fen.add( bouton);
    bouton.setVisible( true );

    show();

    if( type == 1 ) {
        try {
            Thread.sleep(1000);
            thread = 1;
        }
        catch( java.lang.InterruptedException ex ) {
            JOptionPane.showMessageDialog(null, "error");
            }
        dispose();

    }

    else {
        bouton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                     dispose();
                }
        });
    }

 }
}

Solution

  • The code was missing

    getClass().getResource
    

    Then

    ImageIcon imIntro = new ImageIcon(getClass().getResource("/images/Lintro.jpg"));
    

    Full Exemple Here