在上篇文章中简单的介绍了下所要用到的基本知识,现在根据那些基本知识开始制作小游戏。
首先,创建游戏发生的地点——在屏幕上创建一个欢迎窗口,并且在一定时间之后,跳转到游戏窗口(海洋世界)。
欢迎界面的主要代码为:WelcomeWindow.java
package my.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.border.LineBorder;
public class WelcomeWindow extends JWindow{
//设置窗口的形状
int width=643;
int height=433;
//构造方法,在被创建的时候初始化
public WelcomeWindow() throws Exception{
init();
}
//初始化时所执行的方法
private void init() throws Exception{
setSize(width, height);
JPanel pane = new JPanel(new BorderLayout());
//一个 Icon 接口的实现,它根据 Image 绘制 Icon。
ImageIcon ico = new ImageIcon(
getClass().getResource("welcome.jpg")
);
JLabel l = new JLabel(ico);
//在窗格上加上具体的东西
pane.add(BorderLayout.CENTER, l);
//设置边框
pane.setBorder(new LineBorder(Color.GRAY));
setContentPane(pane);
center();
}
public void center(){
//获取默认包
Toolkit toolkit=Toolkit.getDefaultToolkit();
//获取屏幕大小
Dimension screen=toolkit.getScreenSize();
//将屏幕的大小赋值给一个变量
int screen_x=screen.width;
int screen_y=screen.height;
//计算窗口x,y的位置
int location_x=(screen_x-width)/2;
int location_y=(screen_y-height)/2;
//设置窗口的位置
this.setLocation(location_x, location_y);
}
}
另一个游戏窗口设置为:
package my.ui;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
/*
* 描述捕鱼达人的窗体界面
*/
public class FishFrame extends JFrame{
int width=800;
int height=490;
public FishFrame(){
//设置标题
this.setTitle("捕鱼达人");
//设置大小
this.setSize(width,height);
//设置出错的处理
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//不设置自动调整大小
this.setResizable(false);
center();
}
public void center(){
//获取默认包
Toolkit toolkit=Toolkit.getDefaultToolkit();
//获取屏幕大小
Dimension screen=toolkit.getScreenSize();
//将屏幕的大小赋值给一个变量
int screen_x=screen.width;
int screen_y=screen.height;
//计算窗口x,y的位置
int location_x=(screen_x-width)/2;
int location_y=(screen_y-height)/2;
//设置窗口的位置
this.setLocation(location_x, location_y);
}
}
这样所要用到的两个窗口就建好了。