Java jLabel位于另一个侦听器之上

时间:2013-09-10 21:59:34

标签: java swing drag-and-drop jlabel mouse-listeners

我想阅读一个jLabel是否在另一个上面。我将jLabel1拖到jLabel2的顶部并将其放在那里并做一些事情,如果它在顶部。代码:

package javaapplication5;

import java.awt.Component;
import java.awt.Point;

public class NewJFrame extends javax.swing.JFrame {
    boolean OptionsDrag = false, OptionsDrop = false;
    private Point initialLoc;
    private Point initialLocOnScreen;
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(400, 300));
        setMinimumSize(new java.awt.Dimension(400, 300));
        getContentPane().setLayout(null);

        jLabel1.setBackground(new java.awt.Color(0, 0, 255));
        jLabel1.setOpaque(true);
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jLabel1MousePressed(evt);
        }
        public void mouseReleased(java.awt.event.MouseEvent evt) {
            jLabel1MouseReleased(evt);
        }
    });
    jLabel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            jLabel1MouseDragged(evt);
        }
    });
    getContentPane().add(jLabel1);
    jLabel1.setBounds(90, 130, 48, 48);

    jLabel2.setBackground(new java.awt.Color(0, 255, 255));
    jLabel2.setOpaque(true);
    jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jLabel2MouseEntered(evt);
        }
    });
    getContentPane().add(jLabel2);
    jLabel2.setBounds(230, 80, 48, 48);

    jLabel3.setText("showed");
    jLabel3.setVisible(false);
    getContentPane().add(jLabel3);
    jLabel3.setBounds(40, 30, 37, 20);

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

private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {                                     
    Component comp = (Component)evt.getSource();
    initialLoc = comp.getLocation();
    initialLocOnScreen = evt.getLocationOnScreen();
}                                    

private void jLabel1MouseReleased(java.awt.event.MouseEvent evt) {                                      
    Component comp = (Component)evt.getSource();
    Point locOnScreen = evt.getLocationOnScreen();

    int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
    int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
    comp.setLocation(x, y);
    OptionsDrop = true;
}                                     

private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {                                     
    Component comp = (Component)evt.getSource();
    Point locOnScreen = evt.getLocationOnScreen();

    int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
    int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
    comp.setLocation(x, y);
    OptionsDrag = true;
}                                    

private void jLabel2MouseEntered(java.awt.event.MouseEvent evt) {                                     
    if(OptionsDrag == true && OptionsDrop == true){
        jLabel3.setVisible(true);
    }
}                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {

    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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}
    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration                   
}

我可以移动jLabel1但是当它放在名为Preview_1的其他标签上时它什么也没做。 我看到,当我拖放它很好但是只有当我用鼠标进入青色块时它才有效。当蓝色框在青色而不是鼠标上方时,是否可以这样做?

1 个答案:

答案 0 :(得分:2)

  • 我首先要重命名变量,以便他们让代码自我评论。是的,这是一个简单的示例程序,但这个小小的改变可以使一切变得不同。

例如:

private javax.swing.JLabel mobileLabel;
private javax.swing.JLabel fixedLabel;
private javax.swing.JLabel notificationLabel;
  • 我不会将一个MouseListener添加到fixedLabel,因为你并不关心 鼠标 是否超过它,而是拖拉的组件是否。
  • 相反,交叉点测试应该在mobileLabel的MouseListener中。
  • 测试交集的一种方法是提取两个组件的矩形(或者如果必须循环遍历多个组件,则使用for循环,随后提取矩形),然后测试一个Rectangle是否与另一个相交。
  • 如果有重叠,我不确定是否要将mobileLabel置于fixedLabel中心。如果是这样,您可以获得固定位置的位置,并使用它来设置移动位置。
  • 另一种可能的解决方案是使用Java的拖放功能。

例如:

import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;

@SuppressWarnings("serial")
public class NewJFrame2 extends javax.swing.JFrame {
   private static final String OVERLAID = "Overlaid!";
   boolean OptionsDrag = false, OptionsDrop = false;
   private Point initialLoc;
   private Point initialLocOnScreen;

