- import javax.swing.JFrame;
- import javax.swing.JButton;
- import javax.swing.ImageIcon;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.ActionEvent;
- public class main {
-
- private JFrame fm;
- private JButton b[]=new JButton[12];
- private JButton b_r;
- private ImageIcon mm[]=new ImageIcon[12];
- private ImageIcon ic,mm_r,mm_b;
- private int rc[]=new int[12];
- main()
- {
- rc();
- ic=new ImageIcon(main.class.getResource("star.png"));
- mm_b=new ImageIcon(main.class.getResource("0.png"));
- mm_r=new ImageIcon(main.class.getResource("return.png"));
-
- for(int i=0; i<6; i++)
- {
- mm[i]=new ImageIcon(main.class.getResource((i+1)+".png"));
- mm[i+6]=new ImageIcon(main.class.getResource((i+1)+".png"));
- }
-
- for(int i=0; i<12; i++)
- b[i]=new JButton(mm_b);
- for(int i=0; i<4; i++)
- b[ i ].setBounds(i*130+12, 10, 128, 128);
- for(int i=0; i<4; i++)
- b[ i+4 ].setBounds(i*130+12, 140, 128, 128);
- for(int i=0; i<4; i++)
- b[ i+8 ].setBounds(i*130+12, 270, 128, 128);
- for(int i=0; i<12; i++)
- b[i].addMouseListener(ma);
-
- b_r=new JButton(mm_r);
- b_r.setBounds(497, 407, 33, 33);
- b_r.addActionListener(al);
-
- fm=new JFrame("翻牌遊戲");
- fm.setBounds(100, 100, 548, 480);
- fm.setIconImage(ic.getImage());
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- for(int i=0; i<12; i++)
- fm.add(b[i]);
- fm.add(b_r);
- }
-
- void rc()
- {
- for(int i=0; i<12; i++)
- {
- rc[i]=(int)(Math.random()*12); //0~11
- for(int j=0; j<i; j++)
- {
- if(rc[i]==rc[j])
- {
- i--;
- break;
- }
- }
- }
- }
-
- MouseAdapter ma=new MouseAdapter(){
- public void mousePressed(MouseEvent e)
- {
- for(int i=0; i<12; i++)
- {
- if(e.getSource()==b[i])
- b[i].setIcon(mm[rc[i]]);
- }
- }
- };
-
- ActionListener al=new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==b_r)
- {
- rc();
- for(int i=0; i<12; i++)
- b[i].setIcon(mm_b);
- }
- }
- };
- public static void main(String[] args) {
- new main();
- }
- }
複製代碼 |