鏈接:程式設計工藝大師
button上顯示的數字為亂數,點擊交換位置
程式代碼:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Calculator extends JFrame implements
ActionListener{
JButton button[]=new JButton[10];
public static void main(String[]args)
{
new Calculator();
}
public Calculator()
{
String s;
int myrand;
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] aresult;
int temp;
Random ran = new Random();
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]);
}
window.getContentPane().add(jplPanel, BorderLayout.CENTER);
window.setSize(500,500);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
for(int i=1; i <= 9; i++)
{
if(e.getSource() == button[i])
{
if (button[i-3].equals(1))
{
button[i+1].setText(Integer.toString(i));
button[i].setText(Integer.toString(1));
System.out.println(i);
}
if (button[i-1].equals(1))
{
button[i+1].setText(Integer.toString(i));
button[i].setText(Integer.toString(1));
System.out.println(i);
}
if (button[i+1].equals(1))
{
button[i+1].setText(Integer.toString(i));
button[i].setText(Integer.toString(1));
System.out.println(i);
}
if (button[i+3].equals(1))
{
button[i+1].setText(Integer.toString(i));
button[i].setText(Integer.toString(1));
System.out.println(i);
}
}
}
}
}