import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.Image; import java.awt.image.*; public class Hina12 extends JFrame { public Hina12() { setSize(700, 700); //最初のフレームサイズ setTitle("Java Example"); //タイトル setDefaultCloseOperation(EXIT_ON_CLOSE); //コンテナを取得してパネルを貼る MyJPanel myJPanel = new MyJPanel(); Container c = getContentPane(); //コンテナの取得 c.add(myJPanel); //パネルを貼る setVisible(true); } /***************** main ****************************/ public static void main(String[] args) { new Hina12(); } /******************************************************** MyJPanel:パネル *********************************************************/ public class MyJPanel extends JPanel implements MouseListener, MouseMotionListener { int flag; int m_x; int m_y; Dimension d; //宣言 Image ima1; int img_width, img_height; /************ コンストラクタ ****************/ public MyJPanel() { getContentPane().addMouseListener(this); getContentPane().addMouseMotionListener(this); m_x=0; m_y=0; //イメージファイルの読み込み Toolkit toolkit=Toolkit.getDefaultToolkit(); ima1 = toolkit.getImage("sample.jpg"); //イメージファイルの読みが終了するまで待ってます。 MediaTracker mt = new MediaTracker(this); mt.addImage(ima1, 1); try{ mt.waitForAll(); } catch (InterruptedException e) { }; //読みが終了後、width,heightの値を取得できる。 img_width = ima1.getWidth(this); img_height = ima1.getHeight(this); } /*************** paintComponent *******************/ public void paintComponent(Graphics g) { if (flag == 1) { g.drawImage(ima1, m_x - img_width/2, m_y - img_height/2, this); flag = 0; } } public void mouseClicked(MouseEvent me) { flag = 1; m_x = me.getX(); m_y = me.getY(); repaint(); } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseMoved(MouseEvent me) { } public void mouseDragged(MouseEvent me) { } } }