java awt-tank battle interface drawing

The most recent Java course learned about Awt basic interface programming. The teacher then came up with an experiment:
3 pieces of material and asked to complete an interface drawing.

  • Idea
    1. Use the abstract class Component to rewrite its paint(Graphics g) method and draw the picture on the Frame window.
    2. Use the static method getDefaultToolkit in the toolkit abstract class Toolkit to obtain the toolkit (a java custom object), and then call the getImage(url) method to obtain the picture. 3. Use the drawImage method in the graphics class Graphics to draw graphics.

Among them:
Graphics.drawImage(img, x, y, width, height, observer);
Description: img is the image obtained, x/y represents the absolute position in the observer, width/height represents the size information of the image, and observer represents the image The carrier (understood as Container?).

  • achieve
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Practice6_5 {
    
    
	public static void main(String[] args) {
    
    
		new MyTankFrame();
	}
}

class MyTankFrame extends Frame
{
    
    
	public MyTankFrame() {
    
    
		super("坦克大战游戏");
		this.setBounds(100,100,560,890);
		this.setBackground(Color.white);
		myWindowClose();
		this.setVisible(true);
		this.setResizable(false);
	}
	public void myWindowClose() {
    
    
		this.addWindowListener(new WindowAdapter() {
    
    
			@Override
			public void windowClosing(WindowEvent e) {
    
    
				System.exit(0);
			}
		});
	}
	@Override
	public void paint(Graphics g) {
    
    
		Image tank1 = Toolkit.getDefaultToolkit().getImage("C:\\Users\\HiWin10\\Desktop\\学习资料教材\\java\\实验6坦克素材\\p1tankD.gif");
		Image tank2 = Toolkit.getDefaultToolkit().getImage("C:\\Users\\HiWin10\\Desktop\\学习资料教材\\java\\实验6坦克素材\\p2tankU.gif");
		Image steel = Toolkit.getDefaultToolkit().getImage("C:\\Users\\HiWin10\\Desktop\\学习资料教材\\java\\实验6坦克素材\\steels.gif");
		
		// steels
		for(int i=0; i<9; i++) {
    
    
			g.drawImage(steel, i*60+10, 40, 60, 60, this);
		}
		for(int i=0; i<9; i++) {
    
    
			g.drawImage(steel, i*60+10, 820, 60, 60, this);
		}
		for(int i=0; i<12; i++) {
    
    
			g.drawImage(steel, 10, 60*i+100, 60, 60, this);
		}
		for(int i=0; i<12; i++) {
    
    
			g.drawImage(steel, 490, 60*i+100, 60, 60, this);
		}
		
		// tank1
		g.drawImage(tank1, 70, 350, 60,60,this);
		
		// tank2
		g.drawImage(tank2, 190, 410, 60,60,this);
		
	}
}


Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43341057/article/details/105335604