SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
GUI & Event
• ใน GUI เราสามารถทาอะไรได้มากมาย
   –   คลิกเมาส์
   –   เลื่อน mouse wheel
   –   กดปุ่ม keyboard
   –   Touch แล้วลาก รวบห้านิ้ว
• การทาสิ่งใด ๆ ใน GUI จะเกิดเหตุการณ์
   – ทา 1 ครั้ง = สร้าง 1 เหตุการณ์
• event-driven programming แบบหนึ่ง
   – โปรแกรมทางานตามเหตุการณ์ที่สร้างขึ้น
Listener
• Listener = ผู้รับฟัง
   – คอยฟังคนพูด
   – อาจมีโต้ตอบตามสถานการณ์
   – การเป็นผู้ฟังที่ดี
• Event Listener = ผู้รับฟังเหตุการณ์
   – คอยฟังเหตุการณ์ (ที่ผู้ใช้สร้าง)
   – เมื่อมีเหตุการณ์เกิดขึ้น จะทางานตามที่กาหนด
   – Listener จะทาอะไร ขึ้นกับผู้เขียนโปรแกรม
Listener




ที่มา: http://mintclub.kobe-np.co.jp/img/present/367_1_present.JPG
Event Listener
• Listener ~= พนักงานรักษาความปลอดภัย
   – รปภ. ดูแลรักษาความปลอดภัย
   – Listener = รปภ.
   – Event = เหตุการณ์ที่เกิดขึ้น
• รปภ. ตอบสนองต่อเหตุการณ์ต่าง ๆ
   – แลกบัตรผู้มาติดต่อ
   – ดูแลความปลอดภัยทุก 30 นาที
   – ไล่กัดขโมย
Event Listener
                                            ①                               ②




                                            ③                               ④




ที่มา: http://www.youtube.com/watch?feature=player_embedded&v=Q4RAXl4z0gk
Event Listener
• Java API มี listener สาหรับ swing
    – อยู่ในรูปของ interface
• แต่ละ component จะมี listener คอยจับเหตุการณ์
    – ต้องเพิ่ม listener เข้าไปใน component
• พูดถึง listener ที่ได้ใช้เท่านั้น
    – ActionListener
    – KeyListener
Using Listener
• การใช้งาน listener มี 3 วิธี
   – implements กับ JFrame class
   – Inner class
   – Anonymous class
• ทุกวิธีมี tradeoff
   – Anonymous class - listener ที่ทางานเฉพาะเจาะจง
   – Implements กับ class - listener ที่ทางานทั่วไป
ActionListener
•   Listener จับเหตุการณ์ที่มีการคลิกเมาส์
•   อย่าสับสนกับ MouseListener
•   เพิ่ม listener ใช้ addActionListerner(L:    ActionListener)
•   เหตุการณ์ที่ listener สามารถจับได้
           Method Name                         หน้าที่
    actionPerformed(E:
    ActionEvent)                 เมื่อ component ถูกคลิก
Counter GUI
public class CounterGUI extends JFrame {
   private static final Font REGULAR_FONT = new Font("Tahoma", Font.PLAIN, 36);
   private static final Font SMALL_FONT = new Font("Tahoma", Font.PLAIN, 26);
   private int times;
   private JLabel lblCount;
   private JButton btnClick;

    public CounterGUI() {
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setLayout(new GridLayout(2, 1));

        lblCount = new JLabel(Integer.toString(times), SwingConstants.CENTER);
        lblCount.setBorder(new EmptyBorder(3, 3, 3, 3));
        lblCount.setFont(REGULAR_FONT);
        btnClick = new JButton("Click me");
        btnClick.setFont(SMALL_FONT);

        add(lblCount);
        add(btnClick);
        pack();
    }
}
Counter GUI
btnClick.addActionListener(new ActionListener() { // Anonymous Class
   @Override
   public void actionPerformed(ActionEvent e) {
      lblCount.setText(Integer.toString(++times));
   }
});



                 คลิกเมาส์                   คลิกเมาส์
                  1 ครั้ง                     1 ครั้ง
Rock – Scissors – Paper GUI
• เกม เป่า ยิง ฉุบ แบบง่าย ๆ
   – 0 แทนค้อน
   – 2 แทนกรรไกร
   – 5 แทนกระดาษ
• เมื่อกดปุ่มเลือก หน้าจอจะแสดงผลการเป่ายิงฉุบ
Rock – Scissors – Paper GUI
import    java.awt.*;
import    java.awt.event.*;
import    javax.swing.*;
import    javax.swing.border.*;

