SlideShare uma empresa Scribd logo
1 de 12
Baixar para ler offline
บทที่ 12 การใช้ งาน Mouse และ Keyboard

          การใช้งาน   MouseListener   และ   MouseEvent    ในการตรวจสอบการคลิกเมาส์ในตําแหน่งของวัตถุท่ี
ต้องการ

การทดลองที่ 12-1
// File Name : Lab12_01.java

import      java.applet.*;
import      java.awt.*;
import      java.awt.event.*;
import      javax.swing.*;

public class Lab12_01 extends JApplet implements MouseListener {
    int x, y, size;
    Color bgcolor, fgcolor;
    boolean isDraw = true;

      public void init () {
          super.init();
          x = 140;
          y = 100;
          size = 50;
          fgcolor = Color.BLUE;
          addMouseListener(this);
      }

      public void paint(Graphics g) {
          super.paint(g);
          if (isDraw == true) {
              g.setColor(fgcolor);
              g.fillRect( x, y, size , size);
              g.setColor( Color.BLACK );
              g.drawRect( x, y, size, size);
          }
      }

      public void mousePressed(MouseEvent event) {
          Graphics g = getGraphics();
          g.drawString("("+event.getX()+","+event.getY()+")",
                        event.getX(), event.getY());
      }

      public void mouseReleased(MouseEvent event) {
          repaint();
      }

      public void mouseClicked(MouseEvent event) {
          booleanflag = isInside(x,y,size,event.getX(),event.getY());

              if (isDraw == true) {

662305 Information Technology Laboratory II- Chapter 12                                 หน ้า 1 จาก 12
if (flag == true) isDraw = !isDraw;
            }
            else {
                x = event.getX();
                y = event.getY();
                isDraw = !isDraw;
            }
      }

      public void mouseEntered( MouseEvent event ) {
          repaint();
      }

      public void mouseExited(MouseEvent event) {
          repaint();
      }

      boolean isInside(int x1,int y1,int size,int posx,int posy) {
          int x2 = x1 + size;
          int y2 = y1 + size;

            if (posx >= x1 && posx <= x2)
                if (posy >= y1 && posy <= y2) return true;
            return false;
      }

}
ผลลัพธ์




662305 Information Technology Laboratory II- Chapter 12      หน ้า 2 จาก 12
ั
       การใช้งาน MouseListener และ KeyListener กบโปรแกรม Java Application

การทดลองที่ 12-2
// File Name : Lab12_02.java
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Lab12_02 extends JApplet implements KeyListener,
MouseListener {
    private int x, y, size, xCenter, yCenter;
    private int width, height;
    private char typeShape = 'R';

      public Lab12_02() {
          width = 320;
          height = 240;
          xCenter = 160;
          yCenter = 120;
          size = 30;
          x = (width/2) - (size/2);
          y = (height/2) - (size/2);
          addKeyListener( this );
          addMouseListener( this );
      }

      public void paint(Graphics g) {
          super.paint(g);
          g.setColor(Color.BLUE);
          if (typeShape == 'R') {
              g.fillRect( x, y, size , size);
              g.setColor( Color.DARK_GRAY );
              g.drawRect( x, y, size, size);
          }
          else {
              g.fillOval( x, y, size , size);
              g.setColor( Color.DARK_GRAY );

662305 Information Technology Laboratory II- Chapter 12                     หน ้า 3 จาก 12
g.drawOval( x, y, size, size);
            }
            g.setColor(Color.BLACK);
            g.drawLine(1, yCenter,319, yCenter);
            g.drawLine(xCenter, 30,xCenter,239);
      }

      public void mousePressed(MouseEvent event) {
          Graphics g = getGraphics();
          g.drawString(""+ getSize( xCenter, event.getX() ),
                       event.getX(), event.getY() );
      }

      public void mouseReleased(MouseEvent event) {
          repaint();
      }

      public void mouseClicked(MouseEvent event) {
          this.size = getSize(xCenter, event.getX());
          this.x = (width/2) - (size/2);
          this.y = (height/2) - (size/2);
          System.out.println(x + " , "+ y);
      }

      public void mouseEntered( MouseEvent event ) {              }

      public void mouseExited(MouseEvent event) {             }

      public void keyPressed(KeyEvent event) {
          if ( event.getKeyChar() == 'c') typeShape = 'C';
          if ( event.getKeyChar() == 'r') typeShape = 'R';
      }

      public void keyReleased(KeyEvent event) {
          repaint();
      }

      public void keyTyped(KeyEvent event) {              }

      private int getSize(int xCenter, int x) {
          int size = Math.abs ( xCenter - x) * 2;
          return size;
      }

      public void init( ) {
          Lab12_02 window = new Lab12_02();
      }
}




662305 Information Technology Laboratory II- Chapter 12               หน ้า 4 จาก 12
ผลลัพธ์




          การใช้งาน MouseListener และ ActionListener กับโปรแกรมแบบ Applet

การทดลองที่ 12-03
// File Name : Lab12_03.java

import      java.applet.*;
import      java.awt.*;
import      java.awt.event.*;
import      javax.swing.*;

public class Lab12_03 extends JApplet implements ActionListener,
MouseListener {
    int x1, y1, x2,y2;
    JButton btnLine, btnRect, btnCircle, btnClear;
    JTextField text1, text2;
    Color oldColor1, oldColor2;
    char typeShape = 'L';

      public void init () {
          super.init();
          Container c = getContentPane();
          c.setLayout( new FlowLayout() );
          btnLine = new JButton("Line");
          btnLine.addActionListener( this );
          c.add(btnLine);

662305 Information Technology Laboratory II- Chapter 12                     หน ้า 5 จาก 12
btnRect = new JButton("Rectangle");
            btnRect.addActionListener( this );
            c.add(btnRect);

            btnCircle = new JButton("Circle");
            btnCircle.addActionListener( this );
            c.add(btnCircle);

            btnClear = new JButton("Clear");
            btnClear.addActionListener( this );
            c.add(btnClear);

            text1 = new JTextField(12);
            text1.setEditable( false );
            c.add( text1 );

            text2 = new JTextField(12);
            text2.setEditable( false );
            c.add( text2 );

            addMouseListener(this);
            setSize(320, 240);
      }

      public void paint(Graphics               g) {
          super.paint(g);
          switch (typeShape) {
              case 'L' :
                  g.drawLine(x1,               y1, x2, y2);
                  break;
              case 'R' :
                  g.drawRect(x1,               y1, x2-x1, y2-y1);
                  break;
              case 'C' :
                  g.drawOval(x1,               y1, x2-x1, y2-y1);
                  break;
          }
      }

      public void mousePressed(MouseEvent event) {
          if (event.getButton() == 1) { // Mouse Left
              x1 = event.getX();
              y1 = event.getY();
              text1.setText("(X1 = "+x1+",Y1 = "+y1+")" );
          }
          else if (event.getButton() == 3) { // Mouse Right
              x2 = event.getX();
              y2 = event.getY();
              text2.setText(" (X2 = "+x2+",Y2 = "+y2+")" );
          }
      }

      public void mouseReleased(MouseEvent event) {                 }


662305 Information Technology Laboratory II- Chapter 12                 หน ้า 6 จาก 12
public void mouseClicked(MouseEvent event) {
          repaint();
      }

      public void mouseEntered( MouseEvent event ) {
          repaint();
      }

      public void mouseExited(MouseEvent event) {
          repaint();
      }

      public void actionPerformed(ActionEvent e) {
          if (e.getSource() == btnLine) typeShape = 'L';
          else if (e.getSource() == btnRect) typeShape = 'R';
          else if (e.getSource() == btnCircle) typeShape = 'C';
          else if (e.getSource() == btnClear) {
              x1 = y1 = x2 = y2 = 0;
              text1.setText("");
              text2.setText("");
          }
          repaint();
      }

}

ผลลัพธ์




662305 Information Technology Laboratory II- Chapter 12   หน ้า 7 จาก 12
การใช้งาน MouseMontionListener ซ่ ึ งมีเมธอด mouseDragged และ mouseMoved ในการรับเหตุการณ์

การทดลองที่ 12-04
// File Name : Lab12_04.java

import    java.applet.*;
import    java.awt.event.*;
import    java.awt.*;
import    javax.swing.*;

public class Lab12_04 extends JApplet implements ActionListener,
MouseListener, MouseMotionListener{
    private int lastx, lasty;
    private JButton redBtn, greenBtn, blueBtn,clearBtn;
    private Graphics g;
    private Color color;

      public void init() {
          Container c = getContentPane();
          c.setLayout(new FlowLayout());
          redBtn = new JButton("Red");
          redBtn.addActionListener(this);
          c.add(redBtn);

            greenBtn = new JButton("Green");
            greenBtn.addActionListener(this);
            c.add(greenBtn);

            blueBtn = new JButton("Blue");
            blueBtn.addActionListener(this);
            c.add(blueBtn);

            clearBtn = new JButton("Clear");
            clearBtn.addActionListener(this);
            c.add(clearBtn);

            g = getGraphics();
            color = Color.BLACK;
            addMouseListener(this);
            addMouseMotionListener(this);
            setSize(320, 240);
      }

      public void paint(Graphics g) {
          super.paint(g);
      }

662305 Information Technology Laboratory II- Chapter 12                              หน ้า 8 จาก 12
public void mousePressed(MouseEvent event) {
          lastx = event.getX();
          lasty = event.getY();
      }

      public void mouseReleased(MouseEvent event) {           }

      public void mouseClicked(MouseEvent event) {         }

      public void mouseEntered( MouseEvent event ) {           }

      public void mouseExited(MouseEvent event) {         }

      public void mouseDragged(MouseEvent event) {
          int x = event.getX();
          int y = event.getY();
          g.setColor( color );
          g.drawLine(lastx, lasty, x, y);
          lastx = x;
          lasty = y;
      }

      public void mouseMoved(MouseEvent event) {
          showStatus(event.getX() + ", " + event.getY() );
      }

      public void actionPerformed(ActionEvent e) {
          if (e.getSource() == redBtn) color = Color.RED;
          else if (e.getSource() == greenBtn) color = Color.GREEN;
          else if (e.getSource() == blueBtn) color = Color.BLUE;
          else if (e.getSource() == clearBtn) {
              color = Color.BLACK;
              clear();
          }
      }

      public void clear() {
          repaint();
          g.setColor(this.getBackground());
          g.fillRect(0, 0, bounds().width, bounds().height );
      }

}

