2015-09-03 50 views
0

我有以下代碼:鼠標事件,以移動框不工作

panel.addMouseListener(new MouseAdapter() { 
    public void mouseDragged(MouseEvent e) { 
     frame.setLocation(e.getXOnScreen(), e.getYOnScreen()); 
    } 
}); 

panelJPanel,所有的進口已被列入。現在,當我拖動panel時,frame不會移動一點點。爲什麼是這樣,我應該如何解決它?

編輯frame未裝飾。
編輯mouseDragged沒有被觸發 - 這是需要解決的問題! 編輯:CODE !!!!!

package user_interface; 

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

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Test extends JFrame { 
    public Test() { 
     this.setUndecorated(true); 
     this.setLayout(new GridLayout(3, 3, 3, 3)); 
     for (int i = 0; i < 4; i++) { 
      this.add(new JPanel()); 
     } 
     JPanel panel = new JPanel(); 
     panel.setBackground(new Color(0)); 
     panel.setToolTipText("Drag to move frame"); 
     this.addMouseListener(new MouseAdapter() { 
      public void mouseDragged(MouseEvent e) { 
       Test.this.setLocation(e.getXOnScreen(), e.getYOnScreen()); 
       System.out.println(e); 
      } 
     }); 
     this.add(panel); 
     for (int i = 0; i < 4; i++) { 
      this.add(new JPanel()); 
     } 
    } 

    public static void main(String... args) { 
     Test test = new Test(); 
     test.setSize(750, 500); 
     test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 3 
     test.setVisible(true); 
    } 
} 
+0

考慮提供一個[可運行示例](https://stackoverflow.com/help/mcve),它演示了您的問題。這不是代碼轉儲,而是您正在做的事情的一個例子,它突出了您遇到的問題。這會導致更少的混淆和更好的響應 – MadProgrammer

+0

並且[示例](http://stackoverflow.com/questions/16869877/how-to-remove-window-box-from-any-java-gui/16869893#16869893)和[示例](http://stackoverflow.com/questions/30836201/jframe-wrong-location-with-ubuntu-unity/30836537#30836537) – MadProgrammer

+0

[_et al._](http://stackoverflow.com/search ?tab = votes&q =%5bjava%5d%20ComponentMover) – trashgod

回答

1

爲此目的添加MouseMotionListener。

JPanel panel = new JPanel(); 
panel.setBackground(new Color(0)); 
panel.setToolTipText("Drag to move frame"); 

panel.addMouseMotionListener(new MouseMotionAdapter() { 
    public void mouseDragged(MouseEvent e) { 
     super.mouseDragged(e); 
     Test.this.setLocation(e.getXOnScreen(), e.getYOnScreen()); 
     System.out.println(e); 
    } 
}); 

this.setContentPane(panel); 
+0

謝謝!我一定是在方法調用中犯了一個錯誤! – HyperNeutrino