public class RSHGUI extends JFrame implements ActionListener {
   private static final Font REGULAR_FONT = new Font("Tahoma", Font.PLAIN, 16);
   private JPanel wrapper;
   private JLabel lblPlayerResult;
   private JLabel lblComResult;
   private JButton btnHammer;
   private JButton btnScissor;
   private JButton btnPaper;

  public RSHGUI() {
     setDefaultCloseOperation(EXIT_ON_CLOSE);

         wrapper = new JPanel();
         wrapper.setBorder(new EmptyBorder(new Insets(5, 5, 5, 5)));
         wrapper.setLayout(new GridLayout(3, 3, 5, 5));
         wrapper.add(new JLabel("Player", SwingConstants.CENTER));
         wrapper.add(new JLabel("Computer", SwingConstants.CENTER));
         wrapper.add(new JLabel()); // Dummy Component
Rock – Scissors – Paper GUI
        lblPlayerResult = new JLabel("-", SwingConstants.CENTER);
        lblComResult = new JLabel("-", SwingConstants.CENTER);
        wrapper.add(lblPlayerResult);
        wrapper.add(lblComResult);
        wrapper.add(new JLabel());
        btnHammer = new JButton("0");
        btnHammer.addActionListener(this);
        btnScissor = new JButton("2");
        btnScissor.addActionListener(this);
        btnPaper = new JButton("5");
        btnPaper.addActionListener(this);
        wrapper.add(btnHammer);
        wrapper.add(btnScissor);
        wrapper.add(btnPaper);

        for (Component c : wrapper.getComponents())
           c.setFont(REGULAR_FONT);

        add(wrapper);
        pack();
    }
}
Rock – Scissors – Paper GUI
@Override
public void actionPerformed(ActionEvent e) {
   JButton pressedBtn = (JButton) e.getSource();
   lblPlayerResult.setText(pressedBtn.getText());

    int comRandResult = (int) (Math.random() * 3);
    lblComResult.setText(Integer.toString(comRandResult == 1 ? 2 :
                       comRandResult == 2 ? 5 : 0));
}

• ลองทดสอบผลด้วยตนเอง
KeyListener
•   Listener จับเหตุการณ์เมื่อกดปุ่มบน keyboard
•   ใช้ไม่ได้ผลกับ JFrame
•   เพิ่ม listener ใช้ addKeyListerner(L: KeyListener)
•   เหตุการณ์ที่ listener สามารถจับได้
           Method Name                         หน้าที่
    keyTyped(E: KeyEvent)      เมื่อ keyboard มีการพิมพ์
    keyReleased(E: KeyEvent)   เมื่อปล่อยปุ่มบน keyboard
    keyPressed(E: KeyEvent)    เมื่อกดปุ่ม keyboard
KeyListener
• Listener keyPressed() เมื่อกดค้างจะทางานรัว ๆ
   – ระวังเมื่อใช้ listener นี้ทางาน
• Listener ที่ทางานเกี่ยวกับการแก้ไขข้อมูล ควรใช้ keyReleased()
   – เพิ่ม ลบ แก้ไข
   – Object instantiating
• สามารถเลือกปฏิบัติเมื่อกดปุ่มตามที่กาหนดโดยใช้ if
   – e.getKeyCode(): int คืนค่าเป็นตัวเลขของปุ่มที่กด
   – KeyEvent มีค่าคงที่ของปุ่มอยู่
   – if (e.getKeyCode() == KeyEvent.VK_...) { }
Hello GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloGUI extends JFrame {
   private static final Font REGULAR_FONT = new Font("Tahoma", Font.PLAIN, 16);
   private JPanel wrapper;
   private JTextField txtUsername;
   private JButton btnSubmit;

  public HelloGUI() {
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     wrapper = new JPanel();

     txtUsername = new JTextField(10);
     wrapper.add(txtUsername);
     btnSubmit = new JButton("Submit");
     btnSubmit.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
              hello();
           }
     });
Hello GUI
        wrapper.add(btnSubmit);

        for (Component c : wrapper.getComponents())
           c.setFont(REGULAR_FONT);

        add(wrapper);
        pack();
    }

    private void hello() {
       JOptionPane.showMessageDialog(null, "Hello " + txtUsername.getText());
    }
}
Hello GUI
  txtUsername.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
           if (e.getKeyCode() == KeyEvent.VK_ENTER)
              hello();
        }
  });


