简体   繁体   English

如何在运行时移动jpanel

[英]how to move jpanel at run time

I am working on an application and I want the jpanel to move around inside jframe at run time. 我正在开发一个应用程序,并且希望jpanel在运行时在jframe中移动。 here is the code I used 这是我使用的代码

package testing;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;


public class ChangePanel extends javax.swing.JFrame {


public ChangePanel() {
    initComponents();
}

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

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);

    jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jPanel1MousePressed(evt);
        }
    });
    jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            jPanel1MouseDragged(evt);
        }
    });

    jLabel1.setText("panel to move");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(56, 56, 56)
            .addComponent(jLabel1)
            .addContainerGap(119, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(62, 62, 62)
            .addComponent(jLabel1)
            .addContainerGap(81, Short.MAX_VALUE))
    );

    getContentPane().add(jPanel1);
    jPanel1.setBounds(160, 60, 247, 161);

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

private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {                                     

 MouseAdapter ma = new MouseAdapter() {

     int lastX =0, lastY =0;
 @Override
    public void mouseDragged(MouseEvent e) {


        int x = e.getXOnScreen();
        int y = e.getYOnScreen();
        // Move frame by the mouse delta
        setLocation(getLocationOnScreen().x + x - lastX,
                getLocationOnScreen().y + y - lastY);
        lastX = x;
        lastY = y;
    }
 };

}                                    

private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {                                     

    MouseAdapter ma = new MouseAdapter() {
    int lastX, lastY;
    @Override
    public void mousePressed(MouseEvent e) {
        lastX = e.getXOnScreen();
        lastY = e.getYOnScreen();
    }};
}                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    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(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ChangePanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ChangePanel().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration                   
}

but is not working 但不起作用

There's no need to put a MouseAdapter within an already defined Listener. 无需将MouseAdapter放在已经定义的侦听器中。 In fact, you're simply declaring one and not using it in any way. 实际上,您只是声明一个而不以任何方式使用它。 Simply keep it inside the dragged event. 只需将其保留在拖动事件中即可。

Like this. 像这样。 You can adapt it to the calculations you need to do. 您可以将其调整为需要执行的计算。

    private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {                                     
        jPanel1.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM