📄 chessboard.java
字号:
package day19.fivechess;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
/**
* 棋盘类,用来绘制棋盘
* @author Administrator
*
*/
public class ChessBoard extends JFrame implements ActionListener{
private GraphicPanel panel;
private JMenuBar bar;//菜单条
private JMenu game;//游戏菜单
public static JLabel label;//状态栏
public static final int DEFAULT_WIDTH=650;//棋盘宽度
public static final int DEFAULT_HEIGHT=700;//棋盘高度
public ChessBoard(){
super("五子棋 v1.1");
label=new JLabel(" ",JLabel.CENTER);
panel=new GraphicPanel();
this.add(panel,BorderLayout.CENTER);
this.add(label,BorderLayout.SOUTH);
bar=new JMenuBar();
game=new JMenu("游戏");
JMenuItem item=null;
game.add(item=new JMenuItem("重新开始")); item.addActionListener(this);
game.add(item=new JMenuItem("保存游戏...")); item.addActionListener(this);
game.add(item=new JMenuItem("装载游戏...")); item.addActionListener(this);
game.addSeparator();
game.add(item=new JMenuItem("退出")); item.addActionListener(this);
bar.add(game);
this.setJMenuBar(bar);
}
public void showMe(){
this.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("保存游戏...")){
//1,弹出保存文件对话框
JFileChooser jfc=new JFileChooser();
jfc.showSaveDialog(this);
// 2,获得用户选择的文件
File f=jfc.getSelectedFile();
// 3,调用
if(f!=null){
if(panel.saveToFile(f)){
JOptionPane.showMessageDialog(this,"保存成功!");
}else{
JOptionPane.showMessageDialog(this,"保存文件失败!");
}
}
return;
}
if(e.getActionCommand().equals("装载游戏...")){
//1,弹出打开文件对话框
JFileChooser jfc=new JFileChooser();
jfc.showOpenDialog(this);
//2,获得用户选择的文件
File f=jfc.getSelectedFile();
// 3,调用
if(f!=null){
if(!panel.loadFromFile(f)){
JOptionPane.showMessageDialog(this,"文件格式不正确或已损坏!");
}
}
return;
}
if(e.getActionCommand().equals("重新开始")){
panel.clear();
}
if(e.getActionCommand().equals("退出")){
System.exit(0);
}
}
public static void main(String[] args){
new ChessBoard().showMe();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -