I know this should go in advanced topics,but this is just a quick question and i will delete it once i get help. I have code, but the KeyEvent part isnt being called.
import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.util.Random; import javax.swing.JFrame; public class main { public static Random rand = new Random(); public static String gameTitle = "Game"; public static String gameVersion = "1.0 Alpha"; public static Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); public static JFrame window = new JFrame(gameTitle); public static int windowsize = 500; public static int k = KeyEvent.KEY_PRESSED; public static int up = KeyEvent.VK_UP; public static int down = KeyEvent.VK_DOWN; public static int right = KeyEvent.VK_RIGHT; public static int left = KeyEvent.VK_LEFT; public static void main(String[] args) { window.setDefaultLookAndFeelDecorated(true); int x = (dim.width) / 2 - windowsize / 2; int y = (dim.height) / 2 - windowsize / 2; window.setLocation(x, y); window.setSize(windowsize, windowsize); window.setResizable(false); window.setVisible(true); drawPanel(); } public static void drawPanel() { window.add(new graphics()); if (k == up) { gameVersion = "UP"; } else { gameVersion = "NONE"; } window.invalidate(); window.validate(); window.repaint(); drawPanel(); } }
Offline
muppetds wrote:
I have no idea if this is right but arent you setting the keys to be pressed at the beginning?
Nope, because I made the method the keydown is checked for is infinite.
Offline
WindowsExplorer wrote:
muppetds wrote:
I have no idea if this is right but arent you setting the keys to be pressed at the beginning?
Nope, because I made the method the keydown is checked for is infinite.
hmm ok - just make sure it is done correctly as i have been asked something similar before
Offline
I don't believe you're going about this in the right way. Here's what will work (guaranteed.)
import java.awt.event.*; ... window.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { // do stuff here } public void keyReleased(KeyEvent e) { // do more stuff here } public void keyTyped(KeyEvent e) { // don't do stuff here // it's required by the listener, but never called } }); ...
Offline
Or you could add "implements KeyListener" to the end of your class declaration, and then implement the necessary methods into your main class.
Offline
WindowsExplorer wrote:
I know this should go in advanced topics,
No it shouldn't, "Advanced Topics" is about advanced aspects of Scratch itself.
GeonoTRON's suggestion should work - I haven't used Java in ages (I believe it's too complex of a language for most purposes), but I do remember that the KeyListener object is used to, well, listen to key-press events.
Offline