Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 29

Thread: How to change image when a key is pressed?

  1. #1
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default How to change image when a key is pressed?

    I am very much new to Java. I have just started learning event handling. Currently I am learning about Key Events. And am learning by doing. Well that is how one could learn anything in fact. I want to write a program in which the currently loaded image in the panel of a frame changes upon a key press say "Enter" or any other key. Please help me with the program.


  2. #2
    Member Ada Lovelace's Avatar
    Join Date
    May 2014
    Location
    South England UK
    Posts
    411
    My Mood
    Angelic
    Thanks
    27
    Thanked 61 Times in 55 Posts

    Default Re: How to change image when a key is pressed?

    What have you tried so far? Post any code you are having problems with.

    Wishes Ada xx
    If to Err is human - then programmers are most human of us all.
    "The Analytical Engine offers a new, a vast, and a powerful language . . .
    for the purposes of mankind
    ."
    Augusta Ada Byron, Lady Lovelace (1851)

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,051
    My Mood
    Mellow
    Thanks
    184
    Thanked 650 Times in 637 Posts

    Default Re: How to change image when a key is pressed?

    Since I missed your palindrome topic from a few weeks ago while I was on vacation, welcome to the Forum! Please read this topic to learn how to post code correctly and other useful tips for newcomers.

    Which layout manager are you using? How did you get from your palindrome program of a few weeks ago to GUI programming? The Oracle Tutorials are a great place to start.

  4. #4
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    //The panel class
    package learnGUI.rev;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
     
    import javax.imageio.*;
    import javax.swing.*;
     
    import java.util.*;
    public class ImagePanel extends JPanel
    {
    	public ImagePanel()
    	{
    	KeyHandler listener = new KeyHandler();
    	addKeyListener(listener);
    	setFocusable(true);
    	}
        public void paintComponent(Graphics g)
        {
        	super.paintComponent(g);
        	ImageIcon i = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\2.png");
        	i.paintIcon(this,g,500,70);
        } 
    }
     
     
    // KeyHandler Class
     
    public class KeyHandler implements KeyListener {
     
    	public void keyPressed(KeyEvent e)
    	{
    		int code = e.getKeyCode();
    		if(code == KeyEvent.VK_ENTER)
    		{
    			// Dont Know What to do.
    		}
    	}
    	public void keyReleased(KeyEvent e){}
    	public void keyTyped(KeyEvent e){}
    }


    --- Update ---

    Is this how I should even do this?? I know how to load an Image onto a panel and also to write a basic Key Listening program. When I write a System.out.println() statement inside if(code == KeyEvent.VK_ENTER) I am able to print statements like "Hello World" and all when i press the ENTER key. But i dont know to do something on a panel when I press a key.

    --- Update ---

    All I know right now is how to load an image and basic key listener program. Is this much knowledge enough to do this program? I tried linking the panel class and the KeyHandler class using objects but failed in that also. Please advice me on this topic.
    Last edited by jerinjose61; August 21st, 2014 at 08:44 AM.

  5. #5
    Member
    Join Date
    Apr 2014
    Posts
    152
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    Can you please use code tags when posting code like

    //The panel class
    package learnGUI.rev;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
     
    import javax.imageio.*;
    import javax.swing.*;
     
    import java.util.*;
    public class ImagePanel extends JPanel
    {
    public ImagePanel()
    {
    KeyHandler listener = new KeyHandler();
    addKeyListener(listener);
    setFocusable(true);
    }
    public void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    ImageIcon i = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Deskto p\\KidX\\Number Images\\2.png");
    i.paintIcon(this,g,500,70);
    } 
    }
     
     
    // KeyHandler Class
     
    public class KeyHandler implements KeyListener {
     
    public void keyPressed(KeyEvent e)
    {
    int code = e.getKeyCode();
    if(code == KeyEvent.VK_ENTER)
    {
    // Dont Know What to do.
    }
    }
    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    @jocdrew21 Please edit the code in your post and give it proper formatting. Nested statements should be indented.

    @jerinjose61 Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE GOES HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    jerinjose61 (August 21st, 2014)

  8. #7
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    ThankYou!! I have edited my post.
    So any advice on how to do the program?

    --- Update ---

    Okay! I tried doing the program using the following code. But there are errors. My idea is when I press the key "1" I load one image and when I press "2" I load another image. I tried doing this the following way but failed. Somebody please advise me on this. I am stuck here.

    --- Update ---

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ImageTest {
    	public static void main(String[] args) {
    		ImageFrame frame = new ImageFrame();
    		frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
    		frame.setVisible(true);
    	}
    }
    class ImageFrame extends JFrame
    {
    	public ImageFrame()
    	{
    		setTitle("KidX");
    		setSize(500,500);
     
    		ImagePanel panel = new ImagePanel();
    		add(panel);
    	}
    }
    class ImagePanel extends JPanel
    {
    	public ImagePanel()
    	{
    		KeyHandler listener = new KeyHandler(); 
    		addKeyListener(listener);
    		setFocusable(true);
    	}
    	public void img(int imgno)
    	{
    		ImageIcon a;		
    		if (imgno == 1)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\1.png ");
    		}
    		else if (imgno == 2)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\2.png ");
    		}
    	}
    	public void paintComponent(Graphics g)
    	{
    		super.paintComponent(g);
    		a,paintIcon(this,g,200,200); // Error Here: a cannot be resolved
    	}
    }
    class KeyHandler implements KeyListener
    {
    	public void keyPressed(KeyEvent event)
    	{
    		int KeyCode = event.getKeyCode();
    		if(KeyCode == KeyEvent.VK_1) 
    		{
    			img(1); // Error Here: Method img(int) not defined.
    		}
    		if(KeyCode == KeyEvent.VK_2)
    		{
    			img(2); //Error Here: Method img(int) not defined.
    		}
    	}
    	public void keyReleased(KeyEvent event){}
    	public void keyTyped(KeyEvent event){}
    }

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    But there are errors.
    When you have errors, you should copy the full text of the message and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    I refined my code and eclipse now shows no errors. But the image is not loading. And there are run time errors. The code and errors are given below.

    --- Update ---

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ImageTest 
    {
    	public static void main(String[] args) 
    	{
    		ImageFrame frame = new ImageFrame();
    		frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
    		frame.setVisible(true);
    	}
    }
    class ImageFrame extends JFrame
    {
    	public ImageFrame()
    	{
    		setTitle("KidX");
    		setSize(500,500);
    		ImagePanel panel = new ImagePanel();
    		add(panel);
    	}
    }
    class ImagePanel extends JPanel
    {
    	public ImagePanel()
    	{
    		KeyHandler listener = new KeyHandler(); 
    		addKeyListener(listener);
    		setFocusable(true);
    	}
    	public void img(int imgno)
    	{	
    		if (imgno == 1)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\1.png ");
    		}
    		else if (imgno == 2)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\2.png ");
    		}
    	}
    	public void paintComponent(Graphics g)
    	{
    		super.paintComponent(g);
    		a.paintIcon(this,g,200,200);
    	}
    private ImageIcon a;
    private class KeyHandler implements KeyListener
    {
    	public void keyPressed(KeyEvent event)
    	{
    		int KeyCode = event.getKeyCode();
    		if(KeyCode == KeyEvent.VK_1) 
    		{
    			int n = 1;
    			img(n);
    		}
    		if(KeyCode == KeyEvent.VK_2)
    		{
    			int o = 2;
    			img(o); 
    		}
    	}
    	public void keyReleased(KeyEvent event){}
    	public void keyTyped(KeyEvent event){}
    }
    }


    --- Update ---

    /*Errors
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at learnGUI.rev.ImagePanel.paintComponent(ImageTest.java:48)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at javax.swing.JComponent.paintChildren(Unknown Source)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at javax.swing.JComponent.paintChildren(Unknown Source)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at javax.swing.JLayeredPane.paint(Unknown Source)
    	at javax.swing.JComponent.paintChildren(Unknown Source)
    	at javax.swing.JComponent.paintToOffscreen(Unknown Source)
    	at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
    	at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
    	at javax.swing.RepaintManager.paint(Unknown Source)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
    	at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
    	at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
    	at java.awt.Container.paint(Unknown Source)
    	at java.awt.Window.paint(Unknown Source)
    	at javax.swing.RepaintManager$3.run(Unknown Source)
    	at javax.swing.RepaintManager$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    	at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    	at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
    	at javax.swing.RepaintManager.access$1100(Unknown Source)
    	at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$400(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    */


    --- Update ---

    /*Errors
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at learnGUI.rev.ImagePanel.paintComponent(ImageTest.java:48)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at javax.swing.JComponent.paintChildren(Unknown Source)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at javax.swing.JComponent.paintChildren(Unknown Source)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at javax.swing.JLayeredPane.paint(Unknown Source)
    	at javax.swing.JComponent.paintChildren(Unknown Source)
    	at javax.swing.JComponent.paintToOffscreen(Unknown Source)
    	at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
    	at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
    	at javax.swing.RepaintManager.paint(Unknown Source)
    	at javax.swing.JComponent.paint(Unknown Source)
    	at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
    	at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
    	at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
    	at java.awt.Container.paint(Unknown Source)
    	at java.awt.Window.paint(Unknown Source)
    	at javax.swing.RepaintManager$3.run(Unknown Source)
    	at javax.swing.RepaintManager$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    	at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    	at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
    	at javax.swing.RepaintManager.access$1100(Unknown Source)
    	at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$400(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    */

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at learnGUI.rev.ImagePanel.paintComponent(ImageTest.j ava:48)
    There is a null value when line 48 is executed. Look at line 48, find the null value and then backtrack in the code to see where the null value came from.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    line 48 is actually the a.paintComponent(this,g,200,200) statement.
    So that means a is having a value null? There is no image in a?

    --- Update ---

    But I used the img method to load an image to a when i press the key "1" and "2" using the keyPressed method of keyListener.
    How can I rectify the error? Please advise.

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    The paintComponent() method is called BEFORE the user gets a chance to press any keys. Add code there to test if a is null before using the value in a.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #13
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    Yeah you are right! There is nothing in a! What is the solution to this problem?
    How can I rectify it? Where should i actually place the keyPressed method?

    --- Update ---

    Yeah you are right! There is nothing in a! What is the solution to this problem?
    How can I rectify it? Where should i actually place the keyPressed method?

  15. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    The test for a being null would be in the paintComponent() method.

    You can't change the order of when the methods are executed. The user's key pressed can't be recognized before the screen is painted.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #15
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    So I Should paint the screen first then only can I check for any keystrokes and then paint it again?

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    You don't control when the system calls the paint methods. The repaint() method requests that a call be made some time (usually soon).
    What do you want to see on the screen BEFORE the user presses any key?
    What do you want the paintComponent() method to display if a is null?
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    BEFORE the user presses any key I want to display a "WELCOME" image. I have the image.
    And then when I press the key "1" I want to load another image and when I press the key "2" I want to load another message.
    That is what i am trying to do.

    --- Update ---

    Please advise what I should do.

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    Set a to the first image in the constructor so its value is not null when paintComponent() is called.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    Okay. I did that and thankfully my WELCOME image has loaded!!!
    Now what should I do to load another Image when I press the key "1".

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    Change a and call repaint().
    If you don't understand my answer, don't ignore it, ask a question.

  22. #21
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    package learnGUI.rev;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ImageTest 
    {
    	public static void main(String[] args) 
    	{
    		ImageFrame frame = new ImageFrame();
    		frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
    		frame.setVisible(true);
    	}
    }
    class ImageFrame extends JFrame
    {
    	public ImageFrame()
    	{
    		setTitle("KidX");
    		setSize(500,500);
    		ImagePanel panel = new ImagePanel();
    		add(panel);
    	}
    }
    class ImagePanel extends JPanel
    {
    	public ImagePanel()
    	{
    		KeyHandler listener = new KeyHandler(); 
    		addKeyListener(listener);
    		setFocusable(true);
    		a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Welcome\\welcome2.png");
    	}
    	public void img(int imgno)
    	{	
    		if (imgno == 1)
    		{
    		l = 1;
    		}
    		else if (imgno == 2)
    		{
    		l = 2;	  
    		}
    	}
    	public void paintComponent(Graphics g)
    	{   
    		if(l == 1)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\1.png");
    			repaint();
    		}
    		else if(l == 2)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\2.png");
    			repaint();
    		}
    		super.paintComponent(g);
    		a.paintIcon(this,g,200,200);
    	}
    private ImageIcon a;
    private int l;
    private class KeyHandler implements KeyListener
    {
    	public void keyPressed(KeyEvent event)
    	{
    		int KeyCode = event.getKeyCode();
    		if(KeyCode == KeyEvent.VK_1) 
    		{
    			int n = 1;
    			img(n);
    		}
    		if(KeyCode == KeyEvent.VK_2)
    		{
    			int o = 2;
    			img(o); 
    		}
    	}
    	public void keyReleased(KeyEvent event){}
    	public void keyTyped(KeyEvent event){}
     
    }
    }

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    New images should NOT be loaded in the paintComponent() method. Load the image outside of that method and then call repaint() to have the system call the paintComponent() method where the newly loaded image can be displayed.

    BTW It is very poor coding style to use Single letter variable names.
    Variable names should describe what the variable contains.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #23
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?

    The first code after your reply is what I did. Is the repaint() method in the right place? Because upon pressing "1" the image is not changing.

    --- Update ---

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ImageTest 
    {
    	public static void main(String[] args) 
    	{
    		ImageFrame frame = new ImageFrame();
    		frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
    		frame.setVisible(true);
    	}
    }
    class ImageFrame extends JFrame
    {
    	public ImageFrame()
    	{
    		setTitle("KidX");
    		setSize(500,500);
    		ImagePanel panel = new ImagePanel();
    		add(panel);
    	}
    }
    class ImagePanel extends JPanel
    {
    	public ImagePanel()
    	{
    		KeyHandler listener = new KeyHandler(); 
    		addKeyListener(listener);
    		setFocusable(true);
    		a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Welcome\\welcome2.png");
    	}
    	public void img(int imgno)
    	{	
    		if (imgno == 1)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\1.png");
    			repaint();
    		}
    		else if (imgno == 2)
    		{
    			a = new ImageIcon("C:\\Users\\Jerin_Jose.JerinJose\\Desktop\\KidX\\Number Images\\2.png");
    			repaint();  
    		}
    	}
    	public void paintComponent(Graphics g)
    	{   
    		super.paintComponent(g);
    		a.paintIcon(this,g,200,200);
    	}
    private ImageIcon a;
    private class KeyHandler implements KeyListener
    {
    	public void keyPressed(KeyEvent event)
    	{
    		int KeyCode = event.getKeyCode();
    		if(KeyCode == KeyEvent.VK_1) 
    		{
    			int n = 1;
    			img(n);
    		}
    		if(KeyCode == KeyEvent.VK_2)
    		{
    			int o = 2;
    			img(o); 
    		}
    	}
    	public void keyReleased(KeyEvent event){}
    	public void keyTyped(KeyEvent event){}
     
    }
    }


    --- Update ---

    The above code is what I did. I changed the image in another method. Then called repaint() method. But the Image is still not changing upon keypress. what might be the problem?

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,358
    Thanks
    49
    Thanked 2,206 Times in 2,179 Posts

    Default Re: How to change image when a key is pressed?

    The code works for me.
    If you don't understand my answer, don't ignore it, ask a question.

  26. #25
    Junior Member
    Join Date
    Aug 2014
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to change image when a key is pressed?


    Only the WELCOME image is being loaded. There are no errors but the Image is not changing upon Key press.

Page 1 of 2 12 LastLast

Similar Threads

  1. [SOLVED] trying to change image by mouse click
    By leonne in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 5th, 2013, 07:16 PM
  2. KeyListener - how to make program react to the key that was pressed twice?
    By scorpas in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: November 28th, 2012, 07:19 AM
  3. Is Key Pressed statements
    By Yo Cas Cas in forum AWT / Java Swing
    Replies: 6
    Last Post: August 27th, 2011, 12:48 AM
  4. how to know user pressed a key in the keyboard
    By cilang in forum File I/O & Other I/O Streams
    Replies: 16
    Last Post: September 11th, 2009, 10:08 AM
  5. [SOLVED] Change the size of an image
    By subhvi in forum Algorithms & Recursion
    Replies: 4
    Last Post: August 23rd, 2009, 11:44 PM

Tags for this Thread