Phil3992
Phil3992

Reputation: 1055

JAVA Drag and Drop Program not running smoothly

so I will be creating a drag and drop program but before I start my main idea I have been practising my code. At the moment I simply just want to move a jlabel (that contains an image) around the screen. I have this working in a regular JAVA document, but cannot get code to work well under the netbeans design tool, (Trying to get it to work this way as I like the GUI editor).

Now the problem im having is while yes I can move the image it is far from smooth, it is very buggy jumps around quite a bit and stray away from the actual curse pretty badly. How can I fix this? I really want this code working through the design tool, below is my buggy code:

package moodrag;

public class noLag extends javax.swing.JFrame {

    int mouseX , mouseY ;
    boolean mouseD;

    public noLag() {
        initComponents();
    }    

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ball = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(0, 153, 153));    
        ball.setIcon(new                              javax.swing.ImageIcon(getClass().getResource("/moodrag/ball.png"))); // NOI18N
        ball.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                ballMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                ballMouseMoved(evt);
            }
        });    
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(68, 68, 68)
                .addComponent(ball)
                .addContainerGap(70, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(ball)
                .addContainerGap(61, Short.MAX_VALUE))
        );    
        pack();
    }// </editor-fold>                        

    private void ballMouseDragged(java.awt.event.MouseEvent evt) {                                  
       ball.setLocation(mouseX ,mouseY ); 
       mouseX = evt.getX();
       mouseY = evt.getY();
       mouseD = true;
    }                                 

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

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(noLag.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(noLag.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(noLag.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(noLag.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new noLag().setVisible(true);
            }`enter code here`
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel ball;
    // End of variables declaration                   
}

Upvotes: 0

Views: 366

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

Three problems jump out me immediatly.

  1. The container in which ball resides is under the control of a layout manager, which means that the layout manager may choose to reset the location of the component at any time
  2. The logic in ballMouseDragged seems backwards. You're setting the location of ball to the previously known location of the mouse, not it's current location
  3. The MouseListener is attached to ball. This means that mouse events will be contextual to it (that is, the 0x0 will represent the top/left corner of the component (ball))

For example:

Upvotes: 3

Related Questions