【问题标题】:Moving a JLabel Around JPanel在 JPanel 周围移动 JLabel
【发布时间】:2012-12-02 20:36:26
【问题描述】:

我有一个 JPanel,上面有 2 个以上的 JLable,我希望能够抓取一个标签,然后将其移动到 JPanel 上的不同位置。我怎样才能做到这一点?我唯一能找到的就是将标签从组件“A”移动到组件“B”,而不是在面板上移动它。

【问题讨论】:

  • 考虑使用 MouseListener 和 MouseMotionListener 并给 JPanel 一个(颤抖的)空布局。如果你玩这个,你可能会取得进步。
  • 好的,所以我让它移动了,但它移动得很奇怪。我正在使用“mouseDragged()”,其中:int y = evt.getY();this.setBounds(0, y, 198, 50); 但是当它移动时它会摇晃,并且不会移动到鼠标在面板中所在的位置。任何想法为什么?
  • 那么你没有正确实现它。考虑创建并发布一个 sscce 来证明您的问题。
  • 我知道了,我用的是鼠标在标签上的y位置,我应该一直用鼠标在面板上的y位置。
  • @HovercraftFullOfEels 从未想过您会建议使用 null 布局。我会推荐DragLayout

标签: java swing drag-and-drop jlabel


【解决方案1】:

开始玩这个:

public class ComponentDragger extends MouseAdapter {

     private Component target;

    /**
     * {@inheritDoc}
     */
    @Override
    public void mousePressed(MouseEvent e) {
        Container container = (Container) e.getComponent();
        for (Component c : container.getComponents()) {
            if (c.getBounds().contains(e.getPoint())) {
                target = c;
                break;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void mouseDragged(MouseEvent e) {
        if (target != null) {
            target.setBounds(e.getX(), e.getY(), target.getWidth(), target.getHeight());
            e.getComponent().repaint();
            }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void mouseReleased(MouseEvent e) {
        target = null;
    }

    public static void main(String[] args) {
        JLabel label = new JLabel("Drag Me");
        JPanel panel = new JPanel();
        panel.add(label);
        ComponentDragger dragger = new ComponentDragger();
        panel.addMouseListener(dragger);
        panel.addMouseMotionListener(dragger);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(1024, 768);
        f.add(panel);
        f.setVisible(true);
        panel.setLayout(null);
        f.setState(Frame.MAXIMIZED_BOTH);
    }
}

【讨论】:

    【解决方案2】:

    这是另一个示例,其中 MouseListener 和 MouseMotionListener 位于 JLabels 本身上。为此,它需要知道鼠标在屏幕上的位置与最初按下鼠标时在屏幕上的初始位置。

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Random;
    
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    
    public class MovingLabels {
       private static final int PREF_W = 800;
       private static final int PREF_H = 600;
    
       private static void createAndShowGui() {
          Random random = new Random();
          final JPanel panel = new JPanel();
    
          Color[] colors = {Color.red, Color.orange, Color.yellow, Color.green, Color.blue, Color.cyan};
          panel.setPreferredSize(new Dimension(PREF_W, PREF_H)); // sorry kleopatra
          panel.setLayout(null);
    
          MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
    
          for (int i = 0; i < colors.length; i++) {
             Color c = colors[i];
             JLabel label = new JLabel("Label " + (i + 1));
             Border outsideBorder = new LineBorder(Color.black);
             int eb = 10;
             Border insideBorder = new EmptyBorder(eb, eb, eb, eb);
             label.setBorder(BorderFactory.createCompoundBorder(outsideBorder , insideBorder));
             label.setSize(label.getPreferredSize());
             label.setBackground(c);
             label.setOpaque(true);
             int x = random.nextInt(PREF_W - 200) + 100;
             int y = random.nextInt(PREF_H - 200) + 100;
             label.setLocation(x, y);
             label.addMouseListener(myMouseAdapter);
             label.addMouseMotionListener(myMouseAdapter);
             panel.add(label);
          }
    
          JFrame frame = new JFrame("MovingLabels");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(panel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    class MyMouseAdapter extends MouseAdapter {
    
       private Point initialLoc;
       private Point initialLocOnScreen;
    
       @Override
       public void mousePressed(MouseEvent e) {
          Component comp = (Component)e.getSource();
          initialLoc = comp.getLocation();
          initialLocOnScreen = e.getLocationOnScreen();
       }
    
       @Override
       public void mouseReleased(MouseEvent e) {
          Component comp = (Component)e.getSource();
          Point locOnScreen = e.getLocationOnScreen();
    
          int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
          int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
          comp.setLocation(x, y);
       }
    
       @Override
       public void mouseDragged(MouseEvent e) {
          Component comp = (Component)e.getSource();
          Point locOnScreen = e.getLocationOnScreen();
    
          int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
          int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
          comp.setLocation(x, y);
       }
    }
    

    【讨论】:

      【解决方案3】:

      您可能会为标签本身获取它。尝试观察面板的坐标。它应该工作

      【讨论】:

        【解决方案4】:

        这是我想要的:

        public class LayerItem extends JLabel{
        
            protected int lblYPt = 0;
        
            public LayerItem(JPanel layers){
                this.addMouseListener(new MouseAdapter(){
                    @Override
                     public void mousePressed(MouseEvent evt){
                         lblMousePressed(evt);
                     }
                });
        
                this.addMouseMotionListener(new MouseAdapter(){
                    @Override
                    public void mouseDragged(MouseEvent evt){
                        lblMouseDragged(evt);
                    }
                });
            }
        
            public void lblMousePressed(MouseEvent evt){
                lblYPt = evt.getY();
            }
        
            public void lblMouseDragged(MouseEvent evt){
                Component parent = evt.getComponent().getParent();
                Point mouse = parent.getMousePosition();
                try{
                    if(mouse.y - lblYPt >= 30){
                        this.setBounds(0, mouse.y - lblYPt, 198, 50);
                    }
                }catch(Exception e){
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多