0
回答
用java做一个图片在窗口中移动的程序
百度AI开发者大赛带你边学边开发,赢100万奖金,加群:418589053   

刚刚学习了“基于Swing的图形化用户界面”看了老师做的打地鼠程序,然后想自己做一个类似的但是没一次成功了,想请教一下高手。

开始窗口就一开始按钮和两张图片,鼠标单击后图片开始移动,若两张图遇上,则显示失败!程序结束。若移动三次都未遇上,则显示成功。

程序要求使用内部类,刚刚开始学java 很多都不懂,请大神尽量用简单明了的语句,如果可以请边上注释,非常感谢!

这是我们老师做的!

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 * BeatMouse.java
 *
 * Created on 2010-11-24, 8:50:41
 */
package jkx;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
 *
 * @author Administrator
 */
public class BeatMouse extends javax.swing.JFrame {
  int count ;
    /** Creates new form BeatMouse */
    public BeatMouse() {
        initComponents();
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BeatMouse.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(BeatMouse.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(BeatMouse.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(BeatMouse.class.getName()).log(Level.SEVERE, null, ex);
        }
        SwingUtilities.updateComponentTreeUI(this);
    }
    private void endGame() throws HeadlessException {
        timer.cancel();
        endTimer.cancel();
        String message = "";
        if (count > 500) {
            message = "反应很快嘛";
        } else {
            message = "反应要快一些哟!";
        }
        JOptionPane.showMessageDialog(this, message);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        imgLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        scoreLable = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        surplusTimeLable = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jPanel1.setLayout(null);
        imgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/1.jpg"))); // NOI18N
        imgLabel.setText("jLabel1");
        imgLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                imgLabelMouseClicked(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                imgLabelMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                imgLabelMousePressed(evt);
            }
        });
        jPanel1.add(imgLabel);
        imgLabel.setBounds(99, 58, 60, 60);
        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);
        jButton2.setText("End");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);


        jLabel2.setText("得分:");
        jPanel3.add(jLabel2);
        scoreLable.setText("0");
        jPanel3.add(scoreLable);
        jLabel3.setText("  ");
        jPanel3.add(jLabel3);

        jLabel1.setText("时间剩余:");
        jPanel3.add(jLabel1);


        surplusTimeLable.setText("30");
        jPanel3.add(surplusTimeLable);


        jLabel4.setText("秒");
        jPanel3.add(jLabel4);


        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );


        pack();
    }// </editor-fold>                        


    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        gameStart();
    }                                        


    private void imgLabelMouseClicked(java.awt.event.MouseEvent evt) {                                      
   
    }                                     


    private void imgLabelMousePressed(java.awt.event.MouseEvent evt) {                                      
        count+=50;
      scoreLable.setText(count+"");
      // imgLabel.setIcon(new ImageIcon(BeatMouse.class.getResource("images/2.jpg")));
        imgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/2.jpg"))); 
    }                                     


    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        endGame();
    }                                        


    private void imgLabelMouseExited(java.awt.event.MouseEvent evt) {                                     
       imgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/1.jpg")));
    }                                    


    Timer endTimer;
    Timer timer ;
    class ImageLocation extends TimerTask{


        @Override
        public void run() {
            Dimension d =randLocation(jPanel1.getSize());
           imgLabel.setLocation(d.width,d.height);


        }


    }
    class EndGame extends TimerTask{
        int n=30;
        @Override
        public void run() {
            n--;
            surplusTimeLable.setText(""+n);
            if (n ==0) {
                endTimer.cancel();
                timer.cancel();
               JOptionPane.showMessageDialog(null, "时间到了!");
               endGame();
            }
        }


    }
    private void gameStart(){
        timer =new Timer();
        endTimer=new Timer();
        timer.schedule(new ImageLocation(), 500,500);




        endTimer.schedule(new EndGame(), 1000, 1000);
        scoreLable.setText("0");
        surplusTimeLable.setText("30");


    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BeatMouse().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify                     
    private javax.swing.JLabel imgLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JLabel scoreLable;
    private javax.swing.JLabel surplusTimeLable;
    // End of variables declaration                   


    private Dimension randLocation(Dimension d) {
        Dimension d1=new Dimension();




       int  x1=(int)(Math.random()*(d.getWidth()-50));
       int  y1=(int)(Math.random()*(d.getHeight()-50));
       d1.setSize(x1, y1);
        return d1;
    }


}




举报
unravelling
发帖于3年前 0回/2K+阅
顶部