ผลลัพธ์




662305 Information Technology Laboratory II- Chapter 12            หน ้า 9 จาก 12
ั
      การสร้างโปรแกรมแบบ Java Application ทํางานกบ KeyListener และ Timer
การทดลองที่ 12-05
// File Name : Lab12_05.java

import    java.applet.*;
import    java.awt.event.*;
import    java.awt.*;
import    javax.swing.*;

public class Lab12_05 extends JApplet implements KeyListener,
ActionListener {
    private int width, height;
    private JButton startBtn, stopBtn;
    private int xMin, xMax, yMin, yMax;
    private int x, y, size, xSpeed, ySpeed;
    Timer swTimer;

      public Lab12_05() {
          Container c = getContentPane();
          c.setLayout(new FlowLayout());

            startBtn = new JButton("Play");
            startBtn.addActionListener(this);
            startBtn.addKeyListener(this);

662305 Information Technology Laboratory II- Chapter 12                    หน ้า 10 จาก 12
c.add(startBtn);

            stopBtn = new JButton("Stop");
            stopBtn.addActionListener(this);
            stopBtn.addKeyListener(this);
            c.add(stopBtn);

            width = 480;    height = 320;
            xMin = 1;        xMax = 478;
            yMin = 30;      yMax = 319;
            xSpeed = 2;    ySpeed = 2;
            x = 240; y = 160; size = 40;
            swTimer = new Timer(10, this);
      }

      public void paint(Graphics g) {
          super.paint(g);
          g.setColor( Color.BLACK );
          g.drawRect( 4, 30, 471, 285);
          g.setColor( Color.BLUE );
          g.fillOval( x, y, size, size);
      }

      public void keyPressed(KeyEvent event) {
          if ( event.getKeyChar() == 'p')
              swTimer.start();
          else if ( event.getKeyChar() == 's')
              swTimer.stop();
      }

      public void keyReleased(KeyEvent event) { }

      public void keyTyped(KeyEvent event) {              }

      public void actionPerformed(ActionEvent e) {
          if (e.getSource() == startBtn) swTimer.start();
          else if (e.getSource() == stopBtn) swTimer.stop();
          else {
              move();
              repaint();
          }
      }

      public void move() {
          x = x + xSpeed;
          y = y + ySpeed;
          if (x < xMin) {
              x = xMin;
              xSpeed = -xSpeed;
          }
          else if (x+size > xMax) {
              x = xMax - size;
              xSpeed = -xSpeed;
          }

662305 Information Technology Laboratory II- Chapter 12       หน ้า 11 จาก 12
if (y < yMin) {
                y = yMin;
                ySpeed = -ySpeed;
            }
            else if (y+size > yMax) {
                y = yMax - size;
                ySpeed = -ySpeed;
            }
      }

      public static void main(String[] args) {
          Lab12_05 window = new Lab12_05();
      }
}

ผลลัพธ์




662305 Information Technology Laboratory II- Chapter 12   หน ้า 12 จาก 12

Mais conteúdo relacionado

Mais procurados

NTHU AI Reading Group: Improved Training of Wasserstein GANs
NTHU AI Reading Group: Improved Training of Wasserstein GANsNTHU AI Reading Group: Improved Training of Wasserstein GANs
NTHU AI Reading Group: Improved Training of Wasserstein GANsMark Chang
 
The Ring programming language version 1.5.2 book - Part 63 of 181
The Ring programming language version 1.5.2 book - Part 63 of 181The Ring programming language version 1.5.2 book - Part 63 of 181
The Ring programming language version 1.5.2 book - Part 63 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 65 of 202
The Ring programming language version 1.8 book - Part 65 of 202The Ring programming language version 1.8 book - Part 65 of 202
The Ring programming language version 1.8 book - Part 65 of 202Mahmoud Samir Fayed
 
