如何在运行时移动jpanel

时间:2014-08-13 09:06:35

标签: java swing

我正在处理一个应用程序,我希望jpanel在运行时在jframe内部移动。这是我用过的代码

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                   
}

但无效

2 个答案:

答案 0 :(得分:0)

前一段时间,我已经为这些任务编写了一个框架。也许你觉得它很有用(图书馆是开源的):

教程:

http://softsmithy.sourceforge.net/lib/current/docs/tutorial/swing/customizer/index.html

的Javadoc:

http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-swing-customizer/index.html

有关最新版本的信息:

http://puces-blog.blogspot.ch/2013/11/news-from-software-smithy-version-04.html

答案 1 :(得分:0)

无需在已定义的侦听器中放置MouseAdapter。事实上,你只是声明一个而不是以任何方式使用它。只需将其保留在拖动的事件中即可。

喜欢这个。您可以根据需要进行调整。

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