2013-04-16 9 views
7

タイトルバーのないフレームを作成しました。そのためにsetUndecorated(true)を使用しました。方法があるが、その後、何らかの理由でフレームが動かなくなってしまう。Javaスイングフレームを移動可能にしてセットしないでください。

フレームを移動可能にしても、タイトルバーを非表示にするにはどうすればよいですか?

+0

スイングフレームを移動する方法は、タイトルバーをクリックしてドラッグすることです。タイトルバーは移動を意味しません。あなたはどのようにタイトルバーなしでそれをドラッグする予定ですか? – JohnnyO

+2

これはデフォルトの方法ですが、移動可能なタイトルバーがないプログラムを見たことはありませんでしたか?私はして、1つ作成したいと思います:) –

+2

基本的には、 MouseListernerとMouseMotionListenerの組み合わせを使用して、クリックポイントとドラッグポイントの差をデルタする必要があります – MadProgrammer

答えて

14

役立ちます。

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

public class FrameDragListenerExample { 

    public static void main(String[] args) { 
     Runnable runnable = new Runnable() { 
      public void run() { 
       final JFrame frame = new JFrame("Hello"); 

       frame.setUndecorated(true); 
       frame.setBounds(0, 0, 400, 400); 

       JPanel contentPane = new JPanel(new BorderLayout()); 
       JLabel label = new JLabel("Click anywhere in the Jframe and drag"); 
       label.setFont(label.getFont().deriveFont(16f)); 
       label.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100)); 
       contentPane.add(label); 
       frame.setContentPane(contentPane); 

       FrameDragListener frameDragListener = new FrameDragListener(frame); 
       frame.addMouseListener(frameDragListener); 
       frame.addMouseMotionListener(frameDragListener); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }; 
     SwingUtilities.invokeLater(runnable); 
    } 

    public static class FrameDragListener extends MouseAdapter { 

     private final JFrame frame; 
     private Point mouseDownCompCoords = null; 

     public FrameDragListener(JFrame frame) { 
      this.frame = frame; 
     } 

     public void mouseReleased(MouseEvent e) { 
      mouseDownCompCoords = null; 
     } 

     public void mousePressed(MouseEvent e) { 
      mouseDownCompCoords = e.getPoint(); 
     } 

     public void mouseDragged(MouseEvent e) { 
      Point currCoords = e.getLocationOnScreen(); 
      frame.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y); 
     } 
    } 
} 

をあなたはまだ身体をドラッグして、それを周りにドラッグすることができますフレームの

+0

コンポーネントの座標とスクリーン座標を比較するのは良い考えではありません。 mousePressedイベントでもe.getLocationOnScreenを使用する必要があるかもしれません;) – MadProgrammer

+0

thanks great solution –

2

多分これは、次のコードは、あなたがまだ動き回ることができ、タイトルバーなしのJFrameを作成します。あなたMoving Window

関連する問題