JFrame上のJButtonをドラッグしてみる

戻る



:::::::::::::: RagFrame.java :::::::::::::: /** $Id: DraggingButtonOnJFrame.html,v 1.1 2009/06/22 16:11:42 kishi Exp kishi $ */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; /** $Id: DraggingButtonOnJFrame.html,v 1.1 2009/06/22 16:11:42 kishi Exp kishi $ */ public class RagFrame extends JFrame { private int width = 640; private int height = 480; public RagFrame() { super( "JButtonをグラフィックと混在させる" ); Container contentPane = getContentPane(); contentPane.setLayout( new FlowLayout() ); DrawingPanel dp = new DrawingPanel(); dp.setPreferredSize( new Dimension( width, height ) ); contentPane.add( dp ); } public static void main( String[] args ) { RagFrame frame = new RagFrame(); /* 終了処理を追加 */ frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); /** サイズと位置を指定 */ frame.setBounds( 0, 0, frame.width, frame.height ); frame.setVisible( true ); frame.pack(); } } :::::::::::::: DrawingPanel.java :::::::::::::: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; /** $Id: DraggingButtonOnJFrame.html,v 1.1 2009/06/22 16:11:42 kishi Exp kishi $ @author KISHI Yasuhiro */ public class DrawingPanel extends JPanel { private JButton button; public DrawingPanel() { // レイアウトマネージャを使用しない setLayout( null ); button = new JButton( "ステップ" ); button.setBounds( 10, 10, 200, 200 ); this.add( button ); button.addMouseMotionListener( new MyMouseMotionListener( ) ); } private class MyMouseMotionListener implements MouseMotionListener { public void mouseDragged( MouseEvent argEvent ) { System.out.printf( "(%3d,%3d)\n", argEvent.getX() , argEvent.getY() ); if ( argEvent.getX() < 0 || argEvent.getY() < 0 ) { Rectangle objBounds = button.getBounds(); button.setLocation( objBounds.x + argEvent.getX(), objBounds.y + argEvent.getY() ); } else { Rectangle objBounds = button.getBounds(); if ( objBounds.x <= objBounds.x + argEvent.getX() && objBounds.x + argEvent.getX() <= objBounds.x + objBounds.width && objBounds.y <= objBounds.y + argEvent.getY() && objBounds.y + argEvent.getY() <= objBounds.y + objBounds.height ) { button.setLocation( objBounds.x + argEvent.getX(), objBounds.y + argEvent.getY() ); } else { button.setLocation( argEvent.getX(), argEvent.getY() ); } } repaint(); } public void mouseMoved( MouseEvent argEvent ) { } } /** in case when repaint() method is invoked, this method is also executed. */ public void paintComponent( Graphics g ) { System.out.println( "paintComponet:" ); int width = getWidth(); int height = getHeight(); // 画面クリア g.setColor( Color.black ); // このコンポーネントのサイズを取得する g.fillRect( 0 , 0 , width , height ); g.setColor( Color.red ); Point p = button.getLocation(); g.drawLine( 0, 0, ( int ) p.getX(), ( int ) p.getY() ); } }
戻る inserted by FC2 system