用java做的一个小游戏—黑白反斗棋(适合菜鸟)
2011-12-28 22:06
375 查看
用Java做的一个小游戏,黑白反斗棋,我玩过了5*5和10*10的。是学习之后做的,不是自己原始开发的。
import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class MainFrame extends JFrame implements ActionListener{ JButton[][] bus=new JButton[10][10]; //构造方法,方法名必须和类名一致,作用就是创建对象 public MainFrame(){ //网格布局 String path=MainFrame.class.getClassLoader().getResource("haha.jpg").getPath(); ImageIcon icon=new ImageIcon(path); setIconImage(icon.getImage()); GridLayout g=new GridLayout(10,10); getContentPane().setLayout(g); setTitle("黑白翻斗棋"); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { JButton bu=new JButton(); //给按钮注册上点击事件 bu.addActionListener(this); bu.setActionCommand(i+","+j); bu.setSize(50, 50); bu.setBackground(Color.WHITE); bus[i][j]=bu; add(bu); } } //得到显示器的宽和高 int x=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); int y=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); setLocation((x-500)/2,(y-500)/2); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { MainFrame m=new MainFrame(); m.setSize(500, 500); m.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { JButton bu=(JButton)e.getSource(); //System.out.println(bu.getActionCommand()); ChengebgColor(bu); String actioncommand=bu.getActionCommand(); String[] command=actioncommand.split(","); // for (int i = 0; i < command.length; i++) { // System.out.println(command[i]); // } int x=Integer.parseInt(command[0]); int y=Integer.parseInt(command[1]); if(x-1>=0){ ChengebgColor(bus[x-1][y]); } if(x+1<10){ ChengebgColor(bus[x+1][y]); } if(y-1>=0){ ChengebgColor(bus[x][y-1]); } if(y+1<10){ ChengebgColor(bus[x][y+1]); } } public void ChengebgColor(JButton bu){ if(bu.getBackground()==Color.WHITE){ bu.setBackground(Color.BLACK); }else{ bu.setBackground(Color.WHITE); } } }
相关文章推荐
- 一个java菜鸟工作两年的总结
- 一个菜鸟对 java 类和对象的理解
- 使用Java写一个猜数字小游戏
- 一个适合初学者看的java开发环境搭建
- 【菜鸟学Java】3:封装一个分页类PageBean
- 分享一个自己写的适合初学者的类似乒乓球的小游戏
- 一个菜鸟java码农的成长之路(4):用LinkedList模拟栈结构
- 高手对菜鸟谈对Java一个全新的了解
- 关于一个菜鸟的视角--用哈利波特世界的视角看Java语言
- node.js做的一个简单爬虫,适合菜鸟级新手,针对无防爬措施的网站
- 我的第一篇博客,作为一个Java新菜鸟,或许我的问题会很多,但是这不是我退缩的理由。
- 一个菜鸟java码农的成长之路(3):ListIterator的使用及注意的问题
- 菜鸟从零学编程(七)——搭建一个完整的Java开发环境
- 求大神帮忙完善一个java小游戏,急急急!!!!
- NetBeans IDE可视化java编程菜鸟笔记--用NetBeans创建一个Hello World项目
- Java获取随机数的3种方法和总结(正在做一个小游戏 用到了 想总结一下 保存了 以后自己看)
- java中操作mysql数据库(适合菜鸟入门看的)
- 一个菜鸟学习Java 坚持有一个月了 请大佬们多多给晚辈一些建议
- 一个Java菜鸟程序员的《2010年读书总结》
- 【求助】一个菜鸟java作业,帮忙看一下错在哪儿,题目是判断回文数