This site requires JavaScript, please enable it in your browser!
Greenfoot back
Zamoht
Zamoht wrote ...

2013/10/20

Keylistening out of Greenfoot

Zamoht Zamoht

2013/10/20

#
I know this is a Greenfoot forum, but it is the only java forum I know with quick responses and nice people. I'm trying to code some programs in java without Greenfoot. So I have downloaded eclipse and made some simple console programs just printing out stuff. I have also programmed a puzzle game like my Simple Puzzle Game just way simpler. My problem is that the only way I can get the keys pressed is by placing a TextField object and having focus on that. That part of my code looks like this:
public class Puzzle extends Applet implements KeyListener {
	TextField textField;
	
	public void init() {
		textField = new TextField("Random Text");
		this.add(textField, BorderLayout.SOUTH);
		textField.addKeyListener(this);
	}
}
textField.requestFocus(); is placed in the public void paint(Graphics) method. I have implemented the keyPressed(KeyEvent), keyTyped(KeyEvent) and keyReleased(KeyEvent). Again is there a way to get pressed keys without the need to place a TextField object in the applet?
SPower SPower

2013/10/20

#
Some code from some project of mine :)
// frame is a JFrame instance
frame.setFocusable(true);
frame.setFocusTraversalKeysEnabled(true);
// now you can add the keylistener
frame.addKeyListener(...);
If something is added on top of the frame, like a JPanel or something like that, then you have on call the 3 methods to that panel. I haven't used the Applet class a lot, so I don't know for sure whether you can call the methods on that, but I'm sure you can try :)
Zamoht Zamoht

2013/10/20

#
Thanks i managed to create an empty windows using the JFrame and print out "Test" everytime enter was pressed (very basic I know). Now how do I change the size of the window? I tried using setBounds but that didn't work. EDIT: Oh changing frame.pack() to frame.setSize(int, int) worked my bad. Okay and I can use setBounds to change the size and where the windows should start up on the screen. (Learning slowly).
SPower SPower

2013/10/20

#
You mean changing it after you created it? I think you could just do this:
frame.setSize(width, height);
And btw, the basic programs are usually the best and easiest to test these things :)
Zamoht Zamoht

2013/10/20

#
Okay one more thing. How are things with releases in java? Do I have to do it manually or is there some kind of autorelease behind? I have never thought of this when programming in Greenfoot.
You need to login to post a reply.