Recently learning swing programming, according to the teacher's teaching video learning using java.awt.*, javax.swing.*, java.awt.event.* package for a simple tank war game programming, Learning JFrame, JPanel and other containers and components of the use of Learn the various ways to draw graphics using graphics, as well as some event monitoring and processing methods.
JFrame This class is inherited in the current study, and then called Kick to show him, for example:
Public classMytankgameextendsJFrame {//Inherit JFrame .... Public Static voidMain (string[] args) {Mytankgame mtg=NewMytankgame (); } PublicMytankgame () {//Kick This. SetSize (400,300); This. Setdefaultcloseoperation (Jframe.exit_on_close);//Close, exit, prevent memory leaks This. setvisible (true); }}
The tank is using a graphics as a paintbrush to draw 2 long rectangles (as the track of a tank. You can also use 6 small rectangular connections consisting of a large rectangle instead of a better look), 1 short rectangles, 1 circles, 1 lines combined, where the rectangle uses the Fill3drect method to display the border,
for (int i = 0; i < 5; i++) { false); false ); } false ); + 4, Y +, ten, ten); G.drawline (x+10, y+1, x+10, y+10);
Then through the Repaint method to refresh the tank to achieve the movement of the tank, which involves the event of monitoring and event handling methods, can be in the class of the painting tank JPanel call KeyListener interface monitoring JFrame, register JFrame in JPanel monitoring, So JPanel can listen to the input of the keyboard, and then rewrite the KeyListener keypressed, keyreleased, and other methods, using (Type E is also keyevent) E.getkeycode () ==keyevent.vk_ ···· Be judged for further processing.
Public classMytankgameextendsJFrame {Mypanel MP=NULL; Public Static voidMain (string[] args) {Mytankgame mtg=NewMytankgame (); } PublicMytankgame () {MP=NewMypanel (); Mp.setbackground (Color.Black);//Set Background color This. Add (MP); This. Addkeylistener (MP);//Register for monitoring ····· }}classMypanelextendsJPanelImplementsKeyListener { @Override Public voidkeypressed (KeyEvent e) {//TODO auto-generated Method Stub intspeed=2; //move the tank and change the direction if((e.getkeycode () = =keyevent.vk_s)) {Ty+=Speed ; H.sety (Ty); H.setdirect (-1); }Else if(····· ){ ····· } }}
Then a free-moving tank came out.
As follows:
Learn the Java Memory Swing programming (1)