• ทดสอบผลด้วยการพิมพ์แล้วกดปุ่ม ENTER และกดปุ่ม submit
Programming Assignment
• เพิ่ม listener กับโปรแกรมเครื่องคิดเลขที่จาเป็น
   – ActionListener
• พิจารณาถึง input ของเครื่องคิดเลข
   – 2+3=+4
   – 2–3+2–5=
   – 5*2/0=

Mais conteúdo relacionado

Destaque

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Destaque (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

Basic Event Listener

  • 1.
  • 2. GUI & Event • ใน GUI เราสามารถทาอะไรได้มากมาย – คลิกเมาส์ – เลื่อน mouse wheel – กดปุ่ม keyboard – Touch แล้วลาก รวบห้านิ้ว • การทาสิ่งใด ๆ ใน GUI จะเกิดเหตุการณ์ – ทา 1 ครั้ง = สร้าง 1 เหตุการณ์ • event-driven programming แบบหนึ่ง – โปรแกรมทางานตามเหตุการณ์ที่สร้างขึ้น
  • 3. Listener • Listener = ผู้รับฟัง – คอยฟังคนพูด – อาจมีโต้ตอบตามสถานการณ์ – การเป็นผู้ฟังที่ดี • Event Listener = ผู้รับฟังเหตุการณ์ – คอยฟังเหตุการณ์ (ที่ผู้ใช้สร้าง) – เมื่อมีเหตุการณ์เกิดขึ้น จะทางานตามที่กาหนด – Listener จะทาอะไร ขึ้นกับผู้เขียนโปรแกรม
  • 5. Event Listener • Listener ~= พนักงานรักษาความปลอดภัย – รปภ. ดูแลรักษาความปลอดภัย – Listener = รปภ. – Event = เหตุการณ์ที่เกิดขึ้น • รปภ. ตอบสนองต่อเหตุการณ์ต่าง ๆ – แลกบัตรผู้มาติดต่อ – ดูแลความปลอดภัยทุก 30 นาที – ไล่กัดขโมย
  • 6. Event Listener ① ② ③ ④ ที่มา: http://www.youtube.com/watch?feature=player_embedded&v=Q4RAXl4z0gk
  • 7. Event Listener • Java API มี listener สาหรับ swing – อยู่ในรูปของ interface • แต่ละ component จะมี listener คอยจับเหตุการณ์ – ต้องเพิ่ม listener เข้าไปใน component • พูดถึง listener ที่ได้ใช้เท่านั้น – ActionListener – KeyListener
  • 8. Using Listener • การใช้งาน listener มี 3 วิธี – implements กับ JFrame class – Inner class – Anonymous class • ทุกวิธีมี tradeoff – Anonymous class - listener ที่ทางานเฉพาะเจาะจง – Implements กับ class - listener ที่ทางานทั่วไป
  • 9. ActionListener • Listener จับเหตุการณ์ที่มีการคลิกเมาส์ • อย่าสับสนกับ MouseListener • เพิ่ม listener ใช้ addActionListerner(L: ActionListener) • เหตุการณ์ที่ listener สามารถจับได้ Method Name หน้าที่ actionPerformed(E: ActionEvent) เมื่อ component ถูกคลิก
  • 10. Counter GUI public class CounterGUI extends JFrame { private static final Font REGULAR_FONT = new Font("Tahoma", Font.PLAIN, 36); private static final Font SMALL_FONT = new Font("Tahoma", Font.PLAIN, 26); private int times; private JLabel lblCount; private JButton btnClick; public CounterGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(2, 1)); lblCount = new JLabel(Integer.toString(times), SwingConstants.CENTER); lblCount.setBorder(new EmptyBorder(3, 3, 3, 3)); lblCount.setFont(REGULAR_FONT); btnClick = new JButton("Click me"); btnClick.setFont(SMALL_FONT); add(lblCount); add(btnClick); pack(); } }
  • 11. Counter GUI btnClick.addActionListener(new ActionListener() { // Anonymous Class @Override public void actionPerformed(ActionEvent e) { lblCount.setText(Integer.toString(++times)); } }); คลิกเมาส์ คลิกเมาส์ 1 ครั้ง 1 ครั้ง
  • 12. Rock – Scissors – Paper GUI • เกม เป่า ยิง ฉุบ แบบง่าย ๆ – 0 แทนค้อน – 2 แทนกรรไกร – 5 แทนกระดาษ • เมื่อกดปุ่มเลือก หน้าจอจะแสดงผลการเป่ายิงฉุบ
  • 13. Rock – Scissors – Paper GUI import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class RSHGUI extends JFrame implements ActionListener { private static final Font REGULAR_FONT = new Font("Tahoma", Font.PLAIN, 16); private JPanel wrapper; private JLabel lblPlayerResult; private JLabel lblComResult; private JButton btnHammer; private JButton btnScissor; private JButton btnPaper; public RSHGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); wrapper = new JPanel(); wrapper.setBorder(new EmptyBorder(new Insets(5, 5, 5, 5))); wrapper.setLayout(new GridLayout(3, 3, 5, 5)); wrapper.add(new JLabel("Player", SwingConstants.CENTER)); wrapper.add(new JLabel("Computer", SwingConstants.CENTER)); wrapper.add(new JLabel()); // Dummy Component
  • 14. Rock – Scissors – Paper GUI lblPlayerResult = new JLabel("-", SwingConstants.CENTER); lblComResult = new JLabel("-", SwingConstants.CENTER); wrapper.add(lblPlayerResult); wrapper.add(lblComResult); wrapper.add(new JLabel()); btnHammer = new JButton("0"); btnHammer.addActionListener(this); btnScissor = new JButton("2"); btnScissor.addActionListener(this); btnPaper = new JButton("5"); btnPaper.addActionListener(this); wrapper.add(btnHammer); wrapper.add(btnScissor); wrapper.add(btnPaper); for (Component c : wrapper.getComponents()) c.setFont(REGULAR_FONT); add(wrapper); pack(); } }
  • 15. Rock – Scissors – Paper GUI @Override public void actionPerformed(ActionEvent e) { JButton pressedBtn = (JButton) e.getSource(); lblPlayerResult.setText(pressedBtn.getText()); int comRandResult = (int) (Math.random() * 3); lblComResult.setText(Integer.toString(comRandResult == 1 ? 2 : comRandResult == 2 ? 5 : 0)); } • ลองทดสอบผลด้วยตนเอง
  • 16. KeyListener • Listener จับเหตุการณ์เมื่อกดปุ่มบน keyboard • ใช้ไม่ได้ผลกับ JFrame • เพิ่ม listener ใช้ addKeyListerner(L: KeyListener) • เหตุการณ์ที่ listener สามารถจับได้ Method Name หน้าที่ keyTyped(E: KeyEvent) เมื่อ keyboard มีการพิมพ์ keyReleased(E: KeyEvent) เมื่อปล่อยปุ่มบน keyboard keyPressed(E: KeyEvent) เมื่อกดปุ่ม keyboard
  • 17. KeyListener • Listener keyPressed() เมื่อกดค้างจะทางานรัว ๆ – ระวังเมื่อใช้ listener นี้ทางาน • Listener ที่ทางานเกี่ยวกับการแก้ไขข้อมูล ควรใช้ keyReleased() – เพิ่ม ลบ แก้ไข – Object instantiating • สามารถเลือกปฏิบัติเมื่อกดปุ่มตามที่กาหนดโดยใช้ if – e.getKeyCode(): int คืนค่าเป็นตัวเลขของปุ่มที่กด – KeyEvent มีค่าคงที่ของปุ่มอยู่ – if (e.getKeyCode() == KeyEvent.VK_...) { }
  • 18. Hello GUI import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloGUI extends JFrame { private static final Font REGULAR_FONT = new Font("Tahoma", Font.PLAIN, 16); private JPanel wrapper; private JTextField txtUsername; private JButton btnSubmit; public HelloGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); wrapper = new JPanel(); txtUsername = new JTextField(10); wrapper.add(txtUsername); btnSubmit = new JButton("Submit"); btnSubmit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { hello(); } });
  • 19. Hello GUI wrapper.add(btnSubmit); for (Component c : wrapper.getComponents()) c.setFont(REGULAR_FONT); add(wrapper); pack(); } private void hello() { JOptionPane.showMessageDialog(null, "Hello " + txtUsername.getText()); } }
  • 20. Hello GUI txtUsername.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) hello(); } }); • ทดสอบผลด้วยการพิมพ์แล้วกดปุ่ม ENTER และกดปุ่ม submit
  • 21. Programming Assignment • เพิ่ม listener กับโปรแกรมเครื่องคิดเลขที่จาเป็น – ActionListener • พิจารณาถึง input ของเครื่องคิดเลข – 2+3=+4 – 2–3+2–5= – 5*2/0=