Java graphical interface How to use the keyboard to control the movement of the ball and the interface of the explanation

Source: Internet
Author: User

How to realize the movement of small balls

Or go first a small ball bar, has done many times, we began to think, if the user presses a key on the keyboard, then son AH the whole computer system, who first know this thing? This everyone can guess the right is the keyboard, but the next thing, the keyboard is the notification to whom? Let's skip the middle link, we'll get to the operating system, right? If your program is going to be able to respond to user input, is the operating system going to notify you of the event? How can the system tell a thing to your program? In fact, we've encountered things like the system before, whether it's the beginning of main, the repaint paint, or the thread run is dealing with the system, the only way to communicate with the system and the program is to prepare a method that will be called at the right time. Do we have to remember the method? Java designers provide a great solution-interface
We now come to know the interface, in fact, in the previous thread we have used the interface runnable, but at that time we did not carefully talk about what the interface is, why must use the interface.
I am an object, I am a male human object, so to speak, man is from a lot of similar objects abstracted out of a concept, man is a human, it should be human sub-category, that is, human is abstracted from men and women, human is a subclass of animals, then animal is human abstraction. We are now going to write a class-animal, you think of the animal class how to write, I think at least have to eat, drink, pull, scatter, sleep these methods, then we define these methods, specific to the "eat" This method, you think there is a way to describe the animal's "eat" it? is not able to describe, because different animals eat a big difference.

