移動組件練習

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   ext   

 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*;  4 import javax.swing.event.*; 5 public class moveText{ 6     Label myText; 7     Frame mT; 8     Point point = new Point(0, 0); 9     public moveText(){10         myText=new Label("move me please!");11         mT = new Frame("moveTEXT");12         myText.setBackground(Color.yellow);13  14         mT.addWindowListener(new myWindowListener());15         mT.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));16         mT.setSize(600, 600);17         mT.setLocation(100, 100);18         myText.addMouseMotionListener(new myMouseListener1());19         myText.addMouseListener(new myMouseListener2());20         myText.setSize(20, 5);21         mT.add(myText);22         23         mT.setVisible(true);24     }25     class myMouseListener1 extends MouseMotionAdapter {26           27          /* 28           當滑鼠拖動時觸發該事件。 記錄下滑鼠按下(開始拖動)的位置。 29          */  30         public void mouseDragged(MouseEvent e) {  31             // 轉換座標系統,將新的座標(滑鼠相對於組件的座標)轉換成該相對與其組件的父親組件的座標32             Point newPoint = SwingUtilities.convertPoint(myText, e  33                     .getPoint(), myText.getParent());  34             // 設定標籤的新位置  35             36             myText.setLocation(myText.getX()  37                     + (newPoint.x - point.x), myText.getY()  38                     + (newPoint.y - point.y));39             40             //這時開始寫的方法,明顯和上面的方法差別很大41             //myText.setLocation(newPoint);42             43             // 更改座標源點  44             point = newPoint;  45         }  46     }47     class myMouseListener2 extends MouseAdapter{48         /*49            當滑鼠按下時觸發該事件。 記錄下滑鼠按下(開始拖動)的位置。 50          */  51         public void mousePressed(MouseEvent e) {  52             // 得到當前座標點  53             point = SwingUtilities.convertPoint(myText, e.getPoint(),  54                     myText.getParent());  55        }56     }57     public static void main(String args[]){58         moveText mT=new moveText();59         60     }61 }62 63 class myWindowListener extends WindowAdapter{64     public void windowClosing(WindowEvent e){//Frame的關閉方法65        System.exit(0);66     }67 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.