今日內容:2D animations、Anonymous Inner Class
學習如何用昨天學到的2D graphics功能以及簡單的判斷進行動態的畫面變化
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyPanel extends JPanel implements ActionListener{
static final int PANEL_WIDTH = 500;
static final int PANEL_HEIGHT = 500;
Image enemy;
Image backgroundImage;
Timer timer;
int xVelocity = 1;
int yVelocity = 1;
int x = 0;
int y = 0;
MyPanel() {
this.setPreferredSize(new Dimension(500, 500));
this.setBackground(Color.lightGray); // if backgroundImage not available
enemy = new ImageIcon("ironman.png").getImage();
backgroundImage = new ImageIcon("background.png").getImage();
timer = new Timer(10, this); // 每10毫秒執行actionPerformed動作
timer.start();
}
public void paint(Graphics g){
super.paint(g); // 進行預設的繪製動作
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(backgroundImage, 0, 0, null);
g2d.drawImage(enemy, x, y, null);
}
@Override
public void actionPerformed(ActionEvent e) {
if(x >= PANEL_WIDTH-enemy.getWidth(null) || x < 0){
xVelocity *= -1;
}
if(y >= PANEL_HEIGHT-enemy.getHeight(null) || y < 0){
yVelocity *= -1;
}
x += xVelocity;
y += yVelocity;
repaint(); // using repaint instead of calling paint
}
}
在class中建立無名的inner class,用於action listener的效果很好
public class Greeting {
public void Welcome(){
System.out.println("Hello World!");
}
}
public class Main {
public static void main(String[] args){
Greeting greeting = new Greeting();
Greeting greeting2 = new Greeting(){
@Override
public void Welcome(){
System.out.println("Yo Bro!");
}
};
greeting.Welcome();
greeting2.Welcome();
}
}
接下來是實作練習
設置三個不同的按鈕,各自有不同的功能
不再implements ActionListener,而是在addActionListener中獨立創建
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame{
JButton button1 = new JButton("Button #1");
JButton button2 = new JButton("Button #2");
JButton button3 = new JButton("Button #3");
MyFrame(){
button1.setBounds(100, 100, 100, 100);
button2.setBounds(200, 100, 100, 100);
button3.setBounds(300, 100, 100, 100);
button1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("You Pressed Button #1");
}
});
button2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println("You Pressed Button #2");
}
});
button3.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println("You Pressed Button #3");
}
});
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.add(button1);
this.add(button2);
this.add(button3);
this.setLayout(null);
this.setVisible(true);
}
}
今天是學習Java GUI的最後一天,明天就要正式進入開發遊戲的階段了,我目前的想法是將目標分為開發與優化兩個部分,開發大約可以花三天完成,而優化則是依據完成後缺什麼就新增什麼,不會讓自己有時間壓力。
今天也是快樂學習的一天,明天繼續!