刚刚到Java GUI版报告,给大家贴一个我写的五子棋程序。这里重点是关注Java GUI的设计,所以程序只能人和人走(就是没有智能:),不过大家可以看看,做个参考:
/* * filename: Game.java * * author: jellen * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.geom.*; import java.util.*;
class PaintPanel extends JPanel { ArrayList Items = new ArrayList();
public PaintPanel() { setLayout(new BorderLayout()); ButtonPanel buttonPanel = new ButtonPanel(); add(buttonPanel, BorderLayout.SOUTH); addMouseListener(new MouseHandler()); }
public void paintComponent(Graphics g) { int startX = 50; int startY = 50; boolean isMy = false; super.paintComponent(g); Graphics2D g2 = (Graphics2D)g;
for(int i=0; i<16; i++) { g2.draw(new Line2D.Double(startX, startY+20*i, startX+300, startY+20*i)); g2.draw(new Line2D.Double(startX+20*i, startY, startX+20*i, startY+300)); } for(int i=0; i<Items.size(); i++) { isMy = !isMy; if(isMy) g2.setColor(Color.BLACK); else g2.setColor(Color.WHITE); g2.fill((Ellipse2D)Items.get(i)); } } void myRepaint() { repaint(); } private class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); paintItem(x, y); repaint(); } void paintItem(int x, int y) { if(x > 50 && x < 350 && y >50 && y < 350) { int X = x / 20; int Y = y / 20; int centerX = X*20 + 10; int centerY = Y*20 + 10; Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrameFromCenter(centerX, centerY, centerX+8, centerY+8); Items.add(ellipse); } } } private class ButtonPanel extends JPanel { public ButtonPanel() { JButton reset = new JButton(\"Reset\"); add(reset); JButton quit = new JButton(\"Quit\"); add(quit);
ResetEvent listenerR = new ResetEvent(); reset.addMouseListener(listenerR); QuitEvent listenerQ = new QuitEvent(); quit.addMouseListener(listenerQ); }
private class QuitEvent extends MouseAdapter { public void mouseClicked(MouseEvent event) { System.exit(1); } }
private class ResetEvent extends MouseAdapter { public void mouseClicked(MouseEvent event) { Items.clear(); myRepaint(); } } } }
class GameFrame extends JFrame { public GameFrame() { setTitle(\"A Little Game\"); setSize(400, 500); setResizable(false);
PaintPanel panel = new PaintPanel(); getContentPane().add(panel); } } public class Game { public static void main(String[] args) { GameFrame frame = new GameFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } }