2015年5月8日 星期五

3*3 9宮格顯示對的數字
import java.awt.*;
import java.awt.event.*;

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;
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 = 1; 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(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<button.length; i++){
if(e.getSource() == button[i]){    
         
            System.out.println(i);
        }
    }
}
}


=======================================================================
亂數  4*4 不重複
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame{
public static void main(String[]args){



Random random = new Random();

int number = 0;;
int array[] = new int[16];
boolean b;

for(int i=0;i<16;i++)
{
b = true;
while(b) {
b = false;
number = random.nextInt(16)+1;
for(int j=0;j<array.length;j++) {
if(array[j]==number) {
b = true;
}
}
}
array[i] = number;
System.out.printf("array[%d]=%d\n",i,number);
}




JFrame window=new JFrame("myButton");
window.setSize(450, 150);
JButton button[]=new JButton[16];
JPanel jplPanel = new JPanel();
jplPanel.setLayout(new GridLayout(4,4,8,8));

for (int i = 0; i < 16; i++){
//button[i]=new JButton(""+array[16]);
button[i] = new JButton();
button[i].setSize(40,40);
button[i].setText(Integer.toString(array[i]));
button[i].addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int j = 0; j < 16; j++) {
if (e.getSource() == button[j]) {
System.out.println(j+1);
}
}
}

沒有留言:

張貼留言