import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Calculator extends JFrame implements
ActionListener{
int space;
JButton button[]=new JButton[10];
public static void main(String[]args){
new Calculator();
}
public Calculator()
{
String s;
int myrand;
int[] a = { 0,1, 2, 3, 4, 5, 6, 7, 8 };
int[] aresult;
int temp;
Random ran = new Random();
/*
for (int i = 0; i < 9; i++)
{
System.out.println(a[i]);
}
*/
for (int i = 0; i < 9; i++)
{
myrand=ran.nextInt(9-i);
temp=a[8-i];
a[8-i]=a[myrand];
a[myrand]=temp;
}
for (int i = 0; i < 9; i++)
{
System.out.println(a[i]);
}
JFrame window=new JFrame("Calculator");
window.setDefaultLookAndFeelDecorated(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(3,3));
JPanel jplPanel = new JPanel();
jplPanel.setLayout(new GridLayout(3,3));
//s=Integer.toString(1);
s=String.valueOf(1);
//System.out.println(s);
//s="1";
for (int i = 0; i < 9; i++)
{
button[i] = new JButton();
button[i].setActionCommand(s);
button[i].addActionListener(this);
button[i].setSize(50,50);
button[i].setText(Integer.toString(a[i]));
jplPanel.add(button[i]);
if(Integer.valueOf(button[i].getText())==0)
{
space=i;
System.out.println(i);
}
}
window.getContentPane().add(jplPanel, BorderLayout.CENTER);
window.setSize(500,500);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
for(int i=0; i <= 8; i++)
{
if(e.getSource() == button[i]){
String tempstring;
if(i==space-1)
{
tempstring=button[i].getText();
button[i].setText(button[i+1].getText());
button[i+1].setText(tempstring);
System.out.println(i+button[i].getText());
}
if(i==space+1)
{
tempstring=button[i].getText();
button[i].setText(button[i-1].getText());
button[i-1].setText(tempstring);
System.out.println(i+button[i].getText());
}
if(i==space-3)
{
tempstring=button[i].getText();
button[i].setText(button[i+3].getText());
button[i+3].setText(tempstring);
System.out.println(i+button[i].getText());
}
if(i==space+3)
{
tempstring=button[i].getText();
button[i].setText(button[i-3].getText());
button[i-3].setText(tempstring);
System.out.println(i+button[i].getText());
}
}
}
}
}
沒有留言:
張貼留言