   public NewJFrame2() {
      initComponents();
   }

   private void initComponents() {
      mobileLabel = new javax.swing.JLabel("Mobile");
      mobileLabel.setForeground(Color.white);
      fixedLabel = new javax.swing.JLabel("Fixed");
      notificationLabel = new javax.swing.JLabel();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setMaximumSize(new java.awt.Dimension(400, 300));
      setMinimumSize(new java.awt.Dimension(400, 300));
      getContentPane().setLayout(null);

      mobileLabel.setBackground(new java.awt.Color(0, 0, 255));
      mobileLabel.setOpaque(true);
      mobileLabel.addMouseListener(new java.awt.event.MouseAdapter() {
         public void mousePressed(java.awt.event.MouseEvent evt) {
            jLabel1MousePressed(evt);
         }

         public void mouseReleased(java.awt.event.MouseEvent evt) {
            jLabel1MouseReleased(evt);
         }
      });
      mobileLabel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
         public void mouseDragged(java.awt.event.MouseEvent evt) {
            jLabel1MouseDragged(evt);
         }
      });
      getContentPane().add(mobileLabel);
      mobileLabel.setBounds(90, 130, 48, 48);

      fixedLabel.setBackground(new java.awt.Color(0, 255, 255));
      fixedLabel.setOpaque(true);
// !!     fixedLabel.addMouseListener(new java.awt.event.MouseAdapter() {
//         public void mouseEntered(java.awt.event.MouseEvent evt) {
//            jLabel2MouseEntered(evt);
//         }
//      });
      getContentPane().add(fixedLabel);
      fixedLabel.setBounds(230, 80, 48, 48);

      //!! notificationLabel.setText("showed");
      // !! notificationLabel.setVisible(false);
      getContentPane().add(notificationLabel);
      // notificationLabel.setBounds(40, 30, 37, 20); //!!
      notificationLabel.setLocation(40, 30);  //!! 
      notificationLabel.setSize(notificationLabel.getPreferredSize()); //!! 

      pack();
   }

   private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {
      Component comp = (Component) evt.getSource();
      initialLoc = comp.getLocation();
      initialLocOnScreen = evt.getLocationOnScreen();
   }

   private void jLabel1MouseReleased(java.awt.event.MouseEvent evt) {
      Component comp = (Component) evt.getSource();
      Point locOnScreen = evt.getLocationOnScreen();

      int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
      int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
      comp.setLocation(x, y);
      OptionsDrop = true;

      if (compIntersectsFixed(comp)) {

         // if you want to place the mobileLabel directly on top
         // of the fixedLabel
         comp.setLocation(fixedLabel.getLocation());
         repaint();
         notificationLabel.setText(OVERLAID);
         notificationLabel.setSize(notificationLabel.getPreferredSize());
      } else {
         notificationLabel.setText("");
      }
      revalidate();
      repaint();
   }

   private boolean compIntersectsFixed(Component comp) {
      Rectangle compRect = comp.getBounds();
      Rectangle fixedRect = fixedLabel.getBounds();
      if (compRect.intersects(fixedRect)) {
         return true;
      }
      return false;
   }

   private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {
      Component comp = (Component) evt.getSource();
      Point locOnScreen = evt.getLocationOnScreen();

      int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
      int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
      comp.setLocation(x, y);
      OptionsDrag = true;
   }

// !!  private void jLabel2MouseEntered(java.awt.event.MouseEvent evt) {
//      if (OptionsDrag == true && OptionsDrop == true) {
//         notificationLabel.setVisible(true);
//      }
//   }

   public static void main(String args[]) {

      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(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(
               java.util.logging.Level.SEVERE, null, ex);
      }

      java.awt.EventQueue.invokeLater(new Runnable() {
         @Override
         public void run() {
            new NewJFrame2().setVisible(true);
         }
      });
   }

   // !! name changes
   private javax.swing.JLabel mobileLabel;
   private javax.swing.JLabel fixedLabel;
   private javax.swing.JLabel notificationLabel;
}