NTU ML TENSORFLOW
NTU ML TENSORFLOWNTU ML TENSORFLOW
NTU ML TENSORFLOWMark Chang
 
The Ring programming language version 1.5.1 book - Part 66 of 180
The Ring programming language version 1.5.1 book - Part 66 of 180The Ring programming language version 1.5.1 book - Part 66 of 180
The Ring programming language version 1.5.1 book - Part 66 of 180Mahmoud Samir Fayed
 
Computational Linguistics week 5
Computational Linguistics  week 5Computational Linguistics  week 5
Computational Linguistics week 5Mark Chang
 
The Ring programming language version 1.4.1 book - Part 18 of 31
The Ring programming language version 1.4.1 book - Part 18 of 31The Ring programming language version 1.4.1 book - Part 18 of 31
The Ring programming language version 1.4.1 book - Part 18 of 31Mahmoud Samir Fayed
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.UA Mobile
 
The Ring programming language version 1.5.2 book - Part 62 of 181
The Ring programming language version 1.5.2 book - Part 62 of 181The Ring programming language version 1.5.2 book - Part 62 of 181
The Ring programming language version 1.5.2 book - Part 62 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202Mahmoud Samir Fayed
 
551 pd fsam_fayed_ring_doc_1.5.2
551 pd fsam_fayed_ring_doc_1.5.2551 pd fsam_fayed_ring_doc_1.5.2
551 pd fsam_fayed_ring_doc_1.5.2Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 57 of 180
The Ring programming language version 1.5.1 book - Part 57 of 180The Ring programming language version 1.5.1 book - Part 57 of 180
The Ring programming language version 1.5.1 book - Part 57 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 16 of 30
The Ring programming language version 1.4 book - Part 16 of 30The Ring programming language version 1.4 book - Part 16 of 30
The Ring programming language version 1.4 book - Part 16 of 30Mahmoud Samir Fayed
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
The Ring programming language version 1.8 book - Part 53 of 202
The Ring programming language version 1.8 book - Part 53 of 202The Ring programming language version 1.8 book - Part 53 of 202
The Ring programming language version 1.8 book - Part 53 of 202Mahmoud Samir Fayed
 

Mais procurados (20)

NTHU AI Reading Group: Improved Training of Wasserstein GANs
NTHU AI Reading Group: Improved Training of Wasserstein GANsNTHU AI Reading Group: Improved Training of Wasserstein GANs
NTHU AI Reading Group: Improved Training of Wasserstein GANs
 
The Ring programming language version 1.5.2 book - Part 63 of 181
The Ring programming language version 1.5.2 book - Part 63 of 181The Ring programming language version 1.5.2 book - Part 63 of 181
The Ring programming language version 1.5.2 book - Part 63 of 181
 
The Ring programming language version 1.8 book - Part 65 of 202
The Ring programming language version 1.8 book - Part 65 of 202The Ring programming language version 1.8 book - Part 65 of 202
The Ring programming language version 1.8 book - Part 65 of 202
 
NTU ML TENSORFLOW
NTU ML TENSORFLOWNTU ML TENSORFLOW
NTU ML TENSORFLOW
 
Graphical User Components Part 2
Graphical User Components Part 2Graphical User Components Part 2
Graphical User Components Part 2
 
The Ring programming language version 1.5.1 book - Part 66 of 180
The Ring programming language version 1.5.1 book - Part 66 of 180The Ring programming language version 1.5.1 book - Part 66 of 180
The Ring programming language version 1.5.1 book - Part 66 of 180
 
Computational Linguistics week 5
Computational Linguistics  week 5Computational Linguistics  week 5
Computational Linguistics week 5
 
The Ring programming language version 1.4.1 book - Part 18 of 31
The Ring programming language version 1.4.1 book - Part 18 of 31The Ring programming language version 1.4.1 book - Part 18 of 31
The Ring programming language version 1.4.1 book - Part 18 of 31
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Ocr code
Ocr codeOcr code
Ocr code
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.
 
The Ring programming language version 1.5.2 book - Part 62 of 181
The Ring programming language version 1.5.2 book - Part 62 of 181The Ring programming language version 1.5.2 book - Part 62 of 181
The Ring programming language version 1.5.2 book - Part 62 of 181
 
The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184The Ring programming language version 1.5.3 book - Part 79 of 184
The Ring programming language version 1.5.3 book - Part 79 of 184
 
Practical
PracticalPractical
Practical
 
The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202The Ring programming language version 1.8 book - Part 76 of 202
The Ring programming language version 1.8 book - Part 76 of 202
 
551 pd fsam_fayed_ring_doc_1.5.2
551 pd fsam_fayed_ring_doc_1.5.2551 pd fsam_fayed_ring_doc_1.5.2
551 pd fsam_fayed_ring_doc_1.5.2
 
The Ring programming language version 1.5.1 book - Part 57 of 180
The Ring programming language version 1.5.1 book - Part 57 of 180The Ring programming language version 1.5.1 book - Part 57 of 180
The Ring programming language version 1.5.1 book - Part 57 of 180
 
The Ring programming language version 1.4 book - Part 16 of 30
The Ring programming language version 1.4 book - Part 16 of 30The Ring programming language version 1.4 book - Part 16 of 30
The Ring programming language version 1.4 book - Part 16 of 30
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
The Ring programming language version 1.8 book - Part 53 of 202
The Ring programming language version 1.8 book - Part 53 of 202The Ring programming language version 1.8 book - Part 53 of 202
The Ring programming language version 1.8 book - Part 53 of 202
 

Destaque (19)

CENTER OF THE BIBLE
CENTER OF THE BIBLECENTER OF THE BIBLE
CENTER OF THE BIBLE
 
Instructional tech best_practices
Instructional tech best_practicesInstructional tech best_practices
Instructional tech best_practices
 
Karma 2012
Karma 2012Karma 2012
Karma 2012
 
662305 09
662305 09662305 09
662305 09
 
Lowering the drinking age
Lowering the drinking ageLowering the drinking age
Lowering the drinking age
 
662305 11
662305 11662305 11
662305 11
 
El comite sindical 2001
El comite sindical 2001El comite sindical 2001
El comite sindical 2001
 
Lowering the drinking age
Lowering the drinking ageLowering the drinking age
Lowering the drinking age
 
Things_you_dont_see_every_day
Things_you_dont_see_every_dayThings_you_dont_see_every_day
Things_you_dont_see_every_day
 
Set putty to use numeric keyboard in pico
Set putty to use numeric keyboard in picoSet putty to use numeric keyboard in pico
Set putty to use numeric keyboard in pico
 
Things_you_dont_see_every_day
Things_you_dont_see_every_dayThings_you_dont_see_every_day
Things_you_dont_see_every_day
 
Presentacion nomina y pss
Presentacion nomina y pssPresentacion nomina y pss
Presentacion nomina y pss
 
Chapter 1 PowerPoint
Chapter 1 PowerPointChapter 1 PowerPoint
Chapter 1 PowerPoint
 
662305 10
662305 10662305 10
662305 10
 
Control structure
Control structureControl structure
Control structure
 
Narendra murkumbi
Narendra murkumbiNarendra murkumbi
Narendra murkumbi
 
Derivatives in India
Derivatives in IndiaDerivatives in India
Derivatives in India
 
Investment banking
Investment bankingInvestment banking
Investment banking
 
Oppression and Management
Oppression and ManagementOppression and Management
Oppression and Management
 

Semelhante a 662305 LAB12

Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision DetectionJenchoke Tachagomain
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2MEJenchoke Tachagomain
 
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdfimport java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdfanyacarpets
 
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfImport java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfapexcomputer54
 
Creating an Uber Clone - Part VIII.pdf
Creating an Uber Clone - Part VIII.pdfCreating an Uber Clone - Part VIII.pdf
Creating an Uber Clone - Part VIII.pdfShaiAlmog1
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignmentAbdullah Al Shiam
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLgerbille
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfanwarsadath111
 
google play service 7.8 & new tech in M
google play service 7.8 & new tech in M google play service 7.8 & new tech in M
google play service 7.8 & new tech in M Ted Liang
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyoneBartek Witczak
 
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...British Council
 
Mashup caravan android-talks
Mashup caravan android-talksMashup caravan android-talks
Mashup caravan android-talkshonjo2
 
The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88Mahmoud Samir Fayed
 

Semelhante a 662305 LAB12 (20)

Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision Detection
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2ME
 
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdfimport java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
import java.awt.;import java.awt.event.MouseAdaptor;import java.pdf
 
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfImport java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
 
Creating an Uber Clone - Part VIII.pdf
Creating an Uber Clone - Part VIII.pdfCreating an Uber Clone - Part VIII.pdf
Creating an Uber Clone - Part VIII.pdf
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignment
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
 
Encoder + decoder
Encoder + decoderEncoder + decoder
Encoder + decoder
 
No3
No3No3
No3
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdf
 
Applications
ApplicationsApplications
Applications
 
google play service 7.8 & new tech in M
google play service 7.8 & new tech in M google play service 7.8 & new tech in M
google play service 7.8 & new tech in M
 
Java Week8(A) Notepad
Java Week8(A)   NotepadJava Week8(A)   Notepad
Java Week8(A) Notepad
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
 
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
 
Sbaw091117
Sbaw091117Sbaw091117
Sbaw091117
 
CoW Documentatie
CoW DocumentatieCoW Documentatie
CoW Documentatie
 
Mashup caravan android-talks
Mashup caravan android-talksMashup caravan android-talks
Mashup caravan android-talks
 
The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88The Ring programming language version 1.3 book - Part 43 of 88
The Ring programming language version 1.3 book - Part 43 of 88
 
Clock For My
Clock For MyClock For My
Clock For My
 

Mais de Nitigan Nakjuatong (19)

วิธีการกำหนดสิทธิให้กับ Directory
วิธีการกำหนดสิทธิให้กับ Directoryวิธีการกำหนดสิทธิให้กับ Directory
วิธีการกำหนดสิทธิให้กับ Directory
 
Applet 7 image_j_panel
Applet 7 image_j_panelApplet 7 image_j_panel
Applet 7 image_j_panel
 
Applet 5 class_inheritance
Applet 5 class_inheritanceApplet 5 class_inheritance
Applet 5 class_inheritance
 
Applet 7 image_j_panel
Applet 7 image_j_panelApplet 7 image_j_panel
Applet 7 image_j_panel
 
Applet 6 mouse_keyboard
Applet 6 mouse_keyboardApplet 6 mouse_keyboard
Applet 6 mouse_keyboard
 
Applet 5 class_inheritance
Applet 5 class_inheritanceApplet 5 class_inheritance
Applet 5 class_inheritance
 
Applet 4 class_composition
Applet 4 class_compositionApplet 4 class_composition
Applet 4 class_composition
 
Applet 3 design_class_composition
Applet 3 design_class_compositionApplet 3 design_class_composition
Applet 3 design_class_composition
 
662305 08
662305 08662305 08
662305 08
 
Applet 2 container and action_listener
Applet 2 container and action_listenerApplet 2 container and action_listener
Applet 2 container and action_listener
 
662305 Lab7new
662305 Lab7new662305 Lab7new
662305 Lab7new
 
New Assingment3 array2D
New Assingment3 array2DNew Assingment3 array2D
New Assingment3 array2D
 
Assingment3 array2 d
Assingment3 array2 dAssingment3 array2 d
Assingment3 array2 d
 
Lab 6 new
Lab 6 newLab 6 new
Lab 6 new
 
Array2D
Array2DArray2D
Array2D
 
Array
ArrayArray
Array
 
Method part2
Method part2Method part2
Method part2
 
Method JAVA
Method JAVAMethod JAVA
Method JAVA
 
Putty basic setting
Putty basic settingPutty basic setting
Putty basic setting
 

