JAVA如何在画板加分数_自学了java一段时间,做了个最低配的画板
該樓層疑似違規已被系統折疊?隱藏此樓查看此樓
源碼:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;import javax.swing.*;public class MyClass2 extends JFrame implements KeyListener{
private MyPanel pan;
int f = 0;
int[] [] location_array = new int[2] [736];
private boolean b = false;
private final int x_min = 0;
private final int y_min = 0;
private final int x_max = 620;
private final int y_max = 440;
private int x = 0;
private int y = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub 24,32
MyClass2 mc = new MyClass2();
}
public MyClass2() {
pan = new MyPanel();
this.addKeyListener(this);
this.add(pan,BorderLayout.CENTER);
this.setVisible(true);
this.setTitle("低配畫板");
this.setBounds(400,200,646,490);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
}
public void add (int x,int y) {
this.location_array[0] [f] = x;
this.location_array[1] [f] = y;
f++;
}
class MyPanel extends JPanel{
public void paint (Graphics g) {
super.paint(g);
System.out.println("paint被調用");
for (int i = 20;i < 640;i += 20) {
g.drawLine(i,0,i,480);
}
for (int i = 20;i < 480;i += 20) {
g.drawLine(0,i,640,i);
}
g.setColor(Color.red);
for (int i = 1;i < 736;i++) {
g.fillRect(location_array[0] [i],location_array[1] [i],20,20);
}
g.setColor(Color.black);
g.fillRect(x,y,20,20);
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if ((e.getKeyChar() == 'w') && (y > y_min)) {
y -= 20;
System.out.println("按鈕'up'被按下");
repaint();
}else {
if ((e.getKeyChar() == 's') && (y < y_max)) {
y += 20;
System.out.println("按鈕'down'被按下");
repaint();
}
else {
if ((e.getKeyChar() == 'a') && (x > x_min)) {
x -= 20;
System.out.println("按鈕'left'被按下");
repaint();
}
else {
if ((e.getKeyChar() == 'd') && (x < x_max)) {
x += 20;
System.out.println("按鈕'right'被按下");
repaint();
}
}
}
}
if ((e.getKeyChar() == 'W') && (y > y_min)) {
this.add(x,y);
y -= 20;
System.out.println("按鈕'up'被按下");
repaint();
}else {
if ((e.getKeyChar() == 'S') && (y < y_max)) {
this.add(x,y);
y += 20;
System.out.println("按鈕'down'被按下");
repaint();
}
else {
if ((e.getKeyChar() == 'A') && (x > x_min)) {
this.add(x,y);
x -= 20;
System.out.println("按鈕'left'被按下");
repaint();
}
else {
if ((e.getKeyChar() == 'D') && (x < x_max)) {
this.add(x,y);
x += 20;
System.out.println("按鈕'right'被按下");
repaint();
}
}
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}}
操作方法:w,a,s,d移動,摁住Shift畫。
這個畫板低配到沒有橡皮也不能改顏色
總結
以上是生活随笔為你收集整理的JAVA如何在画板加分数_自学了java一段时间,做了个最低配的画板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java同一包protect_Java基
- 下一篇: js php 中文乱码怎么解决_探讨PH