Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. Java
  4. Error show ImageIcon ???

Error show ImageIcon ???

Scheduled Pinned Locked Moved Java
helpjavaperformancequestionlounge
8 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    nghia09t3
    wrote on last edited by
    #1

    I want to show ImageIcon by adding to Label, but it has error, help me?

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.util.Scanner;
    class CatchTheRat extends JFrame
    {
    // The Rat
    JLabel lb;

    // Move it randomly!
    Random r;

    public CatchTheRat(int k)
    {

    // Set frame properties
    setTitle("Catch The Rat");
    setLayout(new FlowLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);

    // Set the background (just for a good look)
    setContentPane(new JLabel(new ImageIcon("background.jpg")));

    // Set layout to the content pane
    getContentPane().setLayout(new FlowLayout());

    // Create the rat
    lb=new JLabel(new ImageIcon("rat.jpg"));

    // Add the rat
    getContentPane().add(lb);

    // Create Random object
    r=new Random();

    // Create a timer and call it for every k seconds
    new Timer(k,new ActionListener(){

    public void actionPerformed(ActionEvent ae)
    {

    // Move the rat randomly, subtract 75, so that the rat should not meet the edges
    lb.setLocation(r.nextInt(getWidth()-75),r.nextInt(getHeight()-75));

    }

    }).start();

    // Add mouselistener, notify when user clicks it!
    lb.addMouseListener(new MouseAdapter(){

    public void mouseClicked(MouseEvent me)
    {
    // Create a beep sound when clicked to notify
    Toolkit.getDefaultToolkit().beep();

    // Also print it!
    System.out.println("Caught!");
    }

    });

    // Maximize the frame
    setExtendedState(MAXIMIZED_BOTH);

    }

    public static void main(String args[])
    {

    // Create Scanner object
    Scanner s=new Scanner(System.in);

    // Let the user enter his capability of catching the rat!
    System.out.println("Enter the speed");

    // Read the input
    int k=s.nextInt();

    // Create the frame and send the value of k
    new CatchTheRat(k);

    }
    }

    L T G 3 Replies Last reply
    0
    • N nghia09t3

      I want to show ImageIcon by adding to Label, but it has error, help me?

      import javax.swing.*;
      import java.awt.*;
      import java.awt.event.*;
      import java.util.Random;
      import java.util.Scanner;
      class CatchTheRat extends JFrame
      {
      // The Rat
      JLabel lb;

      // Move it randomly!
      Random r;

      public CatchTheRat(int k)
      {

      // Set frame properties
      setTitle("Catch The Rat");
      setLayout(new FlowLayout());
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);

      // Set the background (just for a good look)
      setContentPane(new JLabel(new ImageIcon("background.jpg")));

      // Set layout to the content pane
      getContentPane().setLayout(new FlowLayout());

      // Create the rat
      lb=new JLabel(new ImageIcon("rat.jpg"));

      // Add the rat
      getContentPane().add(lb);

      // Create Random object
      r=new Random();

      // Create a timer and call it for every k seconds
      new Timer(k,new ActionListener(){

      public void actionPerformed(ActionEvent ae)
      {

      // Move the rat randomly, subtract 75, so that the rat should not meet the edges
      lb.setLocation(r.nextInt(getWidth()-75),r.nextInt(getHeight()-75));

      }

      }).start();

      // Add mouselistener, notify when user clicks it!
      lb.addMouseListener(new MouseAdapter(){

      public void mouseClicked(MouseEvent me)
      {
      // Create a beep sound when clicked to notify
      Toolkit.getDefaultToolkit().beep();

      // Also print it!
      System.out.println("Caught!");
      }

      });

      // Maximize the frame
      setExtendedState(MAXIMIZED_BOTH);

      }

      public static void main(String args[])
      {

      // Create Scanner object
      Scanner s=new Scanner(System.in);

      // Let the user enter his capability of catching the rat!
      System.out.println("Enter the speed");

      // Read the input
      int k=s.nextInt();

      // Create the frame and send the value of k
      new CatchTheRat(k);

      }
      }

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2
      1. Please fix your formatting.
      2. Which line has the error?
      3. What error?

      Note, we cannot see your screen or guess what problems you are seeing.

      One of these days I'm going to think of a really clever signature.

      1 Reply Last reply
      0
      • N nghia09t3

        I want to show ImageIcon by adding to Label, but it has error, help me?

        import javax.swing.*;
        import java.awt.*;
        import java.awt.event.*;
        import java.util.Random;
        import java.util.Scanner;
        class CatchTheRat extends JFrame
        {
        // The Rat
        JLabel lb;

        // Move it randomly!
        Random r;

        public CatchTheRat(int k)
        {

        // Set frame properties
        setTitle("Catch The Rat");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        // Set the background (just for a good look)
        setContentPane(new JLabel(new ImageIcon("background.jpg")));

        // Set layout to the content pane
        getContentPane().setLayout(new FlowLayout());

        // Create the rat
        lb=new JLabel(new ImageIcon("rat.jpg"));

        // Add the rat
        getContentPane().add(lb);

        // Create Random object
        r=new Random();

        // Create a timer and call it for every k seconds
        new Timer(k,new ActionListener(){

        public void actionPerformed(ActionEvent ae)
        {

        // Move the rat randomly, subtract 75, so that the rat should not meet the edges
        lb.setLocation(r.nextInt(getWidth()-75),r.nextInt(getHeight()-75));

        }

        }).start();

        // Add mouselistener, notify when user clicks it!
        lb.addMouseListener(new MouseAdapter(){

        public void mouseClicked(MouseEvent me)
        {
        // Create a beep sound when clicked to notify
        Toolkit.getDefaultToolkit().beep();

        // Also print it!
        System.out.println("Caught!");
        }

        });

        // Maximize the frame
        setExtendedState(MAXIMIZED_BOTH);

        }

        public static void main(String args[])
        {

        // Create Scanner object
        Scanner s=new Scanner(System.in);

        // Let the user enter his capability of catching the rat!
        System.out.println("Enter the speed");

        // Read the input
        int k=s.nextInt();

        // Create the frame and send the value of k
        new CatchTheRat(k);

        }
        }

        T Offline
        T Offline
        TorstenH
        wrote on last edited by
        #3

        It's called OOP for a reason. Please, the constructor never executes code. Define some methods for that. You are adding the JLabel to the ContentPane - which you first set with a JLabel. Adding a JLabel to a JLabel does not work. Also please just refer to the JFrame by adding to "this". Suggestion: 1. OOP that. 2. Set up a JPanel, that forms the playground for the rat. You probably want a second Panel for the Game controls - which are now to be entered in the console before. 3. Use a null-Layout for the game-Panel. You want to move the rat by pixel / absolute position, not by relative position to some other control. FlowLayout is also default, does not need to be initalized.

        import javax.swing.*;
        class CatchTheRat extends JFrame {
        // The Rat
        JLabel lb;

        // Move it randomly!
        Random r;
        
        public CatchTheRat(int k) {
        	createGUI(k);
        }
        
        private void createGUI(int k) {
        
        	// Set frame properties
        	setTitle("Catch The Rat");
        	setLayout(new FlowLayout());
        	setDefaultCloseOperation(EXIT\_ON\_CLOSE);
        

        // setExtendedState(MAXIMIZED_BOTH);
        setSize(new Dimension(800,600));
        this.add(createContent(k));

        	// Maximize the frame
        	setVisible(true);
        }
        
        private JPanel createContent(int k) {
        	JPanel oPanel = new JPanel();
        	// Set the background (just for a good look)
        

        // setContentPane(new JLabel(new ImageIcon("background.jpg")));

        	// Set layout to the content pane
        

        // oPanel.setLayout(new FlowLayout());

        	// Create the rat
        	lb = new JLabel(new ImageIcon("rat.jpg"));
        
        	// Add the rat
        	oPanel.add(lb);
        
        	// Create Random object
        	r = new Random();
        

        // The random positions do not work, will "hide" the icon therefor

        // // Create a timer and call it for every k seconds
        // new Timer(k, new ActionListener() {
        //
        // public void actionPerformed(ActionEvent ae) {
        //
        // // Move the rat randomly, subtract 75, so that the rat should
        // // not meet the edges
        // lb.setLocation(r.nextInt(getWidth()), r.nextInt(getHeight()));
        //
        // }
        //
        // }).start();

        	// Add mouselistener, notify when user clicks it!
        	lb.addMouseListener(new MouseAdapter() {
        
        		public void mouseClicked(MouseEvent me) {
        			// Create a beep sound when clicked to notify
        			Toolkit.getDefaultToolkit().beep();
        
        			// Also print it!
        			System.out.println("Caught!");
        		}
        
        	});
        	
        	return oPanel;
        
        }
        
        public static void main(String args\[\]) {
        
        	// Create Scanner object
        

        // Scanner s = new Scanner(System.in);
        //
        // /

        G 1 Reply Last reply
        0
        • N nghia09t3

          I want to show ImageIcon by adding to Label, but it has error, help me?

          import javax.swing.*;
          import java.awt.*;
          import java.awt.event.*;
          import java.util.Random;
          import java.util.Scanner;
          class CatchTheRat extends JFrame
          {
          // The Rat
          JLabel lb;

          // Move it randomly!
          Random r;

          public CatchTheRat(int k)
          {

          // Set frame properties
          setTitle("Catch The Rat");
          setLayout(new FlowLayout());
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          setVisible(true);

          // Set the background (just for a good look)
          setContentPane(new JLabel(new ImageIcon("background.jpg")));

          // Set layout to the content pane
          getContentPane().setLayout(new FlowLayout());

          // Create the rat
          lb=new JLabel(new ImageIcon("rat.jpg"));

          // Add the rat
          getContentPane().add(lb);

          // Create Random object
          r=new Random();

          // Create a timer and call it for every k seconds
          new Timer(k,new ActionListener(){

          public void actionPerformed(ActionEvent ae)
          {

          // Move the rat randomly, subtract 75, so that the rat should not meet the edges
          lb.setLocation(r.nextInt(getWidth()-75),r.nextInt(getHeight()-75));

          }

          }).start();

          // Add mouselistener, notify when user clicks it!
          lb.addMouseListener(new MouseAdapter(){

          public void mouseClicked(MouseEvent me)
          {
          // Create a beep sound when clicked to notify
          Toolkit.getDefaultToolkit().beep();

          // Also print it!
          System.out.println("Caught!");
          }

          });

          // Maximize the frame
          setExtendedState(MAXIMIZED_BOTH);

          }

          public static void main(String args[])
          {

          // Create Scanner object
          Scanner s=new Scanner(System.in);

          // Let the user enter his capability of catching the rat!
          System.out.println("Enter the speed");

          // Read the input
          int k=s.nextInt();

          // Create the frame and send the value of k
          new CatchTheRat(k);

          }
          }

          G Offline
          G Offline
          Gowtham Gutha
          wrote on last edited by
          #4

          What really is the error in my program? I couldn't understand. You'll need to have those image files (the background and the rat) to see them. That may be the possible error because it has worked in my development environment.

          Gowtham Gutha (http://java-demos.blogspot.com)

          1 Reply Last reply
          0
          • T TorstenH

            It's called OOP for a reason. Please, the constructor never executes code. Define some methods for that. You are adding the JLabel to the ContentPane - which you first set with a JLabel. Adding a JLabel to a JLabel does not work. Also please just refer to the JFrame by adding to "this". Suggestion: 1. OOP that. 2. Set up a JPanel, that forms the playground for the rat. You probably want a second Panel for the Game controls - which are now to be entered in the console before. 3. Use a null-Layout for the game-Panel. You want to move the rat by pixel / absolute position, not by relative position to some other control. FlowLayout is also default, does not need to be initalized.

            import javax.swing.*;
            class CatchTheRat extends JFrame {
            // The Rat
            JLabel lb;

            // Move it randomly!
            Random r;
            
            public CatchTheRat(int k) {
            	createGUI(k);
            }
            
            private void createGUI(int k) {
            
            	// Set frame properties
            	setTitle("Catch The Rat");
            	setLayout(new FlowLayout());
            	setDefaultCloseOperation(EXIT\_ON\_CLOSE);
            

            // setExtendedState(MAXIMIZED_BOTH);
            setSize(new Dimension(800,600));
            this.add(createContent(k));

            	// Maximize the frame
            	setVisible(true);
            }
            
            private JPanel createContent(int k) {
            	JPanel oPanel = new JPanel();
            	// Set the background (just for a good look)
            

            // setContentPane(new JLabel(new ImageIcon("background.jpg")));

            	// Set layout to the content pane
            

            // oPanel.setLayout(new FlowLayout());

            	// Create the rat
            	lb = new JLabel(new ImageIcon("rat.jpg"));
            
            	// Add the rat
            	oPanel.add(lb);
            
            	// Create Random object
            	r = new Random();
            

            // The random positions do not work, will "hide" the icon therefor

            // // Create a timer and call it for every k seconds
            // new Timer(k, new ActionListener() {
            //
            // public void actionPerformed(ActionEvent ae) {
            //
            // // Move the rat randomly, subtract 75, so that the rat should
            // // not meet the edges
            // lb.setLocation(r.nextInt(getWidth()), r.nextInt(getHeight()));
            //
            // }
            //
            // }).start();

            	// Add mouselistener, notify when user clicks it!
            	lb.addMouseListener(new MouseAdapter() {
            
            		public void mouseClicked(MouseEvent me) {
            			// Create a beep sound when clicked to notify
            			Toolkit.getDefaultToolkit().beep();
            
            			// Also print it!
            			System.out.println("Caught!");
            		}
            
            	});
            	
            	return oPanel;
            
            }
            
            public static void main(String args\[\]) {
            
            	// Create Scanner object
            

            // Scanner s = new Scanner(System.in);
            //
            // /

            G Offline
            G Offline
            Gowtham Gutha
            wrote on last edited by
            #5

            Thanks for the suggestion. But that worked in my system. We can add JLabel to another JLabel because JComponent itself is a container and we can add any component to any component. There is no limitation. The add method does it.

            Gowtham Gutha (http://java-demos.blogspot.com)

            T 1 Reply Last reply
            0
            • G Gowtham Gutha

              Thanks for the suggestion. But that worked in my system. We can add JLabel to another JLabel because JComponent itself is a container and we can add any component to any component. There is no limitation. The add method does it.

              Gowtham Gutha (http://java-demos.blogspot.com)

              T Offline
              T Offline
              TorstenH
              wrote on last edited by
              #6

              Technically - yes. Until someone wants to place place a text in the JLabel or plays around. So it's pretty much safer to use a JPanel, that is known as a container.

              regards Torsten When I'm not working

              G 1 Reply Last reply
              0
              • T TorstenH

                Technically - yes. Until someone wants to place place a text in the JLabel or plays around. So it's pretty much safer to use a JPanel, that is known as a container.

                regards Torsten When I'm not working

                G Offline
                G Offline
                Gowtham Gutha
                wrote on last edited by
                #7

                Ok. By the way, could i also know why it is not recommended to write code in the constructor and only in a separate method and then call that method?

                Gowtham Gutha (http://java-demos.blogspot.com)

                T 1 Reply Last reply
                0
                • G Gowtham Gutha

                  Ok. By the way, could i also know why it is not recommended to write code in the constructor and only in a separate method and then call that method?

                  Gowtham Gutha (http://java-demos.blogspot.com)

                  T Offline
                  T Offline
                  TorstenH
                  wrote on last edited by
                  #8

                  That's basic design: A constructor is there for initalizing the object. JavaWorld - Article on Constructors[^]

                  regards Torsten When I'm not working

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups