返回列表 發帖
本帖最後由 張健勳 於 2018-3-16 23:57 編輯
  1. package bbs.istak.org.tw;

  2. import java.awt.BorderLayout;
  3. import java.awt.EventQueue;

  4. import javax.swing.JFrame;
  5. import javax.swing.JPanel;
  6. import javax.swing.border.EmptyBorder;
  7. import javax.swing.JLabel;
  8. import java.awt.event.MouseMotionAdapter;
  9. import java.awt.event.MouseEvent;

  10. public class Mouse extends JFrame {

  11.         private JPanel contentPane;
  12.         private int X, Y;
  13.         
  14.         public static void main(String[] args) {
  15.                 EventQueue.invokeLater(new Runnable() {
  16.                         public void run() {
  17.                                 try {
  18.                                         Mouse frame = new Mouse();
  19.                                         frame.setVisible(true);
  20.                                 } catch (Exception e) {
  21.                                         e.printStackTrace();
  22.                                 }
  23.                         }
  24.                 });
  25.         }
  26.         public Mouse() {
  27.                 setTitle("\u986F\u793A\u6ED1\u9F20\u6307\u6A19\u7684\u5EA7\u6A19");
  28.                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  29.                 setBounds(100, 100, 420, 320);
  30.                 contentPane = new JPanel();
  31.                 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  32.                 setContentPane(contentPane);
  33.                 contentPane.setLayout(null);
  34.                
  35.                 JLabel JX = new JLabel(); //X座標LB
  36.                 JX.setBounds(267, 243, 46, 15);
  37.                 contentPane.add(JX);
  38.                
  39.                 JLabel JY = new JLabel(); //Y座標Lb
  40.                 JY.setBounds(336, 243, 46, 15);
  41.                 contentPane.add(JY);
  42.                
  43.                 addMouseMotionListener(new MouseMotionAdapter() {
  44.                         @Override
  45.                         public void mouseMoved(MouseEvent e) {
  46.                                 X = e.getX();//抓X座標
  47.                                 Y = e.getY();//抓Y座標
  48.                                 JX.setText("X: "+X); //顯示 X: (X座標)
  49.                                 JY.setText("Y: "+Y); //顯示Y: (Y座標)
  50.                         }
  51.                 });
  52.         }
  53. }
複製代碼

TOP

返回列表