Question

how to prevent dragging the JLabel outside the boundary of JDesktopPane?

i've done an application, in which there is a JLabel placed in JDesktopPane,JLabel can be dragged to any place,but while dragging the problem is that the JLabel can be dragged outside the boundary of the JDesktopPane? can anyone tell me how to prevent that?

and also

in the application can anyone tell me how to edit the JLabel text value by double clicking it. At present i've done that through by JOptionPane.showInputDialog(), can we edit the text of the JLabel just by double clicking it and edit it in any other way not by using JOptionPane.showInputDialog

My code is this

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">

//AUTOMATED 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>

// FUNCTION DEFINITION

 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
        }
Was it helpful?

Solution

The basic idea is to prevent a component from going out of its parent bounds. So in your mouse listener/dragger when changing the location of your label, you should verify that the bounds of the label remain inside the bounds of the parent of the label. If not, then you should "fix" the bounds so that the label remains inside the bounds of its parent component.

Here is an example (it does not use JDesktopPane but the solution should be similar). It lacks a few minor tweaks but it basically works quite well:

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();
            }
        });
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top