Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help with event handling

 
Popot Aartsen
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
If you really have time to help a newbie
I am new to java programming, and my mind still with the old structured programming. I do understand about object, inheritance, polymorphic, method, interface, abstract data type. But, when it comes to EVENT handling, I lost Usually in structured programing, you can follow the flow.
So, in order to be more understand, could you please give me some VERY simple (easy to understand) example code to do :
// this is just a generic algorithm
main_program () {
repeat
write "1 = sub1";
write "2 = sub2";
write "0 = exit program";
key = get_a_key ();
if (key = "1") { sub_program1 (); }
if (key = "2") { sub_program2 ("HELLO"); }
until key = "0";
exit(); // exit program
}
sub_program1 () {
b = 0;
repeat
a = 0;
repeat
c = get_keypressed;
write a; // flood the screen with number
a = a + 1;
until c = <exit_key>;
write b;
b = b + 1;
until b = 3;
return; // go back to main program
}
sub_program2 (s) {
write s;
return;
}
My objective here is to learn how to call a subprogram, and designing event handler in object oriented way.
thanks,
 
Bal Mark
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not going to translate your code .. but as for handling the events .. its done using listeners.
If you want to listen to key events .. get the object that you want to listen to (ie. a JTextField ) and add a KeyListener to it using the addKeyListener(KeyListener) on the JTextField you created
This is basically telling the JTextField where to go if you want to look at the keys pressed and do stuff on them ..
erm ok .. an example
(ps. a KeyAdapter is just a KeyListener with empty methods so you just override the methods you want to use )
JTextField f = new JTextField();
f.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println("Enter was just pressed");
}
}
});

now when you press enter in that JTextField it'll print a message "Enter was just pressed"
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're trying to better understand event-driven programming, you may appreciate the chapters in part 4 of Interactive Programming In Java by Lynn Andrea Stein.
------------------
Balmark,
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic