Results 1 to 19 of 19
  1. #1
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default [SOLVED] KeyListeners in JavaApplets

    So I've decided to continue on my gun applet. I've gotten the stick figure to move his pistol up to a certain angle and fire bullets off that angle. Now what I want to do is replace the if statements that I used to fire the gun (it was a simple loop once a certain angle was reached) to a key listener of when I hit the spacebar and replace the if statement that moves the gun up or down, with keylisteners to the arrow keys.

    So here is what I am looking to find.

    1. How do I make a KEY listener like the one I described
    2. What are the names for the up arrow, down arrow, and spacebar keys?
    3. Given the bellow code how do I do this?

    Thanks in advance!!!1

    PHP Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.KeyListener;
    import java.awt.geom.Line2D;
    import javax.swing.JApplet;
    import java.awt.*;
    
    
    public class Gunmaster extends JApplet implements Runnable
    {
    	final static int WIDTH = 400, HEIGHT = 200;
    	private bulletfire bullet;
    	double stickx = 50, sticky = 50, angle = -Math.PI/3, angle2 = angle, shoot = 0; 
    	double arrowx = stickx +4, arrowy = sticky + 16;
    	Thread runner = null;
    	private Image dbImage;
    	private Graphics dbg;
    	private double vy, vx, anglex, angley, angle3;
    
    
    
    	
    	public void init() 
    	{
    		
    		bullet = new bulletfire(stickx+24,sticky+15);
    		bullet.start();	
    		
    	    runner = new Thread(this);
    		runner.start();	   
    	}
    
    	
    	public void paint(Graphics g)
    	{
    		Graphics2D g2 = (Graphics2D)g;
    		setSize(WIDTH,HEIGHT);
    		Rectangle clear = new Rectangle(0,0,WIDTH,HEIGHT);
    		Gunman stickbob = new Gunman(stickx,sticky,angle);
    		
    		g2.setColor(Color.white);
    		g2.fill(clear);
    		g2.setColor(Color.black);
    	    stickbob.draw(g2);
    	    
    	     
    	    if(angle == Math.PI/3)
    	    {
    	    	bullet.chooseon();
    	    }   
    	    bullet2 projectile1 = new bullet2(bullet.getX(),bullet.getY());
    	    bullet.countadd();
    	    g2.rotate(-angle,stickx+4,sticky+16);
    	    projectile1.shoot(g2);
    	    g2.rotate(angle,stickx+4,sticky+16);
    	    
    
    	}
    	
    	public void update(Graphics g)
    	{
    													// initialize buffer
    	      if (dbImage == null)
    	      {
    	            dbImage = createImage (this.getSize().width, this.getSize().height);
    	            dbg = dbImage.getGraphics ();
    	      }
    	      											// clear screen in background
    	      dbg.setColor (getBackground ());
    	      dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
    	      											// draw elements in background
    	      dbg.setColor (getForeground());
    	      paint (dbg);
    	      											// draw image on the screen
    	      g.drawImage (dbImage, 0, 0, this);
    
    	} 
    
    	public void run() {
    
    		 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    
    	    while ( runner != null) {
    	    	if(angle < Math.PI/3)
    	    	{
    	    		angle  = angle + Math.PI/80;
    	    		if(angle > Math.PI/3)
    	    		{
    	    			angle = Math.PI/3;
    	    		}
    	    	}
    	    	repaint();
    	        try {
    	            Thread.sleep(20);
    	        } catch ( InterruptedException e ) {
    	            // do nothing
    	        }
    	    }
    	}
    	
    	class bulletfire extends Thread
    	{
    		private Rectangle r;
    		private int count = 0, chooser = 0;
    		private int xcord, initialx, initialy;
    
    		public bulletfire(double xcor, double ycor)
    		{
    			xcord = (int)xcor;
    			initialx = (int)xcor;
    			initialy = (int)ycor;
    			r = new Rectangle((int)xcor,(int)ycor,20,20);
    		}
    		public void countadd()
    		{
    			count++;
    		}
    		public void chooseon()
    		{
    			chooser = 1;
    		}
    		public void chooseoff()
    		{
    			chooser = 0;
    		}
    		public void turnoff()
    		{
    			count = 22;
    		}
    		public void turnon()
    		{
    			count = 0;
    		}
    		
    		public void run()
    		{
    			 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    			while(count < 21)
    			{
    				if(chooser == 0)
    				{
    					count = 0;
    				}
    				if(chooser == 1 && count < 20)
    				{
    						xcord = xcord + 10;
    						r.x = xcord;
    				}
    				if(count == 20)
    				{
    					count = 0;
    					chooser = 0;
    					xcord = initialx;
    				}
    			 try {
    
    		            Thread.sleep(20);
    
    		        } catch ( InterruptedException e ) {
    
    		            // do nothing
    		        }
    			}
    		
    			}
    	
    		public double getX()
    		{
    			return r.x;
    		}
    		public double getY()
    		{
    			return r.y;
    		}
    	
    	}
    	
    		
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default

    There was a posting here in the last few weeks that showed how to get key strokes. I think it used Key Bindings. Do a search on that.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

  4. #4
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    Hmm I see Key bindings use JComponent. Does that mean I will need to switch my Java Applet to a Java Component? Just wondering so I can begin thinking

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Unome View Post
    Hmm I see Key bindings use JComponent. Does that mean I will need to switch my Java Applet to a Java Component? Just wondering so I can begin thinking
    Perhaps. Your best option may be to have a class that contains and can return a JComponent that can then be placed in a JApplet's contentPane. This will increase the flexibility of your program making it easy to place in a JApplet or JFrame at will. Also, I'm not a big fan of subclassing components unless one is changing the innate behavior of that component.

  6. #6
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    I'm researching key bindings but am having a very difficult time finding an example of them... I need to see some of the code of how key bindings are used to really understand how to use them. I'm looking at the description, but it doesn't even give me the import statements for the clases I need. I'll accept any information on Key Bindings, or on Key listeners or how you use them. Please help

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default

    Do a Search for InputMap and ActionMap. I think there are code examples on this forum.

  8. #8
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    I looked up what you told me and learned a little more...

    I know now the following:

    upArrow = 38(keycode)
    downArrow = 40(keycode)
    spacebar = 32(keycode)

    I also learned that you can add keyListneres to text fields and I believe buttons. I know how to add my key listener but not a button. I think if I make a default button or an invisible button and use my keylistner on it, I can make this work. Any suggestions hints ideas? help lol

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    again, not keylisteners but use keybindings. Don't use "magic numbers" for your keycodes, use the constants of the KeyEvent class.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Here's a good link that shows a bit on KeyListeners in action: Swing - Detecting two keys at once

  11. #11
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    1. How do I make a KEY listener like the one I described
    You can do this with a KeyListener but it is more work and there can be subtle focus issues to deal with. Key binding is the preferred way for this.
    2. What are the names for the up arrow, down arrow, and spacebar keys?
    Look these up in the Field Summary section of the KeyEvent class api. You specify the "up" key with the int KeyEvent.VK_UP.
    I see Key bindings use JComponent. Does that mean I will need to switch my Java Applet to a Java Component?
    No. You can bind keys to the applets JRootPane (which extends JComponent) - see JRootPane class api for overview and details. Or you can bind them to a child JComponent extension, eg, a JPanel used for drawing/graphics. Focus issues can be a factor in your choice; rootpane binding keeps things simple.
    I need to see some of the code of how key bindings are used to really understand how to use them.
    Fair enough.
    I'm looking at the description, but it doesn't even give me the import statements for the clases I need.
    Learning to use the javadocs is a key to freedom in writing java code.
    Java Code:
    // <applet code="KeyFire" width="400" height="400"></applet>
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    
    public class KeyFire extends JApplet {
        KeyFirePanel keyFirePanel;
    
        public void init() {
            keyFirePanel = new KeyFirePanel();
            keyFirePanel.setFocusable(true);
            add(keyFirePanel);
            bindKeys();
        }
    
        private void bindKeys() {
            JRootPane rp = getRootPane();
            int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
            InputMap inputMap = rp.getInputMap(c);
            ActionMap actionMap = rp.getActionMap();
            inputMap.put(KeyStroke.getKeyStroke("UP"), "UP");
            actionMap.put("UP", upAction);
            inputMap.put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
            actionMap.put("DOWN", downAction);
            inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
            actionMap.put("RIGHT", rightAction);
        }
    
        public static void main(String[] args) {
            JApplet applet = new KeyFire();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
        }
    
        private AbstractAction upAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                keyFirePanel.rotateRect(-1);
            }
        };
    
        private AbstractAction downAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                keyFirePanel.rotateRect(1);
            }
        };
    
        private AbstractAction rightAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                keyFirePanel.fire();
            }
        };
    }
    
    class KeyFirePanel extends JPanel {
        Rectangle rect = new Rectangle(25,165,75,20);
        int angle = 0;
        int inc = 5;
        boolean firing = false;
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            double theta = Math.toRadians(angle);
            double x = rect.getCenterX();
            double y = rect.getCenterY();
            AffineTransform at = AffineTransform.getRotateInstance(theta,x,y);
            g2.draw(at.createTransformedShape(rect));
            if(firing) {
                // In place of rendering your bullet animation.
                double dx = (rect.width/2) + 15;
                FontRenderContext frc = g2.getFontRenderContext();
                LineMetrics lm = g2.getFont().getLineMetrics("0", frc);
                double strHeight = lm.getAscent() + lm.getDescent();
                double dy = strHeight/2 - lm.getDescent();
                Point2D.Double p = new Point2D.Double(x+dx, y+dy);
                Point2D xp = at.transform(p, null);
                at.setToRotation(theta);
                g2.setFont(g2.getFont().deriveFont(at));
                g2.drawString("bang", (float)xp.getX(), (float)xp.getY());
            }
        }
    
        public void rotateRect(int direction) {
            firing = false;
            angle += direction*inc;
            repaint();
        }
    
        public void fire() {
            firing = true;
            repaint();
        }
    }

  12. #12
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    Thankyou SO much hardwired.. your a great programmer. Now I just got to apply it to the thread :) I should be able to handle it... you gave me a running start

  13. #13
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    Thanks for solving my question!
    Last edited by Unome; 10-24-2008 at 08:25 AM.

  14. #14
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    How do I make it run despite holding a key or not?
    Fire up a new Thread to start an animation along a line from beginning to end, viz, boundry of component.
    There are a lot of ways you could put something like this together.
    Here's an idea to get started:
    Java Code:
    public class KeyFire extends JApplet {
        ...
        KeyFireRunner keyFireRunner;
    
        public void init() {
            ...
            keyFireRunner = new KeyFireRunner(keyFirePanel);
            ...
        }
    
        private AbstractAction rightAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                keyFirePanel.fire();
                keyFireRunner.start();
            }
        };
    
        ...
    }
    
    class KeyFirePanel extends JPanel {
        ...
        Line2D.Double lineOfFire = new Line2D.Double();
        Ellipse2D.Double ball = new Ellipse2D.Double(0,0,10,10);
        ...
    
        protected void paintComponent(Graphics g) {
            ...
            if(firing) {
                g2.setPaint(Color.pink);
                g2.draw(lineOfFire);  // optional
                g2.setPaint(Color.red);
                g2.fill(ball);
            }
        }
    
        public void fire() {
            // Calculate beginning and end (end is offscreen)
            // of the line of travel for projectile ("ball").
            lineOfFire.setLine(x1, y1, x2, y2);
            ball.setFrameFromCenter(x1, y1, x1+ball.width/2, y1+ball.height/2);
            // Set other variables as needed, including
            firing = true;
            repaint();
        }
    
        public boolean step() {
            // Increment (member variable) distance along line
            // for next position of projectile.
            // Calculate next position.
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
            firing = test_if_projectile_is_still_in_bounds
            repaint();
            return firing;
        }
    }
    
    class KeyFireRunner implements Runnable {
        ...
    
        public void run() {
            while(running) {
                try {
                    Thread.sleep(delay);
                } catch(InterruptedException e) {
                    running = false;
                }
                boolean more = keyFirePanel.step();
                if(!more) {
                    stop();
                }
            }
        }
    
        // Methods to start and stop this thread.
    }

  15. #15
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    mmk I've ran around some trouble when trying to add the thread to the code, and I have no clue why. I'm probobally leaving out some important thing. I feel bad bugging you guys so much... My java teacher doesn't really know how to program, so its independent study so you guys are all I got :confused:.

    When I started working to put the thread within the code I realized a problem immediately, and I've been trying to work around it but I'm not sure what I'm doing wrong. There are three errors I'll mark um in red bold.

    I was

    // <applet code="KeyFire" width="400" height="400"></applet>
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;


    public class Gunmaster2 extends JApplet {
    KeyFirePanel keyFirePanel;
    KeyFireRunner keyFireRunner;

    public void init() {
    keyFirePanel = new KeyFirePanel();
    keyFireRunner = new KeyFireRunner(keyFirePanel);

    keyFirePanel.setFocusable(true);
    add(keyFirePanel);
    bindKeys();
    }

    private void bindKeys() {
    JRootPane rp = getRootPane();
    int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
    InputMap inputMap = rp.getInputMap(c);
    ActionMap actionMap = rp.getActionMap();
    inputMap.put(KeyStroke.getKeyStroke("UP"), "UP");
    actionMap.put("UP", upAction);
    inputMap.put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
    actionMap.put("DOWN", downAction);
    inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
    actionMap.put("RIGHT", rightAction);
    inputMap.put(KeyStroke.getKeyStroke("SPACE"), "released");
    actionMap.put("released", releasedAction);

    }

    public static void main(String[] args) {
    JApplet applet = new Gunmaster();
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(applet);
    f.setSize(400,400);
    f.setLocation(200,200);
    applet.init();
    f.setVisible(true);
    }

    private AbstractAction upAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    keyFirePanel.rotateRect(1); //-1 is needed to go up
    }
    };

    private AbstractAction downAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    keyFirePanel.rotateRect(-1); // + 1 is needed to go down
    }
    };

    private AbstractAction rightAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    keyFirePanel.fire();
    keyFireRunner.start();
    }
    };

    private AbstractAction releasedAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    keyFirePanel.draw();
    }
    };
    }

    class KeyFirePanel extends JPanel {
    int angle = 0;
    int anglefire = 0;
    int inc = 5;
    int stickx = 50;
    int sticky =50;
    int bulx = 0;
    int count2 = 1;
    int count = 0;
    boolean firing = false;


    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    double theta = Math.toRadians(angle);
    Rectangle clear = new Rectangle(0,0,500,500);
    Gunman stickbob = new Gunman(stickx,sticky,theta);
    g2.setColor(Color.WHITE);
    g2.fill(clear);
    stickbob.draw(g2);
    g2.setColor(Color.BLACK);

    if(count == 0)
    {anglefire = angle;}

    if(firing)
    {

    bullet2 projectile1 = new bullet2(stickx+16 + bulx,sticky+14);
    g2.rotate(Math.toRadians(-anglefire),stickx+4,sticky+16);
    projectile1.shoot(g2);
    g2.rotate(Math.toRadians(anglefire),stickx+4,stick y+16);
    count++;
    if(count == 10)
    {
    anglefire = 0;
    bulx = 0;
    count = 0;
    firing = false;
    }
    }
    }



    public void rotateRect(int direction) { //rotates arm up or own
    angle += direction*inc;
    repaint();
    }

    public void fire() { //fires the bullet
    firing = true;
    repaint();
    }

    public int step() {
    bulx= bulx + 10;
    firing = true;
    repaint();
    return count;
    }
    public void draw() { //draws
    repaint();
    }
    }

    class KeyFireRunner implements Runnable {
    boolean running = false;

    public KeyFireRunner()
    {

    }


    public void run() {
    while(running) {
    try {
    Thread.sleep(0);
    } catch(InterruptedException e) {
    running = false;
    }
    int more = keyFirePanel.step();
    if(more >= 10) {
    running = false;
    }
    }
    }

    }

    The first error says "The Constructor jeyFireRunner(keyFirePanel)" cannot be resolved

    The second error says "The method "start" is undefined"

    the third error says "KeyFirePanel cannot be resolved" Whats the reason for these errors? do you know?
    Last edited by Unome; 10-24-2008 at 09:06 PM.

  16. #16
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    The first error says "The Constructor jeyFireRunner(keyFirePanel)" cannot be resolved
    The compiler cannot find (resolve) a constructor in the KeyFireRunner class that has the signature:
    Java Code:
    KeyFireRunner(KeyFirePanel kfp)
    You have to add a constructor to the class that will take a KeyFirePanel argument, ie, that has a single parameter of type KeyFirePanel.

    The second error says "The method "start" is undefined"
    You will have to add a start method to the KeyFireRunner class. This is the method you call to start a new thread in/of this class:
    Java Code:
    thread = new Thread(this);
    thread.start();
    where "thread" is a member variable (which you will need to declare).

    the third error says "KeyFirePanel cannot be resolved" Whats the reason for these errors? do you know?
    You will need to have a member variable "keyFirePanel" which you initialize in the constructor:
    Java Code:
    class KeyFireRunner implements Runnable {
        KeyFirePanel keyFirePanel;  // member variable has class scope
    
        public KeyFireRunner(KeyFirePanel kfp) {
            // Assign value of argument "kfp"
            // to member variable "keyFirePanel".
            // This initializes the member variable.
            keyFirePanel = kfp;
        }

  17. #17
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    Ughh... Still no luck on making the bullet fire with the code implemented

    This is my code:

    PHP Code:
    // <applet code="KeyFire" width="400" height="400"></applet>
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    
    
    public class Gunmaster2 extends JApplet {
    KeyFirePanel keyFirePanel;
    KeyFireRunner keyFireRunner;
    
    public void init() {
    keyFirePanel = new KeyFirePanel();
    keyFireRunner = new KeyFireRunner(keyFirePanel);
    
    keyFirePanel.setFocusable(true);
    add(keyFirePanel);
    bindKeys();
    	}
    
    	private void bindKeys() {
    		JRootPane rp = getRootPane();
    		int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
    		InputMap inputMap = rp.getInputMap(c);
    		ActionMap actionMap = rp.getActionMap();
    		inputMap.put(KeyStroke.getKeyStroke("UP"), "UP");
    		actionMap.put("UP", upAction);
    		inputMap.put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
    		actionMap.put("DOWN", downAction);
    		inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
    		actionMap.put("RIGHT", rightAction);
    		inputMap.put(KeyStroke.getKeyStroke("SPACE"), "released");
    		actionMap.put("released", releasedAction);
    
    	}
    
    	public static void main(String[] args) {
    		JApplet applet = new Gunmaster();
    		JFrame f = new JFrame();
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		f.add(applet);
    		f.setSize(400,400);
    		f.setLocation(200,200);
    		applet.init();
    		f.setVisible(true);
    }
    
    	private AbstractAction upAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.rotateRect(1); //-1 is needed to go up
    		}
    };
    
    	private AbstractAction downAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.rotateRect(-1); // + 1 is needed to go down
    		}
    };
    
    	private AbstractAction rightAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.fire();
    			keyFireRunner.start();
    		}
    };
    
    	private AbstractAction releasedAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.draw();
    		}
    };
    }
    
    	class KeyFirePanel extends JPanel {
    		int angle = 0;
    		int anglefire = 0;
    		int inc = 5;
    		int stickx = 50;
    		int sticky =50;
    		int bulx = 0;
    		int count2 = 1;
    		int count = 0;
    		boolean firing = false;
    
    
    		protected void paintComponent(Graphics g) {
    			super.paintComponent(g);
    			Graphics2D g2 = (Graphics2D)g;	
    			double theta = Math.toRadians(angle);
    			Rectangle clear = new Rectangle(0,0,500,500);
    			Gunman stickbob = new Gunman(stickx,sticky,theta,100);
    			g2.setColor(Color.WHITE);
    			g2.fill(clear);
    			stickbob.draw(g2);
    			g2.setColor(Color.BLACK);
    
    		if(count == 0)
    		{anglefire = angle;}
    
    	if(firing)
    	{
    		bullet2 projectile1 = new bullet2(stickx+16 + bulx,sticky+14);
    		g2.rotate(Math.toRadians(-anglefire),stickx+4,sticky+16);
    		projectile1.shoot(g2);
    		g2.rotate(Math.toRadians(anglefire),stickx+4,sticky+16);
    		count++;
    		if(count == 10)
    		{
    			anglefire = 0;
    			bulx = 0;
    			count = 0;
    			firing = false;
    		}
    	}
    }
    
    
    
    		public void rotateRect(int direction) { //rotates arm up or own
    			angle += direction*inc;
    			repaint();
    		}
    
    		public void fire() { //fires the bullet
    			firing = true;
    			repaint();
    		}
    
    		public void step() {
    			bulx= bulx + 10;
    			firing = true;
    			
    		}
    		public void draw() { //draws
    			repaint();
    		}
    	}
    
    	class KeyFireRunner implements Runnable {
    		boolean running = false;
    		KeyFirePanel keyFirePanel;  // member variable has class scope
    		Thread superthread;
    
    		public KeyFireRunner(KeyFirePanel kfp) {
    	        keyFirePanel = kfp;
    		}
    		
    		public void start()
    		{
    			superthread = new Thread(this);
    			superthread.start();
    			running = true;
    		}
    
    
    
    		public void run() {
    			while(running) {
    				
    				try {	
    					Thread.sleep(0);
    				} catch(InterruptedException e) {
    					
    				}
    				keyFirePanel.step();
    				keyFirePanel.repaint();
    
    			}
    			
    			
    }
    
    }

    I'm getting this error message:

    "Exception in thread "Thread-9" java.lang.NoSuchMethodError: KeyFirePanel.step()V
    at KeyFireRunner.run(Gunmaster2.java:166)
    at java.lang.Thread.run(Unknown Source)"

    What do I need to fix in my code to make this thing work right?

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default

    Is it possible that all of the class files were NOT compiled at the same source level? Ie there are old versions of class files being used.

  19. #19
    Unome is offline Member
    Join Date
    Oct 2008
    Posts
    44
    Rep Power
    0

    Default

    Hmm... I'm nots sure about that... I tweaked some things... and now I'm getting a BUTLOAD OF ERRORS...

    PHP Code:
    // <applet code="KeyFire" width="400" height="400"></applet>
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    
    
    public class Gunmaster2 extends JApplet {
    KeyFirePanel keyFirePanel;
    KeyFireRunner keyFireRunner;
    
    public void init() {
    keyFirePanel = new KeyFirePanel();
    keyFireRunner = new KeyFireRunner(keyFirePanel);
    
    keyFirePanel.setFocusable(true);
    add(keyFirePanel);
    bindKeys();
    	}
    
    	private void bindKeys() {
    		JRootPane rp = getRootPane();
    		int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
    		InputMap inputMap = rp.getInputMap(c);
    		ActionMap actionMap = rp.getActionMap();
    		inputMap.put(KeyStroke.getKeyStroke("UP"), "UP");
    		actionMap.put("UP", upAction);
    		inputMap.put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
    		actionMap.put("DOWN", downAction);
    		inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
    		actionMap.put("RIGHT", rightAction);
    		inputMap.put(KeyStroke.getKeyStroke("SPACE"), "released");
    		actionMap.put("released", releasedAction);
    
    	}
    
    	public static void main(String[] args) {
    		JApplet applet = new Gunmaster();
    		JFrame f = new JFrame();
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		f.add(applet);
    		f.setSize(400,400);
    		f.setLocation(200,200);
    		applet.init();
    		f.setVisible(true);
    }
    
    	private AbstractAction upAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.rotateRect(1); //-1 is needed to go up
    		}
    };
    
    	private AbstractAction downAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.rotateRect(-1); // + 1 is needed to go down
    		}
    };
    
    	private AbstractAction rightAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.fire();
    			keyFireRunner.start();
    			keyFireRunner.run();
    		}
    };
    
    	private AbstractAction releasedAction = new AbstractAction() {
    		public void actionPerformed(ActionEvent e) {
    			keyFirePanel.draw();
    		}
    };
    }
    
    	class KeyFirePanel extends JPanel {
    		int angle = 0;
    		int anglefire = 0;
    		int inc = 5;
    		int stickx = 50;
    		int sticky =50;
    		int bulx = 0;
    		int count2 = 1;
    		int count = 0;
    		boolean firing = false;
    
    
    		protected void paintComponent(Graphics g) {
    			super.paintComponent(g);
    			Graphics2D g2 = (Graphics2D)g;	
    			double theta = Math.toRadians(angle);
    			Rectangle clear = new Rectangle(0,0,500,500);
    			Gunman stickbob = new Gunman(stickx,sticky,theta,100);
    			g2.setColor(Color.WHITE);
    			g2.fill(clear);
    			stickbob.draw(g2);
    			g2.setColor(Color.BLACK);
    
    		if(count == 0)
    		{anglefire = angle;}
    
    	if(firing)
    	{
    		bullet2 projectile1 = new bullet2(stickx+16 + bulx,sticky+14);
    		g2.rotate(Math.toRadians(-anglefire),stickx+4,sticky+16);
    		projectile1.shoot(g2);
    		g2.rotate(Math.toRadians(anglefire),stickx+4,sticky+16);
    		count++;
    		if(count == 10)
    		{
    			anglefire = 0;
    			bulx = 0;
    			count = 0;
    			firing = false;
    		}
    	}
    }
    
    
    
    		public void rotateRect(int direction) { //rotates arm up or own
    			angle += direction*inc;
    			repaint();
    		}
    
    		public void fire() { //fires the bullet
    			firing = true;
    			repaint();
    		}
    
    		public void step2() {
    			
    			
    		}
    		public void draw() { //draws
    			repaint();
    		}
    
    
    
    		public void step() {
    			// TODO Auto-generated method stub
    			bulx= bulx + 10;
    			firing = true;
    		}
    	}
    
    	class KeyFireRunner implements Runnable {
    		boolean running = false;
    		KeyFirePanel keyFirePanel;  // member variable has class scope
    		Thread superthread;
    		
    
    		public KeyFireRunner(KeyFirePanel kfp) {
    	        keyFirePanel = kfp;
    	        superthread = new Thread(this);
    	        superthread.start();
    		}
    		
    		public void start()
    		{
    			
    			running = true;
    		}
    
    
    
    		public void run() {
    			while(running) {
    				keyFirePanel.step();
    				System.out.print("Jeff is stupid");
    				keyFirePanel.repaint();
    				try {	
    					Thread.sleep(0);
    				} catch(InterruptedException e) {
    					
    				}
    				
    
    			}
    			
    			
    }
    
    }

    Exception in thread "AWT-EventQueue-1" java.lang.NoSuchMethodError: KeyFirePanel.step()V
    at KeyFireRunner.run(Gunmaster2.java:170)
    at Gunmaster2$3.actionPerformed(Gunmaster2.java:65)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.KeyboardManager.fireBinding(Unknown Source)
    at javax.swing.KeyboardManager.fireKeyboardAction(Unk nown Source)
    at javax.swing.JComponent.processKeyBindingsForAllCom ponents(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unkn own Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEv ent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKe yEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAsse rtions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent (Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Last edited by Unome; 10-30-2008 at 11:37 PM. Reason: forgot info

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •