【问题标题】:how to prevent dragging the JLabel outside the boundary of JDesktopPane?如何防止将 JLabel 拖到 JDesktopPane 边界之外?
【发布时间】:2012-11-16 08:56:09
【问题描述】:

如何防止将 JLabel 拖到 JDesktopPane 的边界之外?

我做过一个应用,在JDesktopPane里面放了一个JLabel,JLabel可以拖到任何地方,但是拖的时候问题是JLabel可以拖到JDesktopPane的边界之外吗?谁能告诉我如何防止这种情况?

还有

在应用程序中,任何人都可以告诉我如何通过双击来编辑 JLabel 文本值。目前我已经通过 JOptionPane.showInputDialog() 完成了,我们可以通过双击 JLabel 的文本来编辑它并以任何其他方式而不是使用 JOptionPane 来编辑它。显示输入对话框

我的代码是这样的

import java.awt.Point;
import javax.swing.*;

public class Testing extends javax.swing.JFrame {
private int clicX = 0,clicX1 = 0;
private int clicY = 0,clicY1 = 0;
private boolean drag = false,drag1 = false;

    public Testing() {
        initComponents();
        headlabel.setVisible(false);
        footlabel.setVisible(false);
    }

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

//自动生成代码

    private void initComponents() {
            head = new javax.swing.JCheckBox();
            jDesktopPane1 = new javax.swing.JDesktopPane();
            headlabel = new javax.swing.JLabel();
            footlabel = new javax.swing.JLabel();
            foot = new javax.swing.JCheckBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            head.setText("Head");
            head.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    headActionPerformed(evt);
                }
            });       jDesktopPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background"));
            headlabel.setBackground(new java.awt.Color(255, 255, 255));
            headlabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
            headlabel.setForeground(new java.awt.Color(255, 255, 255));
            headlabel.setText("Heading");
            headlabel.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    headlabelMouseClicked(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    headlabelMousePressed(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    headlabelMouseReleased(evt);
                }
            });
            headlabel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    headlabelMouseDragged(evt);
                }
            });
            headlabel.setBounds(80, 20, 100, 20);
            jDesktopPane1.add(headlabel, javax.swing.JLayeredPane.DEFAULT_LAYER);

            footlabel.setBackground(new java.awt.Color(255, 255, 255));
            footlabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
            footlabel.setForeground(new java.awt.Color(255, 255, 255));
            footlabel.setText("Foot");
            footlabel.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    footlabelMouseClicked(evt);
                }
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    footlabelMousePressed(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    footlabelMouseReleased(evt);
                }
            });
            footlabel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    footlabelMouseDragged(evt);
                }
            });
            footlabel.setBounds(100, 280, 100, 20);
            jDesktopPane1.add(footlabel, javax.swing.JLayeredPane.DEFAULT_LAYER);

            foot.setText("Foot");
            foot.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    footActionPerformed(evt);
                }
            });

            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.LEADING)
                        .addComponent(head, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(foot, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                    .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(52, 52, 52)
                            .addComponent(head)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(foot)
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addContainerGap())
            );

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

// 函数定义

 private void headlabelMouseClicked(java.awt.event.MouseEvent evt) {                                       
            if (evt.getClickCount() == 2) {
            String str = JOptionPane.showInputDialog(null, "Enter text : ", "Enter text", 1);


             Point location = headlabel.getLocation();

             headlabel.setLocation(location);
             headlabel.setText(str);
            }

    }                                      



    private void headlabelMouseReleased(java.awt.event.MouseEvent evt) {                                        
                // drag = false;
    }                                       


    private void headlabelMousePressed(java.awt.event.MouseEvent evt) {                                       
                drag = true;
                if (evt.getSource() == headlabel) {
                }
                if (evt.getSource() == headlabel) {
                clicX = evt.getX();
                clicY = evt.getY();
                }
    }                                      


    private void headlabelMouseDragged(java.awt.event.MouseEvent evt) {                                       
                if (evt.getSource() == headlabel) {

                javax.swing.JComponent jc = (javax.swing.JComponent)evt.getSource();
                jc.setLocation(jc.getX()+evt.getX()-clicX, jc.getY()+evt.getY()-clicY);

                }
    }                                      


    private void headActionPerformed(java.awt.event.ActionEvent evt) {                                     
             if (head.isSelected()) {
                    headlabel.setVisible(true);
                } else {
                    headlabel.setVisible(false);
                }
    }                                    


    private void footlabelMouseClicked(java.awt.event.MouseEvent evt) {                                       
               if (evt.getClickCount() == 2) {
            String str = JOptionPane.showInputDialog(null, "Enter text : ", "Enter text", 1);


             Point location = footlabel.getLocation();

             footlabel.setLocation(location);
             footlabel.setText(str);
            }
    }                                      


    private void footlabelMousePressed(java.awt.event.MouseEvent evt) {                                       
                 drag1 = true;
                if (evt.getSource() == footlabel) {
                }
                if (evt.getSource() == footlabel) {
                clicX1 = evt.getX();
                clicY1 = evt.getY();
                }
    }                                      


    private void footlabelMouseReleased(java.awt.event.MouseEvent evt) {                                        
                // TODO add your handling code here:
    }                                       


    private void footlabelMouseDragged(java.awt.event.MouseEvent evt) {                                       
               if (evt.getSource() == footlabel) {

                javax.swing.JComponent jc = (javax.swing.JComponent)evt.getSource();
                jc.setLocation(jc.getX()+evt.getX()-clicX1, jc.getY()+evt.getY()-clicY1);
                }
    }                                      


    private void footActionPerformed(java.awt.event.ActionEvent evt) {                                     
               if (foot.isSelected()) {
                    footlabel.setVisible(true);
                } else {
                    footlabel.setVisible(false);
                }
    }                                    


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

                java.awt.EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        new Testing().setVisible(true);
                    }
                });
            }
            // Variables declaration - do not modify
            private javax.swing.JCheckBox foot;
            private javax.swing.JLabel footlabel;
            private javax.swing.JCheckBox head;
            private javax.swing.JLabel headlabel;
            private javax.swing.JDesktopPane jDesktopPane1;
            // End of variables declaration
        }

