如何让用户通过鼠标移动jLabel?

时间:2015-06-04 18:30:29

标签: java swing mouseevent mouse jlabel

我正在JFrame工作,我在JLabel上有这些图片,我希望用户移动它们,以便他们可以选择拖动它们的位置。

public class Level3 extends JFrame {

/**
 * Creates new form Level3
 */
public Level3() {
    initComponents();     
    jLabel16.setVisible(false);
    jLabel17.setVisible(false);
    jLabel18.setVisible(false);
    jLabel19.setVisible(false);
    jLabel20.setVisible(false);
    jLabel21.setVisible(false);
    jLabel22.setVisible(false);
}    private void jButton2ActionPerformed(ActionEvent evt) {                                         
     jLabel16.setVisible(true);
    jLabel17.setVisible(true);
    jLabel18.setVisible(true);
    jLabel19.setVisible(true);
    jLabel20.setVisible(true);
    jLabel21.setVisible(true);
    jLabel22.setVisible(true);
}              

1 个答案:

答案 0 :(得分:0)

如果您只是想在JFrame中拖动标签,可以使用它。它绝不是一个完美的代码,但它对我有用。所以尝试修改它以使其更好。

public class Test extends JFrame implements MouseMotionListener{

        protected JLabel label; 
        protected Point currentLocation;

        public Test() {
            initComponents(); 

            setSize(new Dimension(500, 500));
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }

        private void initComponents() {
            label = new JLabel("some label"); 
            currentLocation = label.getLocation();

            addMouseMotionListener(this);
            add(label); 
        }

        public JLabel getLabel() {
            return label;
        }

        public void setLabel(JLabel label) {
            this.label = label;
        }


        @Override
        public void mouseDragged(MouseEvent e) {

            Point p = e.getPoint();
            currentLocation.x = (int) p.getX();
            currentLocation.y = (int) p.getY() - 250; // Height/2

            label.setLocation(currentLocation);
        }

        @Override
        public void mouseMoved(MouseEvent e) {

        }

}

并尝试使用arraysList来保留您的标签。