662305 LAB12

  • 1. บทที่ 12 การใช้ งาน Mouse และ Keyboard การใช้งาน MouseListener และ MouseEvent ในการตรวจสอบการคลิกเมาส์ในตําแหน่งของวัตถุท่ี ต้องการ การทดลองที่ 12-1 // File Name : Lab12_01.java import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Lab12_01 extends JApplet implements MouseListener { int x, y, size; Color bgcolor, fgcolor; boolean isDraw = true; public void init () { super.init(); x = 140; y = 100; size = 50; fgcolor = Color.BLUE; addMouseListener(this); } public void paint(Graphics g) { super.paint(g); if (isDraw == true) { g.setColor(fgcolor); g.fillRect( x, y, size , size); g.setColor( Color.BLACK ); g.drawRect( x, y, size, size); } } public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); g.drawString("("+event.getX()+","+event.getY()+")", event.getX(), event.getY()); } public void mouseReleased(MouseEvent event) { repaint(); } public void mouseClicked(MouseEvent event) { booleanflag = isInside(x,y,size,event.getX(),event.getY()); if (isDraw == true) { 662305 Information Technology Laboratory II- Chapter 12 หน ้า 1 จาก 12
  • 2. if (flag == true) isDraw = !isDraw; } else { x = event.getX(); y = event.getY(); isDraw = !isDraw; } } public void mouseEntered( MouseEvent event ) { repaint(); } public void mouseExited(MouseEvent event) { repaint(); } boolean isInside(int x1,int y1,int size,int posx,int posy) { int x2 = x1 + size; int y2 = y1 + size; if (posx >= x1 && posx <= x2) if (posy >= y1 && posy <= y2) return true; return false; } } ผลลัพธ์ 662305 Information Technology Laboratory II- Chapter 12 หน ้า 2 จาก 12
  • 3. การใช้งาน MouseListener และ KeyListener กบโปรแกรม Java Application การทดลองที่ 12-2 // File Name : Lab12_02.java import java.applet.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class Lab12_02 extends JApplet implements KeyListener, MouseListener { private int x, y, size, xCenter, yCenter; private int width, height; private char typeShape = 'R'; public Lab12_02() { width = 320; height = 240; xCenter = 160; yCenter = 120; size = 30; x = (width/2) - (size/2); y = (height/2) - (size/2); addKeyListener( this ); addMouseListener( this ); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.BLUE); if (typeShape == 'R') { g.fillRect( x, y, size , size); g.setColor( Color.DARK_GRAY ); g.drawRect( x, y, size, size); } else { g.fillOval( x, y, size , size); g.setColor( Color.DARK_GRAY ); 662305 Information Technology Laboratory II- Chapter 12 หน ้า 3 จาก 12
  • 4. g.drawOval( x, y, size, size); } g.setColor(Color.BLACK); g.drawLine(1, yCenter,319, yCenter); g.drawLine(xCenter, 30,xCenter,239); } public void mousePressed(MouseEvent event) { Graphics g = getGraphics(); g.drawString(""+ getSize( xCenter, event.getX() ), event.getX(), event.getY() ); } public void mouseReleased(MouseEvent event) { repaint(); } public void mouseClicked(MouseEvent event) { this.size = getSize(xCenter, event.getX()); this.x = (width/2) - (size/2); this.y = (height/2) - (size/2); System.out.println(x + " , "+ y); } public void mouseEntered( MouseEvent event ) { } public void mouseExited(MouseEvent event) { } public void keyPressed(KeyEvent event) { if ( event.getKeyChar() == 'c') typeShape = 'C'; if ( event.getKeyChar() == 'r') typeShape = 'R'; } public void keyReleased(KeyEvent event) { repaint(); } public void keyTyped(KeyEvent event) { } private int getSize(int xCenter, int x) { int size = Math.abs ( xCenter - x) * 2; return size; } public void init( ) { Lab12_02 window = new Lab12_02(); } } 662305 Information Technology Laboratory II- Chapter 12 หน ้า 4 จาก 12
  • 5. ผลลัพธ์ การใช้งาน MouseListener และ ActionListener กับโปรแกรมแบบ Applet การทดลองที่ 12-03 // File Name : Lab12_03.java import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Lab12_03 extends JApplet implements ActionListener, MouseListener { int x1, y1, x2,y2; JButton btnLine, btnRect, btnCircle, btnClear; JTextField text1, text2; Color oldColor1, oldColor2; char typeShape = 'L'; public void init () { super.init(); Container c = getContentPane(); c.setLayout( new FlowLayout() ); btnLine = new JButton("Line"); btnLine.addActionListener( this ); c.add(btnLine); 662305 Information Technology Laboratory II- Chapter 12 หน ้า 5 จาก 12
  • 6. btnRect = new JButton("Rectangle"); btnRect.addActionListener( this ); c.add(btnRect); btnCircle = new JButton("Circle"); btnCircle.addActionListener( this ); c.add(btnCircle); btnClear = new JButton("Clear"); btnClear.addActionListener( this ); c.add(btnClear); text1 = new JTextField(12); text1.setEditable( false ); c.add( text1 ); text2 = new JTextField(12); text2.setEditable( false ); c.add( text2 ); addMouseListener(this); setSize(320, 240); } public void paint(Graphics g) { super.paint(g); switch (typeShape) { case 'L' : g.drawLine(x1, y1, x2, y2); break; case 'R' : g.drawRect(x1, y1, x2-x1, y2-y1); break; case 'C' : g.drawOval(x1, y1, x2-x1, y2-y1); break; } } public void mousePressed(MouseEvent event) { if (event.getButton() == 1) { // Mouse Left x1 = event.getX(); y1 = event.getY(); text1.setText("(X1 = "+x1+",Y1 = "+y1+")" ); } else if (event.getButton() == 3) { // Mouse Right x2 = event.getX(); y2 = event.getY(); text2.setText(" (X2 = "+x2+",Y2 = "+y2+")" ); } } public void mouseReleased(MouseEvent event) { } 662305 Information Technology Laboratory II- Chapter 12 หน ้า 6 จาก 12
  • 7. public void mouseClicked(MouseEvent event) { repaint(); } public void mouseEntered( MouseEvent event ) { repaint(); } public void mouseExited(MouseEvent event) { repaint(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == btnLine) typeShape = 'L'; else if (e.getSource() == btnRect) typeShape = 'R'; else if (e.getSource() == btnCircle) typeShape = 'C'; else if (e.getSource() == btnClear) { x1 = y1 = x2 = y2 = 0; text1.setText(""); text2.setText(""); } repaint(); } } ผลลัพธ์ 662305 Information Technology Laboratory II- Chapter 12 หน ้า 7 จาก 12
  • 8. การใช้งาน MouseMontionListener ซ่ ึ งมีเมธอด mouseDragged และ mouseMoved ในการรับเหตุการณ์ การทดลองที่ 12-04 // File Name : Lab12_04.java import java.applet.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class Lab12_04 extends JApplet implements ActionListener, MouseListener, MouseMotionListener{ private int lastx, lasty; private JButton redBtn, greenBtn, blueBtn,clearBtn; private Graphics g; private Color color; public void init() { Container c = getContentPane(); c.setLayout(new FlowLayout()); redBtn = new JButton("Red"); redBtn.addActionListener(this); c.add(redBtn); greenBtn = new JButton("Green"); greenBtn.addActionListener(this); c.add(greenBtn); blueBtn = new JButton("Blue"); blueBtn.addActionListener(this); c.add(blueBtn); clearBtn = new JButton("Clear"); clearBtn.addActionListener(this); c.add(clearBtn); g = getGraphics(); color = Color.BLACK; addMouseListener(this); addMouseMotionListener(this); setSize(320, 240); } public void paint(Graphics g) { super.paint(g); } 662305 Information Technology Laboratory II- Chapter 12 หน ้า 8 จาก 12
  • 9. public void mousePressed(MouseEvent event) { lastx = event.getX(); lasty = event.getY(); } public void mouseReleased(MouseEvent event) { } public void mouseClicked(MouseEvent event) { } public void mouseEntered( MouseEvent event ) { } public void mouseExited(MouseEvent event) { } public void mouseDragged(MouseEvent event) { int x = event.getX(); int y = event.getY(); g.setColor( color ); g.drawLine(lastx, lasty, x, y); lastx = x; lasty = y; } public void mouseMoved(MouseEvent event) { showStatus(event.getX() + ", " + event.getY() ); } public void actionPerformed(ActionEvent e) { if (e.getSource() == redBtn) color = Color.RED; else if (e.getSource() == greenBtn) color = Color.GREEN; else if (e.getSource() == blueBtn) color = Color.BLUE; else if (e.getSource() == clearBtn) { color = Color.BLACK; clear(); } } public void clear() { repaint(); g.setColor(this.getBackground()); g.fillRect(0, 0, bounds().width, bounds().height ); } } ผลลัพธ์ 662305 Information Technology Laboratory II- Chapter 12 หน ้า 9 จาก 12
  • 10. การสร้างโปรแกรมแบบ Java Application ทํางานกบ KeyListener และ Timer การทดลองที่ 12-05 // File Name : Lab12_05.java import java.applet.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class Lab12_05 extends JApplet implements KeyListener, ActionListener { private int width, height; private JButton startBtn, stopBtn; private int xMin, xMax, yMin, yMax; private int x, y, size, xSpeed, ySpeed; Timer swTimer; public Lab12_05() { Container c = getContentPane(); c.setLayout(new FlowLayout()); startBtn = new JButton("Play"); startBtn.addActionListener(this); startBtn.addKeyListener(this); 662305 Information Technology Laboratory II- Chapter 12 หน ้า 10 จาก 12
  • 11. c.add(startBtn); stopBtn = new JButton("Stop"); stopBtn.addActionListener(this); stopBtn.addKeyListener(this); c.add(stopBtn); width = 480; height = 320; xMin = 1; xMax = 478; yMin = 30; yMax = 319; xSpeed = 2; ySpeed = 2; x = 240; y = 160; size = 40; swTimer = new Timer(10, this); } public void paint(Graphics g) { super.paint(g); g.setColor( Color.BLACK ); g.drawRect( 4, 30, 471, 285); g.setColor( Color.BLUE ); g.fillOval( x, y, size, size); } public void keyPressed(KeyEvent event) { if ( event.getKeyChar() == 'p') swTimer.start(); else if ( event.getKeyChar() == 's') swTimer.stop(); } public void keyReleased(KeyEvent event) { } public void keyTyped(KeyEvent event) { } public void actionPerformed(ActionEvent e) { if (e.getSource() == startBtn) swTimer.start(); else if (e.getSource() == stopBtn) swTimer.stop(); else { move(); repaint(); } } public void move() { x = x + xSpeed; y = y + ySpeed; if (x < xMin) { x = xMin; xSpeed = -xSpeed; } else if (x+size > xMax) { x = xMax - size; xSpeed = -xSpeed; } 662305 Information Technology Laboratory II- Chapter 12 หน ้า 11 จาก 12
  • 12. if (y < yMin) { y = yMin; ySpeed = -ySpeed; } else if (y+size > yMax) { y = yMax - size; ySpeed = -ySpeed; } } public static void main(String[] args) { Lab12_05 window = new Lab12_05(); } } ผลลัพธ์ 662305 Information Technology Laboratory II- Chapter 12 หน ้า 12 จาก 12