【问题讨论】:

    标签: java swing drag-and-drop jlabel jdesktoppane


    【解决方案1】:

    基本思想是防止组件超出其父边界。因此,在更改标签位置时,在鼠标侦听器/拖动器中,您应该验证标签的边界是否保持在标签父级的边界内。如果不是,那么您应该“修复”边界,以便标签保持在其父组件的边界内。

    这是一个示例(它不使用 JDesktopPane,但解决方案应该类似)。它缺少一些小的调整,但基本上运行良好:

    import java.awt.Component;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    
    public class TestLimitedDrag {
    
        public static class MouseDragger extends MouseAdapter {
            private Point startPoint;
            private Component draggedObject;
    
            @Override
            public void mousePressed(MouseEvent e) {
                draggedObject = (Component) e.getSource();
                startPoint = SwingUtilities.convertPoint(draggedObject, e.getPoint(), draggedObject.getParent());
            }
    
            @Override
            public void mouseDragged(MouseEvent e) {
                Point location = SwingUtilities.convertPoint(draggedObject, e.getPoint(), draggedObject.getParent());
                if (draggedObject.getParent().getBounds().contains(location)) {
                    Point newLocation = draggedObject.getLocation();
                    newLocation.translate(location.x - startPoint.x, location.y - startPoint.y);
                    newLocation.x = Math.max(newLocation.x, 0);
                    newLocation.x = Math.min(newLocation.x, draggedObject.getParent().getWidth() - draggedObject.getWidth());
                    newLocation.y = Math.max(newLocation.y, 0);
                    newLocation.y = Math.min(newLocation.y, draggedObject.getParent().getHeight() - draggedObject.getHeight());
                    draggedObject.setLocation(newLocation);
                    startPoint = location;
                }
            }
    
            @Override
            public void mouseReleased(MouseEvent e) {
                startPoint = null;
                draggedObject = null;
            }
    
            public void makeDraggable(Component component) {
                component.addMouseListener(this);
                component.addMouseMotionListener(this);
            }
    
        }
    
        private void initUI() {
            JFrame frame = new JFrame(TestLimitedDrag.class.getSimpleName());
            frame.setLayout(null);
            MouseDragger dragger = new MouseDragger();
            JLabel labelToDrag = new JLabel("Drag me");
            dragger.makeDraggable(labelToDrag);
            frame.add(labelToDrag);
            labelToDrag.setSize(labelToDrag.getPreferredSize());
            labelToDrag.setLocation(50, 50);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new TestLimitedDrag().initUI();
                }
            });
        }
    
    }
    

    【讨论】:

    • @NidhinKrishnan 完全相同的方式。我不使用 JDesktopPane 的事实并没有改变任何东西。 JDesktopPane 和我的示例都使用绝对布局。其余代码是纯包含逻辑,即,它确保标签不会超出其父组件的范围。父组件是 JDesktopPane 还是简单的 JPanel(或事实上的任何其他 Container)并不重要
    • @NidhinKrishnan 代码中最重要的部分在我的mouseDragged 方法中,在调用setLocation 之前。您应该在 headlabelMouseDragged 中使用类似的内容。
    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多