Results 1 to 4 of 4
  1. #1
    Phill Phan is offline Member
    Join Date
    Jan 2011
    Posts
    2
    Rep Power
    0

    Default Help adding a keylistener to a paint class

    For a school project I am making a game similar to the old spyhunter games. There is a road being randomly generated and a car that we want to be able to move right and left. The car is a paint object aswell.

    We cant get the program to go into the keylistener at all.

    Java Code:
    package events;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.geom.*;
    
    import java.awt.image.*;
    import javax.imageio.*;
    import java.io.File;
    
     
    public class TestRoad extends JPanel {
     
        private final LinkedList<Point> road = new LinkedList<Point>();
        private final Random random = new Random();
        
        //used to syncrhonize the swing componenets, This is an alternative to multithreading because Swing is not
        //multi threading safe.
        private final javax.swing.Timer timer;
        
        //used to create an outline that creates a shape that can be filled. "CAP_ROUND" sets unclosed segments to
        //be closed roundly witha radius 1/2 the width of the stroke. "JOIN_ROUND" joins segments of the path with 
        //a round point.
       	private final Stroke stroke = new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
       	
        private final float[] fractions = new float[] { 0.0f, 0.25f, 0.5f, 0.75f, 1.0f };
        private final Color[] colors = new Color[] { Color.GRAY, Color.GRAY, Color.GRAY, Color.GRAY, Color.GRAY };
     
        private int paintOffset;
        private boolean smoothSpeed;
        private boolean curvy;
        private boolean flip;
        private int location;
        private int colX;
        
        private int x;
    	private int y;
    	private BufferedImage carImg;
        
        
        
        public TestRoad() {
        	/*
        	Color newColor = JColorChooser.showDialog(
                         this,
                         "Choose Background Color",
                         null);
            System.out.println(newColor);
            */
            
            
            Color colors = new Color(51,102,0);            
    		
            setBackground(colors);
            
            
            //uses setPreferredSize instead of setSize because parent component utilizes a layout manager.
            setPreferredSize(new Dimension(500, 500));
            
            timer = new javax.swing.Timer(25, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    addPoint();
                    repaint();
                }
            });
            
            // generate an initial road
            
            setSize(400, 400);
            do {
                addPoint();
            }
            while(road.getFirst().y < 410);
    
    		
    			
    			// getting the car file
    			
    		try
    		{
    			carImg = ImageIO.read(new File("C:/Documents and Settings/635739/Desktop/ExampleRoad/playerCar.gif"));
    			System.out.println("found car");
    				
    		}
    		catch (Exception ex)
    		{
    			System.out.println("catch");
    		}
    		
    		
    		x=150;
    		y=150;	
    
    
    
        }
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
        //~~~~~~~~~~~~~~~keylistener starts here~~~~~~~~~~~~~~~~~
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     
     
    
        public void keyTyped(KeyEvent e)
        	{
        	
        	}
        	
    	 public void keyPressed(KeyEvent e)
    	 {
    	 	int Location = e.getKeyLocation();
    	    if(e.getKeyCode()==KeyEvent.VK_UP)
    	    {
    	    	y-=2;	
    	   	}
               		
    	    if(e.getKeyCode()==KeyEvent.VK_DOWN)
    	    {
    	       	y+=2;	
    	    }
    	            
    	    if(location == KeyEvent.KEY_LOCATION_RIGHT)
    	    {
    	    	x+=4;
    	     	System.out.println("x" + x + " Y" + y);	
    	   	}
    	            
    	    if(e.getKeyCode()==KeyEvent.VK_LEFT)
    	    {
    	   		x-=4;	
    	    }
    	    
    	    System.out.println("x" + x + " Y" + y);
    	   	this.repaint();  
    
    	   
    	 }
    
      //~~~~~~~ends here~~~~~	
    	    
    	  	public  void keyReleased(KeyEvent e)
    	    {
    	    	
    	    } 
        
        //road gen
     
        public void addPoint() 
        {
            Point next = generateNewPoint();
            road.add(next);
     
            if(next.y < 0) 
            {
                int yOffset = -next.y;
            
                for(Point point : road) 
                {
                    point.y += yOffset;
                }
                if(road.size() > 3 && road.get(2).y > getHeight()) 
                {
                    road.removeFirst();
                    if(curvy) 
                    {
                        road.removeFirst();
                    }
                }
            }
            if(curvy) 
            {
                flip = !flip;
            }
        }
     
        private Point generateNewPoint() {
        	smoothSpeed = true;
        	curvy = true;
            Point next;
            if(road.isEmpty()) {
                next = new Point(getWidth() / 3, getHeight());
            }
            else {
                next = new Point(road.getLast());
            }
     
            int thirdWidth = getWidth() / 3;
            int variance = thirdWidth / 3;
            int xOffset = random.nextInt(variance);
            next.x += xOffset - (variance / 2);
            if(next.x < thirdWidth) {
                next.x += xOffset;
            }
            else if(next.x > getWidth() - thirdWidth) {
                next.x -= xOffset;
            }
            
       //     int	colX = next.x;
     
            int yOffset;
            if(smoothSpeed) {
                yOffset = getHeight() / 20;
            }
            else {
                yOffset = random.nextInt(timer.getDelay() / 5) + 1;
            }
            next.y -= yOffset;
            paintOffset = (paintOffset + yOffset) % getHeight();
     
            return next;
        }
     
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
     
            if(road.isEmpty()) {
                return;
            }
            
            int thirdWidth = getWidth() / 3;
            Path2D path = new Path2D.Double();
            ListIterator<Point> roadPoints = road.listIterator();
            Point point = roadPoints.next();
            path.moveTo(point.x, point.y);
            while(roadPoints.hasNext()) {
                point = roadPoints.next();
                if(curvy && roadPoints.hasNext()) {
                    Point control = point;
                    point = roadPoints.next();
                    path.quadTo(control.x, control.y, 
                            point.x, point.y);
                }
                else {
                    path.lineTo(point.x, point.y);
                }
            }
     
            if(curvy && flip) {
                point = roadPoints.previous();
            }
            path.lineTo(point.x + thirdWidth, point.y);
            while(roadPoints.hasPrevious()) {
                point = roadPoints.previous();
                if(curvy && roadPoints.hasPrevious()) {
                    Point control = point;
                    point = roadPoints.previous();
                    path.quadTo(control.x + thirdWidth, control.y, 
                            point.x + thirdWidth, point.y);
                }
                else {
                    path.lineTo(point.x + thirdWidth, point.y);
                }
            }
            path.closePath();
            
            Graphics2D gg = (Graphics2D) g;
            gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            int offset = paintOffset - getHeight();
            gg.setPaint(new LinearGradientPaint(
                    new Point(0, offset),
                    new Point(0, getHeight() + paintOffset), fractions, colors));
            gg.fill(path);
            gg.setColor(Color.BLACK);
            gg.setStroke(stroke);
            gg.draw(path);
            
            
            gg.drawImage(carImg,x,y ,null);
      
        }
     
     
     
        public static void main(String[] args) 
        {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    final TestRoad road = new TestRoad();
               //     final JSlider slider = new JSlider(5, 100, road.timer.getDelay());
               //     slider.addChangeListener(new ChangeListener() 
               //     {
               //         @Override
               //         public void stateChanged(ChangeEvent e) {
                            road.timer.setDelay(100);
                            //System.out.println(slider.getValue());
                    //    }
                   // });
                   
                    JPanel options = new JPanel();
                 //   options.add(slider);
                    
                    
                    
                 //   options.add(new JCheckBox(new AbstractAction("Smooth") 
                 //   {
                    //    { 
                    //    	putValue(SELECTED_KEY, road.smoothSpeed); 
                   //     }
                        
                   //     @Override
                  //      public void actionPerformed(ActionEvent e) 
                  //      {
                            road.smoothSpeed = true; //(Boolean) getValue(SELECTED_KEY);
                    //        System.out.println(SELECTED_KEY);
                     //   }
                    //}));
                    
                  //  options.add(new JCheckBox(new AbstractAction("Curvy") {
                //        { 
                //        	putValue(SELECTED_KEY, road.curvy); 
                //        }
                        
               //         @Override
               //         public void actionPerformed(ActionEvent e) {
                            road.curvy = true;//(Boolean) getValue(SELECTED_KEY);
                 //       }
               //     }));
                    JFrame frame = new JFrame("On the move");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    
                    frame.addWindowListener(new WindowAdapter() {
                        @Override
                        
                        public void windowOpened(WindowEvent e) {
                            road.timer.start();
                        }
                        
                        @Override
                        public void windowClosing(WindowEvent e) {
                            road.timer.stop();
                        }
                    });
                    frame.getContentPane().add(road);
                    frame.getContentPane().add(options, BorderLayout.PAGE_END);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    }
    Last edited by Phill Phan; 01-20-2011 at 10:06 PM.

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

    Default

    What key listener as I see no code for a key listener nor do I see that you've added one to a component in the massive amount of code that you've posted? Also, are you sure you want to use a key listener and not key binding (please see Swing Tutorial on this for more info)?


    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?

    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [/cod&#101;] below your pasted code like so:

    Java Code:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]

    Luck

  3. #3
    Phill Phan is offline Member
    Join Date
    Jan 2011
    Posts
    2
    Rep Power
    0

    Default

    Sorry about that, I should have read some of the stickies before I posted. Sorry about the lack of comments too, the program is abit of a mess right now.

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

    Default

    No problem, but I still see no KeyListener -- no class that implements the KeyListener interface, and no place where you add a KeyListener to a component. I have to ask, have you even read the tutorial on this yet? If not, please do this before doing anything else.

Similar Threads

  1. Adding a KeyListener to a JFrame with buttons.
    By jamhead in forum AWT / Swing
    Replies: 1
    Last Post: 12-11-2010, 08:29 PM
  2. adding a actionListener but not using inner class
    By hariza in forum AWT / Swing
    Replies: 2
    Last Post: 10-08-2010, 08:24 AM
  3. using paint methode in another class
    By imorio in forum New To Java
    Replies: 8
    Last Post: 08-12-2010, 04:17 PM
  4. Help me in adding keylistener
    By kumarv75 in forum CLDC and MIDP
    Replies: 0
    Last Post: 06-22-2010, 08:10 AM
  5. Adding a new class to a jar file
    By Raul Menendez in forum New To Java
    Replies: 2
    Last Post: 08-21-2008, 05:52 PM

Posting Permissions

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