转载请标明出处:http://blog.csdn.net/idealism_xxm/article/details/50279075,本文出自: 【idealism_xxm的博客】
虽然C++都学过,但是 Introduction to Java Programming 前十一章基本都认真看过了,还做了少部分题...
虽然只学了各种基本组件,但是终于可以编界面程序了。
自己查了一下设置监听的方法,做了一个简易版井字棋,由于只为熟悉各种用法,所以电脑采取随机下子
图片是截取pdf的...
import java.awt.*; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import javax.swing.*; public class Tic_tac_toe extends JFrame{ JLabel[] jlb=new JLabel[9]; int clicked=0,i; ImageIcon x=new ImageIcon("x.png"); ImageIcon o=new ImageIcon("o.png"); public Tic_tac_toe() { setSize(67*3+15,67*3+15); setLayout(new GridLayout(3,3,5,5)); for(i=0;i<9;++i) { jlb[i]=new JLabel(); jlb[i].addMouseListener(new MouseListener() {//【注意】必须重写所有的5个函数 int id=i;//【注意】数组对象用循环设置监听时应这样使用,若用i则会使在该类中,只对jlb[9]起作用,即只获取当前i的值 @Override public void mouseClicked(MouseEvent e) { if(jlb[id].getIcon()==null) {//判断下棋子地方是否合法 jlb[id].setIcon(x); if(Judge()) { JOptionPane.showMessageDialog(null,"You win!", "Congratulation", JOptionPane.PLAIN_MESSAGE, null); init(); } else { if(++clicked==5) { JOptionPane.showMessageDialog(null,"Please try again!", "Draw", JOptionPane.PLAIN_MESSAGE, null); init(); } else {//电脑随机下 int index=((int)(Math.random()*9))%9; while(jlb[index].getIcon()!=null) index=((int)(Math.random()*9))%9; jlb[index].setIcon(o); if(Judge()) { JOptionPane.showMessageDialog(null,"You lose!", "What a pity", JOptionPane.PLAIN_MESSAGE, null); init(); } } } } else JOptionPane.showMessageDialog(null,"Please select another!", "Illegal", JOptionPane.INFORMATION_MESSAGE, null); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); add(jlb[i]); } setResizable(false); setLocationRelativeTo(null); setVisible(true); } boolean Judge() {//判断当前局面是否有人赢 if( (jlb[0].getIcon()!=null&&jlb[0].getIcon()==jlb[4].getIcon()&&jlb[0].getIcon()==jlb[8].getIcon())|| (jlb[0].getIcon()!=null&&jlb[0].getIcon()==jlb[1].getIcon()&&jlb[0].getIcon()==jlb[2].getIcon())|| (jlb[0].getIcon()!=null&&jlb[0].getIcon()==jlb[3].getIcon()&&jlb[0].getIcon()==jlb[6].getIcon())|| (jlb[1].getIcon()!=null&&jlb[1].getIcon()==jlb[4].getIcon()&&jlb[1].getIcon()==jlb[7].getIcon())|| (jlb[2].getIcon()!=null&&jlb[2].getIcon()==jlb[5].getIcon()&&jlb[2].getIcon()==jlb[8].getIcon())|| (jlb[2].getIcon()!=null&&jlb[2].getIcon()==jlb[4].getIcon()&&jlb[2].getIcon()==jlb[6].getIcon())|| (jlb[3].getIcon()!=null&&jlb[3].getIcon()==jlb[4].getIcon()&&jlb[3].getIcon()==jlb[5].getIcon())|| (jlb[6].getIcon()!=null&&jlb[6].getIcon()==jlb[7].getIcon()&&jlb[6].getIcon()==jlb[8].getIcon())) return true; return false; } void init() { clicked=0; for(int j=0;j<9;++j) jlb[j].setIcon(null); } public static void main(String[] argv) { new Tic_tac_toe(); } }