黑马程序员技术交流社区
标题:
现在我想要在mouseClicked()方法里写一段代码,操作过程像是数字拼图的小游戏
[打印本页]
作者:
@♂№‰腊布啊に
时间:
2013-1-17 23:57
标题:
现在我想要在mouseClicked()方法里写一段代码,操作过程像是数字拼图的小游戏
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SlidingPuzzle extends JFrame implements MouseListener
{
public static void main(String[] args){
SlidingPuzzle frame=new SlidingPuzzle();
frame.TestPanel();
frame.setTitle("Numeric Sliding Puzzle");
frame.setSize(400,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void TestPanel(){
Container container=getContentPane();
container.setLayout(new GridLayout(3,3,5,5));
PuzzleTile[] listenerPanel;
listenerPanel=new PuzzleTile[9];
int[] myList=new int[9];
outer:
for(int i=0;i<=8;i++){
int j=(int)(Math.random()*9);
myList[i]=j;
if(null == listenerPanel[j]){
listenerPanel[j] = new PuzzleTile(j);
}
if(i==0)
{
container.add(listenerPanel[j]);
listenerPanel[j].addMouseListener(this);
}
else{
for(int k=0;k<i;){
if(myList[k]==myList[i]){
i--;
continue outer;
}
k++;
if(k==i)
{
container.add(listenerPanel[j]);
listenerPanel[j].addMouseListener(this);
}
}
}
}
}
public void mousePressed(MouseEvent e){
PuzzleTile pt = (PuzzleTile) e.getSource();
if (pt.getBackground().equals(Color.white)) {
return;
}
pt.setBackground(Color.LIGHT_GRAY);
}
public void mouseReleased(MouseEvent e){
PuzzleTile pt = (PuzzleTile) e.getSource();
if (pt.getBackground().equals(Color.white)) {
return;
}
pt.setBackground(Color.DARK_GRAY);
}
public void mouseClicked(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
}
public class PuzzleTile extends JPanel {
private String tileNumber;
public PuzzleTile(int number) {
super();
if (number == 0) {
this.setBackground(Color.white);
}
else {
this.setBackground(Color.darkGray);
}
this.tileNumber = "" + number;
}
public void paintComponent(Graphics graphics) {
Font a=new Font("Arial",Font.BOLD,30);
graphics.setFont(a);
graphics.setColor(Color.white);
super.paintComponent(graphics);
FontMetrics b=graphics.getFontMetrics(a);
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2