ลองทำรูปเคลื่อนไหวโดยการใช้โค๊ด java กัน

YouTube Preview Image

เป็นไงบ้างละครับดูว่ามันสวยและน่าทำมากเลยใช่ไหม งั้นเราลองมาดูส่วนของโค๊ดกัน

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
*
* @author Administrator
*/
public class NeedForSpeed extends JFrame{
public NeedForSpeed(){
add(new RacaCar());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
NeedForSpeed frame = new NeedForSpeed();
frame.setTitle(“Need For Speed”);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
frame.setVisible(true);
}
class RacaCar extends JPanel implements ActionListener{
private int xBase = 20;
public RacaCar(){
Timer timer = new Timer (15, this);
timer.start();

}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int yBase = getHeight();
if (xBase > getWidth())
xBase = 20;
else
xBase +=2;
g.setColor(Color.RED);

g.setColor(Color.BLUE);
g.fillRect(xBase, yBase -120, 50, 10);
g.setColor(Color.RED);
Polygon polygon = new Polygon();
polygon.addPoint(xBase +10, yBase -120);
polygon.addPoint(xBase +20, yBase -130);
polygon.addPoint(xBase +30, yBase -130);
polygon.addPoint(xBase +40, yBase -120);
g.fillPolygon(polygon);}
}
}

ถ้าเราเข้าใจโค๊ดแล้วเราสามารถเปลี่ยนโค๊ดเพื่อให้มันแสดงเป็นรูปอื่นสีอื่นหรือความเร็วได้นะครับ

มาดูการรันโปรแกรมบ้าง

2

1

3

4

รายชื่อสมาชิก

นายเรวัตร ยั่งยืน 1570900611

นายศักดิติ จอนกิ่ง 1570900629

นายชาคริต เคร่งธรรมกิจ  1570901411

Chakit crengtummakit
at GlurGeek.Com
ผมชื่อบองครับ

Leave a Reply

© 2022 GlurGeek.Com