Skip to main content
gamedev.net
🔒 Locked

[java] Weird Variable problem

Started by C1rdan Mar 9, 2004 at 6:43 PM 5 replies 400+ views
Original Post
C1rdan
C1rdan
I''m trying to make a game, I am working on the controles. I want it so when i press "right" arrow the message will change to "right".
 

//import files 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 


public class gametest extends JComponent implements KeyListener { 
    
   //Player Coords    
   int playerX = 125, playerY = 95; 
   String message = "none"; 

public void keyTyped (KeyEvent k) {} 
public void keyPressed (KeyEvent k) { 
   if (k.getKeyCode() == k.VK_RIGHT) { 
   message = "right"; 
       repaint(); 
   } 
    
}    
    
public void keyReleased(KeyEvent k) {}    
    
    
    
   public static void main (String[] args) { 
      JFrame f = new JFrame("Bontale"); 
    
      //Close when X is pressed 
      f.addWindowListener(new WindowAdapter() { 
         public void windowClosing(Window we) { System.exit(0); } 
         }); 
    
    
      f.setSize(400, 400); 
      f.getContentPane().add(new gametest());    
      f.setVisible( true ); 
      f.setLocation( 200, 200 ); 
       
    } 
public void paintComponent(Graphics g) { 
     g.drawString(message,playerX,playerY); 
    
} 
}  
 
Sneftel
Sneftel
...and what is your question?


"Sneftel is correct, if rather vulgar." --Flarelocke
C1rdan
C1rdan
Why won''t the message change when I press Right.
pinacolada
pinacolada
I dunno exactly what the problem is, but here are some ideas:

1) make sure to set the frame''s layout to null (as in: f.setLayout(null) ), because if you leave it with a default layout, it will completely ignore your requests to resize & move components

2) You might have better luck making gametest a JPanel instead of a JComponent
C1rdan
C1rdan
Lemmie explain more...



I want to make it so when the user presses the right arrow on the keyboard, the message on the screen swiches from "none" to "right". Now, when i test the program, it doesn''t swich.
pinacolada
pinacolada
Oh now I see what you''re missing. You need to register gametest as a key listener. Change these lines:


f.setSize(400, 400);
f.getContentPane().add(new gametest());
f.setVisible( true );
f.setLocation( 200, 200 );


to this:


gametest myGametest = new gametest();
f.setLayout(null);
f.setSize(400, 400);
f.getContentPane().add(myGametest);
f.setVisible( true );
f.setLocation( 200, 200 );
f.addKeyListener(myGametest);
myGametest.addKeyListener(myGametest);
C1rdan
C1rdan
Wow, thanks! I took away the ContentPane().setLayout(null); and it worked for some reason. hmmm, anyway, thanks!!!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.