class Animal{    publicvoideat(){    //描述如何吃      }    }

The location of the note is not very difficult, I know exactly as an animal must have a way to eat, but I now have no way to describe, since this looks like simply do not describe.

class Animal{    publicvoideat();    }

If you write this on eclipse, you will find that the editor will immediately error, because there is no method of the subject, but do not know how to write the subject Ah, then you can explain this method before this method is "abstract".

class Animal{    publicabstractvoideat();    }

This place in the animal class immediately gave an error, suggesting that if there were abstract methods in the class, then the class would need to be described as abstract. In fact, it is very well understood, we abstract, abstract to a certain extent, got a class called animal, but this class is too abstract, a lot of things I can not describe, then I told the Java editor, this is abstract, I do not specifically write the content.

abstract class Animal{publicabstractvoideat();}

Another question is, can abstract classes produce objects? If you're a Java editor and someone gives you a code that makes an abstract class into an object, do you have a way to do it? So abstract classes cannot generate objects.
Let's think about the other ways of animal, you will find that all the methods can not be described, not only the method cannot be described, and can not find the need to declare variables, we tube such a class is called Pure abstract class, in Java pure abstract class will be replaced by another name called interface.

interface Animal{    publicvoid eat();    }class Person implements Animal{}    

We use a human class to implement the interface of the animal, the code is written here, you will find the person under the red wavy line, this class is wrong, put the mouse on the man above, prompted to tell you, must implement the interface animal inside the abstract method eat. What's the use of this?
For example, or my teacher and I said, suppose I am now a class of teachers, the class has 20 students, I think every day class too hard, and money also earn less, I now come up with a good way, I go out to a software development live, quote 100,000, according to the previous standard, about 100,000 lines of code volume, My class changed into a training program, also do not have classes, each student on average 5000 lines of code, the respective home to complete, a semester ended, completed the students this course passed, and not only earned the lecture money, but also the outsourcing of the software money to earn, this plan looks very good, but there is a problem, is to the end, I need to combine 100,000 lines of code written by 20 people to get the sales, so do I have to read 100,000 lines of code? No, this looks too tired, so I rule, students to write their own 5000 lines of code to write the comments, each person has a maximum of 200 lines on the label is for me to see, the other I can not see the merger, this rule in Java do not need, all to show me the code before to write public, Do not need me to read the private, this is understood, the definition of common, the main purpose of private is to reduce the project manager's workload, in fact, in the object-oriented, the project manager will not look at a line, maybe everyone handed me is 5 classes, 20 people is 100 classes, just need to write a main program, New to the object, and then the call is good. It's not that easy to do, project managers not only need to know how to use Java classes, but also to learn the class of project team members, so there is a lot of technology to simplify the project manager's work, for example, there is no construction method, each class of project managers will learn one more method.
Now there is a problem, that is, students work, the teacher did not work, the teacher to wait for all the students will be handed in to write the main program, which is a bit delayed, can students and teachers at the same time write programs? Now it seems impossible, because the teacher does not know the situation of each class, the main method, it seems that the teacher needs to specify the methods contained in each class beforehand, and then hand over the described documents to the students. But this also has the hidden danger, if the student did not follow the document stipulation to complete what? At this time the interface appeared, the teacher can give each student to distribute 5 interface, let everybody to realize, realize interface means must implement inside of abstract method, such interface becomes the project manager and project team members of mandatory agreement, this time in back to think about interface this word is not particularly in line with.
Interface is not just for this purpose, I have an example here. Suppose I now take a business management software project, planning finance, production and sales system, but this unit of funds can not be put in place so much, now decided to develop financial and sales system, production system to stay, wait until the funds in place to develop. So what am I supposed to do? Maybe I'll develop a menu with three options: finance, Production and sales, I will set the current non-developed production system to gray, and so the money in place, I then developed into a usable state, the user click "Production", will produce a method call, call to my future development of the production system module method, that is, I want to make this method call now, although this method does not exist now, how can I ensure that if I am not in this software company after a few years, others will be able to write exactly the method that is called? I can develop this menu, leave an interface, the future development of the production system of the people as long as the implementation of this interface, then his program can be integrated into the existing program. Interface becomes the agreement of predecessors and posterity, how? is the word interface especially in place? It seems that there is no more suitable term for this word.
Back to the task, I want to write a code to respond to the user's keyboard input, how to write a method to make the system call it? In fact, the system call has been written well, now know, the system will provide an excuse to me, I just need to implement this excuse is good. It seems that the thread's runnaable also play a role, and the implementation method is run.
The excuse of the keyboard is KeyListener, put in java.awt.event inside, write when importing
import java.awt.event.*;

This time the attentive person will find that I have not been imported before

import java.awt.*;

It? No, I'm telling you now, this import is effective on a layer, and Eclipse has an auxiliary tool to help you import it. However, it is still a reminder that excessive reliance on tools is not a good thing, and all the way through Notepad to write code is the real programming, because this will ensure that each letter is their own code, will build a sense of the code.

Import Java.awt.*;import java.awt.event.*; Public  class myball {     Public Static voidMain (string[] args) {//TODO auto-generated method stubFrame W =NewFrame (); W.setsize ( -, -); Myoval MP =NewMyoval ();        W.add (MP);    W.show (); }} class myoval extends Panel implements KeyListener{      Public voidPaint (Graphics g) {G.filloval ( -, -, -, -); }

The code here, you will find that there are red wavy lines below the Mypanel, indicating there are errors, we know because there are non-implemented abstract methods, these methods are what we want. In front of this line, you can see a small red fork icon you can see, click with the mouse, will pop up a window, there is an option to "add the non-implemented method"


Is the first add unimplemented methods, just choose it, with the mouse click, you will see the following suddenly jumped out a lot of code


A closer look, is 3 methods, there are keypressed (Key Press), (key to lift), Kettype (Key Press), keyreleased (key lift), KeyType more special, the first two is the comparison of the underlying method, to identify a key action, But we know that there are many key combinations on the keyboard, such as the "shift+a" key combination, which requires keytype to be recognized. I'd better put the code in.

 class myoval extends Panel implements KeyListener{     Public voidPaint (Graphics g) {G.filloval ( -, -, -, -); } @Override Public voidkeytyped (KeyEvent e) {//TODO auto-generated method stub} @Override Public voidkeypressed (KeyEvent e) {//TODO auto-generated method stub} @Override Public voidkeyreleased (KeyEvent e) {//TODO auto-generated method stub}

Now has the keyboard input method, but still one step, the system does not only take you to receive, or say that the system does not know that your object to handle keyboard input, as if there is one thing happened, my mobile phone number has changed, in fact, I have no impact, I want to find anyone can find, as long as I have someone else's number, But in turn, to other people have influence ah, I am the event of the departure, you are the event of the handler, you because of this matter, you want to contact me in the phone contact update, the problem is, if I do not have your number, I will not notify you, so here is a step-register the event.
We know that the class that implements the interface is Mypanel, the class does not work, its object may be the processor, then the MP is the processor, who is the issuer of the event? Supposedly it should be the keyboard, but things outside of the program we don't care about, this event first arrives at the form, so we need to

publicclass MyBall {    publicstaticvoidmain(String[] args) {        // TODO Auto-generated method stub        new Frame();        w.setSize(300400);        new MyOval();        w.add(mp);        //注册事件        w.addKeyListener(mp);        w.show();    }

However, there is a problem here, there are currently two objects in our program, one is a form, the form is placed on a panel, most of the time the form is the basis of the program, keyboard events will reach the form, but if the mouse in the middle of the form on the panel, keyboard events will not be received, Because the current valid object becomes a panel, we add a statement to avoid the treasure case. The code becomes the amount of this

public   Class  Myball {public  static  void  main  (string[] args) {//TODO        auto-generated method Stub  Frame w = new  Frame ();        W.setsize (300 , 400 );        Myoval MP = new  myoval ();        W.add (MP);        //Register event  W.addkeylistener (MP);        Mp.addkeylistener (MP);    W.show (); }

The new sentence seems a bit strange, it seems that we have MP added to the MP, this is because the MP has two identities, the front with MP is because this is the object of the Panel, the latter with the MP is because it is the processor of the keyboard event. Let's focus now on what to do with the events we receive. In my opinion, the event is handled in three steps
1. Implementing the interface
2. Registering events
3. Writing Event handlers
First come to know the very important statement. Remember the previous few "Hello world!" It? In fact, in the console print a word, although printing to the console is very boring, but we still have to learn. Although this sentence seems to have little practical value today, because now everyone uses the graphical interface, no one will display the information through the console to the user to see, but printing this sentence can help us to determine that the program is operating as expected, we will add this sentence in an uncertain place, See if the desired result is displayed after the run. There is another use that can help me explore what I do not know, and I will be using this method of exploration frequently later on.
What is a console? It is possible that we can occasionally see the Black DOS box, but because of the use of Eclipse, so the console is integrated into a window of the software, this window is every time we close the program window.
This statement is:

System.out.println("需要打印的内容");

We put this statement in the code, then run, see the form, press the keyboard, if there is a bunch of a display on the console, say that our keyboard event mechanism is not a problem.
Attached code

 class myoval extends Panel implements KeyListener{     Public voidPaint (Graphics g) {G.filloval ( -, -, -, -); } @Override Public voidkeytyped (KeyEvent e) {//TODO auto-generated method stub} @Override Public voidkeypressed (KeyEvent e) {//TODO auto-generated method stubSystem.out.println ("AAAAAAAA"); } @Override Public voidkeyreleased (KeyEvent e) {//TODO auto-generated method stub}

Or the same thing, practice 20 times, after the next step, the next problem is that there are so many keys on the keyboard, in the end, which Ah, not always show a bunch of a bar, notice the parameters of the received method did not? Since there are parameters to say that someone to the inside of the parameter value, who passed the value, of course, the caller, the caller is the system, then the system is passed in, usually you need information in the inside, print a try.

    publicvoidkeyPressed(KeyEvent e) {        // TODO Auto-generated method stub        System.out.println(e);    }

What is the result, is not a lot of messy results, don't worry, calm down to see, there you press the letter, but this is too irritating, so many things can not use it.
We look at this E is what type of things, of course, not keyevent, this is not the basic data type, a look at the know is an object, the first letter or uppercase, since it is the object, we take the mouse point, bounce out is we can use the method, the method name also up enough appropriate, You'll find so many ways to look at it, and it's actually regular, to get the information to start with get, to modify the object to start with set, right?

Even pupils can find a getkeychar, literal translation "Get the key character", since guessed, let's try.

    publicvoidkeyPressed(KeyEvent e) {        // TODO Auto-generated method stub        System.out.println(e.getKeyChar());    }

What do you think? After running is the button you press, and soon you will find the problem, if we use WASD to control the ball is OK, but with the arrows up and down around? You now press the arrow to see what can be printed out, is not a bunch of question marks? In fact, the arrows do not correspond to the characters, this attempt failed, we see what get method can be used, really do not try each, anyway, I think you can find getKeyCode, and can try out the number of arrows is what.

publicvoidkeyPressed(KeyEvent e) {        // TODO Auto-generated method stub        System.out.println(e.getKeyCode());    }

Left 37, top 38, right 39, next 40, it appears to be clockwise, now you can control the ball in the direction of movement.
Now I'm going to attach all the code to this

Mport Java.awt.*;import java.awt.event.*; Public  class myball {     Public Static voidMain (string[] args) {//TODO auto-generated method stubFrame W =NewFrame (); W.setsize ( -, -); Myoval MP =NewMyoval (); W.add (MP);//Register eventW.addkeylistener (MP);        Mp.addkeylistener (MP);    W.show (); }} class myoval extends Panel implements KeyListener{    intx= -;inty= -; Public voidPaint (Graphics g) {G.filloval ( -, -, -, -); } @Override Public voidkeytyped (KeyEvent e) {//TODO auto-generated method stub} @Override Public voidkeypressed (KeyEvent e) {//TODO auto-generated method stub        if(E.getkeycode () = =Panax Notoginseng) {x--; }if(E.getkeycode () = = -) {y--; }if(E.getkeycode () = = the) {x + +; }if(E.getkeycode () = = +) {y++;    } repaint (); } @Override Public voidkeyreleased (KeyEvent e) {//TODO auto-generated method stub}

Next time I'm going to use this button to listen to play a game of the alphabet, but I believe we should all have the ability to make, not only this, but also the Lightning and tank wars these classic FC games.
I'll see you here today, next time.

by Whitejavacoder

Java graphical interface How to use the keyboard to control the movement of the ball and the interface of the explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.