62
บทที15 JComponent และการจัดการอีเว้นท์ JComponent and Events ในบทนี้กล่าวถึง JComponent ชนิดต่างๆ เช่น JPanel, Border, JRadioButtion เป็นต้น ซึ่งอยู่ใน Package javax.swing และกล่าวถึงวิธีการจัดการเหตุการณ์ต่างๆ (Events) ที่เกิดขึ้นเมื่อผู้ใช้งานคลิกหรือเรียกใช้ งาน JComponent JPanel JPanel เป็นคลาส Container ที่สามารถบรรจุ JComponent อื่นๆ ได้ วัตถุประสงค์ของการใช้ JPanel คือ เพื่อจัดเรียงให้ GUI Component อยู่รวมกัน และง่ายต่อการจัดการ เพราะเมื่อมีการย้าย JPanel ส่งผลให้ JComponet ทั้งหมดที่อยู่ใน JPanel นั้นถูกย้ายตามไปด้วย นอกจากนี้ยังทาให้เกิดความสวยงามในการจัดเรียง JComponent ด้วย เช่นภาพที่ 15.1 ภาพที่ 15.1 แสดง JPanel จากโปรแกรม TestJPanel.java คาสั่งที่ใช้ในการสร้าง JPanel คือ JPanel panel = new JPanel(); เมื่อสร้าง JPanel แล้ว สามารถเพิ่ม JComponent ต่างๆ ไปทีJPanel ได้ จึงอาจกล่าวได้ว่า JPanel มี ลักษณะการทางานคล้ายกับ ContentPane ใน JFrame โปรแกรม TestJPanel.java แสดงการสร้าง JPanel ซ้าย และขวา ซึ่งในแต่ละ JPanel ประกอบด้วย JButtton จานวน 2 ปุ่มคือ Hello และ Click here ดังภาพที่ 15.1 import java.awt.*; import javax.swing.*; import javax.swing.border.*; class MyFrame extends JFrame{ public MyFrame(int width, int height) { Toolkit tk = getToolkit();

บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

บทท 15

JComponent และการจดการอเวนท JComponent and Events ในบทนกลาวถง JComponent ชนดตางๆ เชน JPanel, Border, JRadioButtion เปนตน ซงอยใน Package javax.swing และกลาวถงวธการจดการเหตการณตางๆ (Events) ทเกดขนเมอผใชงานคลกหรอเรยกใชงาน JComponent JPanel JPanel เปนคลาส Container ทสามารถบรรจ JComponent อนๆ ได วตถประสงคของการใช JPanel คอ เพอจดเรยงให GUI Component อยรวมกน และงายตอการจดการ เพราะเมอมการยาย JPanel สงผลให JComponet ทงหมดทอยใน JPanel นนถกยายตามไปดวย นอกจากนยงท าใหเกดความสวยงามในการจดเรยง JComponent ดวย เชนภาพท 15.1

ภาพท 15.1 แสดง JPanel จากโปรแกรม TestJPanel.java ค าสงทใชในการสราง JPanel คอ JPanel panel = new JPanel();

เมอสราง JPanel แลว สามารถเพม JComponent ตางๆ ไปท JPanel ได จงอาจกลาวไดวา JPanel มลกษณะการท างานคลายกบ ContentPane ใน JFrame โปรแกรม TestJPanel.java แสดงการสราง JPanel ซาย และขวา ซงในแตละ JPanel ประกอบดวย JButtton จ านวน 2 ปมคอ Hello และ Click here ดงภาพท 15.1 import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Page 2: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

256 การเขยนโปรแกรมภาษา Java

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

// สรางคลาส MyPanel ซง Inherit จากคลาส JPanel class MyPanel extends JPanel{

public MyPanel(String name) {

// สราง Border โปรดอานเรอง Border ในหวขอถดไป TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

setBorder(border);

}

}

public class TestJPanel {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200, 400);

frame.setTitle("Test JPanel");

// สราง GridLayout (1 row, 2 cols) frame.getContentPane().setLayout(new GridLayout(1. 2));

// สราง JPanel โดยมชอเปน ‚Left Panel‛ MyPanel leftPanel = new MyPanel("Left Panel");

// เพม JButton ‚Hello‛ ลงใน leftPanel leftPanel.add(new Button("Hello"));

// เพม JButton ‚Click here‛ leftPanel.add(new Button("Click here"));

// สราง JPanel ส าหรบดานขวา MyPanel rightPanel = new MyPanel("Right Panel");

rightPanel.add(new Button("Hello"));

rightPanel.add(new Button("Click here"));

// เพม leftPanel ไปท ContentPane frame.getContentPane().add(leftPanel);

// เพม rightPanel ไปท ContentPane frame.getContentPane().add(rightPanel);

frame.setVisible(true);

}

}

Border ทก JComponent สามารถเพมเสนขอบ เพอใหเกดความสวยงามได และสามารถเพมชองวางระหวาง JComponent ทอยตดกนเพอท าให JComponent ไมอยชดเกนไป

คลาสทเกยวของกบการสรางเสนขอบคอ javax.swing.BorderFactory และคลาสตางๆ ใน Package javax.swing.border.* ตวอยางการสรางเสนขอบโดยใชค าสงในการสราง Border ดงตอไปน Border border = BorderFactory.createLineBorder(Color.BLACK);

Page 3: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 257

ค าสง createLineBorder(Color.BLACK) สงคาวตถ Border กลบโดยเปนเสนขอบทมสด า เมอสราง Border แลว ขนตอไป คอ ตงคาใหกบ JComponent ดงตวอยาง JPanel panel = new JPanel();

panel.setBorder(border);

ชนดของ Border มหลายแบบ สรางไดโดยใชค าสง BorderFactory.create…() ขนกบชนดของ Border ทตองการ เชน blackline = BorderFactory.createLineBorder(Color.black);

etched = BorderFactory.createEtchedBorder();

raisedbevel = BorderFactory.createRaisedBevelBorder();

loweredbevel = BorderFactory.createLoweredBevelBorder();

empty = BorderFactory.createEmptyBorder();

โปรแกรม LineBorderJPanel.java แสดงการเพมเสนขอบใหกบ JPanel โดยสามารถก าหนดสของ Border ใหมความแตกตางกนดงผลลพธในภาพท 15.2 import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

public class LineBorderJPanel {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,200);

frame.setTitle("Test JPanel");

// ใช BorderLayout ซงสามารถละไดเนองจากเปนคาเรมตนของ JFrame frame.getContentPane().setLayout(new BorderLayout() );

JPanel leftPanel = new JPanel();

// สราง Border เสนสด า leftPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

leftPanel.add(new Button("Hello left"));

JPanel rightPanel = new JPanel();

//สราง Border เสนสน าเงน rightPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));

rightPanel.add(new Button("Hello right"));

Page 4: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

258 การเขยนโปรแกรมภาษา Java

//เพม JPanel ใน JFrame frame.getContentPane().add(leftPanel, BorderLayout.WEST);

frame.getContentPane().add(rightPanel, BorderLayout.EAST);

frame.setVisible(true);

}

}

ภาพท 15.2 แสดง LineBorder โปรแกรมตอไป EtchedBorderJPanel.java แสดงการสราง Etched Border หรอเสนขอบแบบลายพมพ ค าสง createEtchedBorder() สามารถระบชนดของเสนขอบทตองการใหนนหรอยบลงไดโดยใชคาคงทของคลาส EtchedBorder ใน Package javax.swing.border 2 คา คอ EtchedBorder.RAISED จะท าใหเสนขอบมลกษณะทนนขน และ EtchedBorder.LOWERED ท าใหเสนขอบมลกษณะทยบลง import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

public class EtchedBorderJPanel {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,200);

frame.setTitle("Test EtchedBorder");

// ใช BorderLayout Manager frame.getContentPane().setLayout(new BorderLayout() );

JPanel leftPanel = new JPanel();

// สราง EtchedBorder แบบรอยเสนลก กรณไมระบคา Parameter leftPanel.setBorder( BorderFactory.createEtchedBorder() );

leftPanel.add(new Button("Hello left"));

JPanel rightPanel = new JPanel();

Page 5: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 259

// สราง EtchedBorder โดยมรอยเสนนน rightPanel.setBorder(BorderFactory.createEtchedBorder(

EtchedBorder.RAISED));

rightPanel.add(new Button("Hello right"));

frame.getContentPane().add(leftPanel, BorderLayout.WEST);

frame.getContentPane().add(rightPanel, BorderLayout.EAST);

frame.setVisible(true);

}

}

ภาพท 15.3 แสดง EtchedBorder

โปรแกรม BevelBorderJPanel.java แสดงการเพมเสนขอบใหกบ JPanel แบบ Bevel ซงท าใหพนทงหมดของของ JPanel สงหรอต าลงได import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

public class BevelBorderJPanel {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,200);

frame.setTitle("Test EtchedBorder");

frame.getContentPane().setLayout(new BorderLayout() );

JPanel leftPanel = new JPanel();

// สราง Raised Bevel แบบยกพน JPanel สงขน leftPanel.setBorder( BorderFactory.createRaisedBevelBorder() );

leftPanel.add(new Button("Hello left"));

JPanel rightPanel = new JPanel();

// สราง Lowered Bevel แบบท าใหพนต าลง rightPanel.setBorder( BorderFactory.createLoweredBevelBorder());

EtchedBorder.RAISED

Page 6: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

260 การเขยนโปรแกรมภาษา Java

rightPanel.add(new Button("Hello right"));

frame.getContentPane().add(leftPanel, BorderLayout.WEST);

frame.getContentPane().add(rightPanel, BorderLayout.EAST);

frame.setVisible(true);

}

}

ภาพท 15.4 แสดง BevelBorder โปรแกรมตอไป TitledBorderJPanel.java แสดงการเพมเสนขอบใหกบ JPanel แบบ TitledBorder ซงสามารถใสค าอธบายอยทเสนขอบได import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

public class TitledBorderJPanel {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200, 200);

frame.setTitle("Test EtchedBorder");

frame.getContentPane().setLayout(new BorderLayout() );

JPanel leftPanel = new JPanel();

Border etched = new EtchedBorder();

TitledBorder border =

BorderFactory.createTitledBorder(etched, "Left");

// ปรบให Title อยกลาง Border border.setTitleJustification(TitledBorder.CENTER);

leftPanel.setBorder(border);

leftPanel.add(new Button("Hello left"));

JPanel rightPanel = new JPanel();

RaisedBevelBorder

LoweredBevelBorder

Page 7: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 261

// ถาไมระบวาต าแหนงของ Title โดยใช setTitleJustification() // จะท าให Title อยในต าแหนงชดดานซายเสมอ rightPanel.setBorder(

BorderFactory.createTitledBorder(etched, "Right"));

rightPanel.add(new Button("Hello right"));

frame.getContentPane().add(leftPanel, BorderLayout.WEST);

frame.getContentPane().add(rightPanel, BorderLayout.EAST);

frame.setVisible(true);

}

}

ภาพท 15.5 แสดง TitledBorder

จากโปรแกรม TitledBorderJPanel.java ค าอธบายทใสไวทเสนขอบสามารถเปลยนต าแหนงไดโดยใช

ค าสง setTitleJustification(TitledBorder.CENTER) ซงท าใหค าอธบายอยกลางเสนขอบ ถาตองการใหชดดานขวาสามารถใช TitledBorder.RIGHT ไดเปนตน JLabel ใชในการแสดงขอความหรอรปภาพ ซงขอความทแสดงไมสามารถเปลยนแปลงโดยผใชงาน รปแบบ Constructor ของ JLabel ส าหรบใชแสดงขอความทางจอภาพคอ JLabel(String text, int horizontalAlignment);

คา text เปนขอความทตองการใหแสดงใน JLabel สวนคา horizontalAlignment คอต าแหนงทแสดงขอความใน JLabel ซงสามารถมคาเปน JLabel.CENTER, JLabel.RIGHT หรอ JLabel.LEFT ส าหรบConstructor ของ JLabel ส าหรบแสดงทงขอความและรปภาพคอ JLabel(String text, Icon icon, int horizontalAlignment)

Page 8: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

262 การเขยนโปรแกรมภาษา Java

การสราง Icon สามารถสรางไดดงตวอยางตอไปน ImageIcon icon = new ImageIcon(String filename);

การสราง Icon ตองระบชอของแฟมขอมลทเปนรปภาพเทานน โปรแกรม ShowJLabel.java แสดงการใชงาน JLabel โดยผลลพธแสดงในภาพท 15.6 import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit(); Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel{

JLabel label1, label2, label3, label4;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

setBorder(border);

// ตงคา Layout Manger เปน GridLayout ประกอบดวบ 4 rows 1 col setLayout( new GridLayout(4,1) );

// วางขอความตรงกลาง JLabel label1 = new JLabel("Hello how are you?", JLabel.CENTER);

// สราง Icon จากแฟมขอมล x.gif ImageIcon icon = new ImageIcon("x.gif");

// วาง Icon และขอความชดซายชดซายของ JLable label2 = new JLabel("Label with icon", icon, JLabel.LEFT);

// วาง Icons และขอความไวตรงกลาง JLabel label3 = new JLabel("Label with icon", icon, JLabel.CENTER); label4 = new JLabel("Label with icon", icon, JLabel.CENTER);

// ส าหรบ label4 ตงคาใหขอความอยตรงกลางใตรปภาพ label4.setVerticalTextPosition(JLabel.BOTTOM);

label4.setHorizontalTextPosition(JLabel.CENTER);

add(label1);

add(label2);

add(label3);

add(label4);

}

}

public class ShowJLabel {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,300);

frame.setTitle("Test JLablel");

Page 9: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 263

MyPanel panel = new MyPanel("JLebel");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

จากโปรแกรม ShowJLabel.java ตวแปร label4 มทงขอความและรปภาพ ซงสามารถก าหนดต าแหนงใหตวอกษรแสดงโดยเทยบกบรปภาพได //ใหแสดงขอความใตรปภาพและอยตรงกลาง label4.setVerticalTextPosition(JLabel.BOTTOM);

label4.setHorizontalTextPosition(JLabel.CENTER);

//ใหแสดงขอความบนรปภาพและชดซาย label4.setVerticalTextPosition(JLabel.TOP);

label4.setHorizontalTextPosition(JLabel.LEFT);

การเปลยนคาขอความทแสดงใน JLabel กอนหนาน ใชค าสง setText(String text)

ภาพท 15.6 แสดงผลลพธจากโปรแกรม ShowJLabel.java

Event กอนทจะกลาวถง JComponent ชนดตอไป จะอธบายการใช Event ใน GUI เพอสามารถน าไปใชในการตรวจสอบ เมอผใชงานมการโตตอบกบ JComponent การเขยนโปรแกรมเพอจดการกบ GUI ใชการหลกการของ Events-Driven Program หลกการท างานคอ เมอผใชงานมการสงงานผาน JComponent ใน GUI เชนการคลกเมาสบน JButton การกดปมบน Keyboard หรอแมแตการเคลอนเมาส จะท าใหเกดสญญาณ Event สงออกมา ถาผเขยนโปรแกรมอยากทราบวาผใชงานมการเคลอนเมาสหรอไม ผเขยนโปรแกรมตองสรางดกจบสญญาณ MouseEvent ทถกสงออกมา เมอใดกตามทผใชงานมการเคลอนเมาส JVM จะสง MouseEvent ออกมา ดงภาพท 15.7 และเมอดกจบสญญาณไดแลว ผเขยนโปรแกรมจ าเปนตองสราง Event Routine ส าหรบ Event ทจบไดดวย โดยการ Implement คลาส Listener

Page 10: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

264 การเขยนโปรแกรมภาษา Java

ภาพท 15.7 เมอเคลอนเมาสท าใหเกด Event

ถาตองการจบสญญาณ Event ใน GUI จ าเปนตองสรางคลาสท Implement Listener Interface เชน การจบ Event ทเกดจากการเปดหรอปด Widows จ าเปนตองใหคลาสทมการดกจบ Event เหลาน implement WindowListener เพอสราง Methods ตางๆ ตามขอก าหนดของ WindowListener ส าหรบรองรบในกรณทเกด Event ขน หลงจากนนตองใชค าสง addWindowListener(WindowListener l) โดยม Parameter เปนคลาสทมการ Implement Listener Interface น Event ไดแบงเปน 2 ชนดคอ

Low-Level Events ส าหรบ Windows, Mouse และ Keyboard Semantic Events ส าหรบ Component อนๆ ใน java.awt และ javax.swing

Low-Level Events: Window Listener WindowListener Interface (java.awt.event.WindowListener) ใชในการจบสญญาณทเกดจาก JFrame เชน การเปด ปด Windows การยอ หรอขยายขนาดของ Windows ซงม Abstract Method ดงตอไปน

public void windowOpened(WindowEvent) ถกเรยกเมอมการเปด Windows public void windowClosing(WindowEvent) ถกเรยกเมอมการปด Windows ซงผเขยนโปรแกรมควร

เรยกใช dispose() หรอ setVisible(false) ถาไมมการเรยกใช Methods ทงสองนใน Event Routine จะท าใหการปด Windows ถกยกเลก

public void windowClosed(WindowEvent) ถกเรยกใชเมอ Windows ถกปดแลว public void windowIconified(WindowEvent) ถกเรยกเมอมการกดปม Minimize void windowDeiconified(WindowEvent) ถกเรยกเมอมการกดปม Restore void windowActivated(WindowEvent) ถกเรยกเมอมการเลอก Windows นโดยการคลกทสวนใดสวน

หนงของ Windows public void windowDeactivated(WindowEvent) ถกเรยกเมอมการคลกท Windows อน

โปรแกรม WinEvent.java แสดงการใช WindowListener เพอจบ Event เมอผใชงานปด Windows แทนการใชค าสง setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) สงเกตวาถามการ Implements Interface แลว จ าเปนตองสราง Method ทงหมดใน Interface นนดวย แมวาจะไมมการเขยนค าสงใดๆ ใน Method เหลานนกตาม เนองจาก Interface บรรจ Pure Abstract Method เทานน import java.awt.*;

Move mouse Event

Mousemove(){ Do something }

Page 11: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 265

import javax.swing.*;

import java.awt.event.*;

class MyFrame extends JFrame implements WindowListener{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width – width)/2,

(screen.height – height)/2, width, height);

// เนองจากคลาส MyFrame ได Implements WindowsListener // สามารถใช this เปน Pameter ของ addWindowListener() ได addWindowListener(this);

}

public void windowClosing(WindowEvent e) {

// ค าสง dispose() ใชซอน Windows เทานน ไมใชการปด Windows // ถาตองการจบโปรแกรมตองใช System.exit() เทานน dispose();

System.exit(0);

}

/*จ าเปนตองเขยน Methods ทงหมดทมอยใน WindowListener Interface แมวาไมตอง การใชกตาม ดงทกลาวแลว*/ public void windowClosed(WindowEvent e) {}

public void windowOpened(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

public void windowDeactivated(WindowEvent e) {}

}

public class WinEvent {

public static void main(String[] args) {

MyFrame frame = new MyFrame(400, 200);

frame.setVisible(true);

}

}

ส าหรบ Listener Interface ทเกยวของกบการจดการ Windows มอกสอง Interfaces คอ WindowFocusLister ใชส าหรบดกจบ Event ในกรณท Windows หรอ Component ทอยใน Windows เชน JTextField ไดรบ Focus จาก Keyboard

void windowGainedFocus (WindowEvent e) public void windowLostFocus (WindowEvent e)

WindowStateListener ใชส าหรบดกจบ Event ในกรณทสถานะของ Windows มการเปลยนแปลง เชน การ Minimize หรอ การ Restore

public void windowStateChanged(WindowEvent e)

Page 12: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

266 การเขยนโปรแกรมภาษา Java

การใช WindowListener ทกลาวมา ผเขยนโปรแกรมจ าเปนตองเขยน Methods ทงหมดแมวาไมตองการใชงาน เนองจากกฎของการใช Interface (ในบทท 5) แตเพอความสะดวก ผเขยนโปรแกรมสามารถใชคลาส WindowAdapter ซงคลาสนมการ Implements Methods ทงหมดของ WindowListener, WindowFocusListener และ WindowStateListerner แลว ดงนนผเขยนโปรแกรมไมจ าเปนสราง Methods ทงหมดใน Interface อก และสามารถเลอกสราง Methods ทตองการเทานน ดงตวอยางโปรแกรม WinEvent1.java import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

class MyFrame extends Jframe {

public MyFrame(int width, int height) {

//can call getToolkit() methods directly from Jframe

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width – width)/2,

(screen.height – height)/2, width, height);

}

}

public class WinEvent1 extends WindowAdapter{

static MyFrame frame = new MyFrame(400, 200);

public static void main(String[] args) {

frame.addWindowListener(new WinEvent1());

frame.setVisible(true);

}

public void windowClosing(WindowEvent e) {

frame.dispose();

System.exit(0);

}

}

โปรแกรม WinEvent1.java ใชการ Extends WindowAdapter ซงท าใหจ านวนค าสงนอยลงอยางมาก เนองจากไมจ าเปนตองเขยน Method ทไมตองการเหมอนในโปรแกรม WinEvent.java แตขอจ ากดของการใช WindowAdapter คอท าใหคลาส WinEven1 ไมสามารถ Extends คลาสใดๆ ไดอก เนองจากในภาษา Java คลาสทสรางขนสามารถ Extends คลาสแมไดเพยงคลาสเดยวเทานน Low-Level Events: Mouse Listener การจบ Event ทเกดจากเมาสสามารถใช Interface MouseListener, MouseMotionListener และ MouseWheelListener ได MouseListener ใชส าหรบดกจบ Event ในกรณทมการสงงานโดยใชเมาส

public void mouseClicked(MouseEvent e) public void mousePressed(MouseEvent e) public void mouseReleased(MouseEvent e) public void mouseEntered(MouseEvent e) public void mouseExited(MouseEvent e)

Page 13: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 267

MouseMotionListener ใชส าหรบดกจบ Event ในกรณทมการเคลอนหรอ Drag and Drop เมาส public void mouseMoved(MouseEvent e) public void mouseDragged(MouseEvent e)

MouseWheelListener ใชส าหรบดกจบ Event ในกรณทมการใช Wheel ของเมาส mouseWheelMoved(MouseWheelEvent e)

เชนเดยวกบ WindowAdapter ผเขยนโปรแกรมสามารถใชการ Extends MouseInputAdapter แทนการใช Interface MouseListener และ MouseMotionListener ได โปรแกรม MouseMove.java แสดงการใช MouseListener และ MouseMotionListner ในการตรวจสอบการเคลอนไหวและการคลกของของเมาส

import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends Jframe{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width – width)/2,

(screen.height – height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends Jpanel implements MouseListener, MouseMotionListener{

Jlabel label;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

setLayout( new BorderLayout() );

label = new Jlabel(“Please move your mouse”, Jlabel.CENTER);

add(label,BorderLayout.SOUTH);

// เพม MouseListener และ MouseMotionListener โดยใช this คลาสเปน Parameter addMouseListener(this);

addMouseMotionListener(this);

}

// Method จาก MouseListener public void mousePressed (MouseEvent e) {

label.setText(“You are pressing your mouse”);

}

public void mouseReleased (MouseEvent e) {

label.setText(“You have released your mouse”);

}

public void mouseClicked (MouseEvent e){

label.setText(“You‟ve just clicked your mouse”);

}

Page 14: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

268 การเขยนโปรแกรมภาษา Java

// สอง Method นไมไดใชงาน public void mouseEntered (MouseEvent e) {}

public void mouseExited (MouseEvent e) {}

// Method จาก MouseMotionListener public void mouseMoved(MouseEvent e){

// getX() และ getY() ใชดงคา (X, Y) ของเมาสปจจบน label.setText(“X = “ +e.getX() +” Y = “ + e.getY() );

}

// Method นไมไดใชงาน public void mouseDragged(MouseEvent e){}

}

public class MouseMove {

public static void main(String[] args) {

MyFrame frame = new MyFrame(400,400);

frame.setTitle(“Mouse Move”);

MyPanel panel = new MyPanel(“Try to move, click, “ +

“and press your mouse”);

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.8 แสดงผลลพธจากโปรแกรม MouseMove.java Low-Level Events: Key Listener การจบ Event ทเกดจาก Keyboard สามารถใช Listener ตอไปน KeyListener ใชส าหรบดกจบ Event ในกรณผใชงานมการกดปมใดๆ บน Keyboard ซงม Methods ดงตอไปน

public void keyTyped (KeyEvent e) เมอมการพมพ

Page 15: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 269

public void keyPressed (KeyEvent e) เมอกด Shift, Ctrl หรอ Alt public void keyReleased (KeyEvent e) เมอปลอย Key ทกด

เชนเดยวกบการใช WindowAdapter ส าหรบการจดการเรอง Keybaord สามารถใชคลาส KeyAdapter แทนการใช Interface KeyListener ได โปรแกรม KeyResponse.java แสดงการใช KeyListener โดยเมอผใชงานกด Key ใดๆ ผานทาง JTextField ซงเปนชองพมพขอความได โปรแกรมจะแสดง Key ทกดทาง JLabel ดงภาพท 15.9 import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements KeyListener{

JLabel label;

JTextField text_field;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

setLayout( new BorderLayout() );

label = new JLabel("Please type something", JLabel.CENTER);

// สราง JTextField โดยมคา ‚Type here‛ เปนคาเรมตน text_field = new JTextField("Type here");

// ท าใหตวอกษรใน JTextField ถกเลอกเปนแถบส text_field.selectAll();

// เพม KeyListener ให JTextField เพอจบ KeyEvent text_field.addKeyListener(this);

add(text_field, BorderLayout.NORTH);

add(label,BorderLayout.SOUTH);

}

// Method จาก KeyListener // เมอมการกด Key จะแสดงตวอกษรทกดทาง JLabel public void keyTyped (KeyEvent e){

label.setText( "Your typed: "+e.getKeyChar() );

}

// เมอกดปม Shift, Ctrl หรอ Alt public void keyPressed (KeyEvent e){

label.setText("Your pressed: "+ e.getKeyText(e.getKeyCode()));

}

Page 16: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

270 การเขยนโปรแกรมภาษา Java

// Method นไมใชงาน public void keyReleased (KeyEvent e){}

}

public class KeyResponse {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,200);

frame.setTitle("KeyListener");

MyPanel panel = new MyPanel("Try to type something");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.9 แสดงผลลพธจากโปรแกรม KeyResponse Semantic Events Low-Level Events เปนเหตการณทเกดจาก Windows และ Keybaord แต Semantic Events เปน Event ทเกดจากวตถใน GUI เอง เชน การเลอกเมน หรอ การคลกปมตางๆ ประเภทของ Semantic Events แบงเปน 3 แบบคอ

ตารางท 15.1 แสดงชนดของ Event กบ JComponent ชนดของ Event ใชกบ JComponent Method ทตองสรางเมอมการ Implement Interface

ActionEvent เมอมการคลก

JButton, JToggleButton, JCheckBox,JMenuItem, JMenu, JCheckBoxMenuItem, JRadioButtonMenuItem, JTextField, JPasswordField, JComboBox

void actionPerformed(ActionEvent e)

ItemEvent เมอมการเลอก

JButton, JToggleButton, JCheckBox JMenuItem, JMenu,

void itemStateChanged(ItemEvent e)

Page 17: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 271

ชนดของ Event ใชกบ JComponent Method ทตองสรางเมอมการ Implement Interface

JCheckBoxMenuItem, JRadioButtonMenuItem

AdjustmentEvent เมอมการปรบคา

JScrollbar void adjustmentValueChanged(AdjustmentEvent e)

ListSelectionEvent เมอเลอกคาใน List

JList void valueChanged(ListSelectionEvent e)

ChangeListener เมอมเปลยนคา

JSlider void stateChanged(ChangeEvent e)

JButton JButton ท าหนาทรบค าสงจากผใชงานดวยการกด JButton มลกษณะเปนปมซงผใชงานสามารถใชเมาสคลกหรอใช Short-Cut Key ได JButton สามารถบรรจไดทงรปภาพและขอความ ตวอยาง Constructor ของ JButton คอ JButton(String text);

// กรณทตองการให JButton แสดงทงขอความและรปภาพ JButton(String text,Icon icon);

การตงคา Short Cut Key ใหกบ JButton ใชค าสง //คา mnemonic อยในคลาส java.awt.event.KeyEvent public void setMnemonic(int mnemonic)

การตงคา Tool Tip (ปรากฏขอความอธบายขนเมอมการเลอนเมาสไปท JButton) เพอชวยใหผใชงานทราบวาปมนท าหนาทอะไร สามารถใชค าสงตอไปน public void setToolTipText(String text);

ให JButton แสดงรปภาพเมอมการคลก ใชค าสง public void setPressedIcon(Icon pressedIcon);

ให JButton แสดงรปภาพเมอเลอนเมาสผาน ใชค าสง // ควรใชค าสงนกอนเพอให Rollover ท างาน public void setRolloverEnabled(boolean b);

Page 18: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

272 การเขยนโปรแกรมภาษา Java

// เมอ Enable Rollover แลวจงเพมรปภาพใหกบ JButton public void setRolloverIcon(Icon rolloverIcon);

โปรแกรม SetJButton.java แสดงการใชงาน JButton โดยใชค าสงตงคา Tool Tip การเปลยนรป Icon เมอกดปม และแสดงการใชคณสมบต Rollover ของ JButton import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.KeyEvent;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel{

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

setBorder(border);

setLayout(new FlowLayout());

// สราง Icons ตางๆ เพอใชในการสราง JButton ImageIcon point = new ImageIcon("point.gif");

ImageIcon ball = new ImageIcon("ball.gif");

ImageIcon right = new ImageIcon("right.gif");

// สราง Button 1 JButton b1 = new JButton("ToolTip", ball);

// ตงคา Short-Cut key เปน ALT+T b1.setMnemonic(KeyEvent.VK_T);

// ตงคา Tool Tip b1.setToolTipText("This is a tooltip");

// ตงคารปภาพของ Button 1 เมอมการกดปม b1.setPressedIcon(point);

// สราง Button 2 JButton b2 = new JButton("Roll Over", right);

// ตงคาใชงาน Rollover b2.setRolloverEnabled(true);

// ตงคารปภาพของ Rollover b2.setRolloverIcon(point);

// เพม Button 1 และ 2 ไปท JPanel add(b1); add(b2); }

}

Page 19: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 273

public class SetJButton {

public static void main(String[] args) {

MyFrame frame = new MyFrame(400, 100);

frame.setTitle("Test JPanel");

MyPanel panel = new MyPanel("JButton"); frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.19 แสดงผลลพธจากโปรแกรม SetJButton.java การเพมคณสมบตให JButton เพอรองรบการท างานของ Semantic Event ทเกดจากการคลก สามารถท าโดยการ Implement ActionListener Interface (ตารางท 5.1) และตองสราง Method ส าหรบจดการดวย ดงน void actionPerformed(ActionEvent e);

โปรแกรม ShowColor.java แสดงการใช JButton เพอเปลยนส Background ของ JPanel import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import java.util.Random;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ActionListener {

JButton color_button, blue_button, exit_button;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

New EtchedBorder(), name);

setBorder(border);

setLayout(new FlowLayout());

// สราง Icons ImageIcon point = new ImageIcon("point.gif");

ImageIcon ball = new ImageIcon("ball.gif");

Page 20: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

274 การเขยนโปรแกรมภาษา Java

ImageIcon right = new ImageIcon("right.gif");

// สราง Color Button color_button = new JButton("Change backgroud color to red", ball);

// ตงคา Short-Cut Key ALT+R color_button.setMnemonic(KeyEvent.VK_R);

// ตงคา Tool Tip color_button.setToolTipText("Plese click here to

change background color");

// สราง Blue Button blue_button = new JButton("Blue");

// สราง Exit Button exit_button = new JButton("Exit", right);

exit_button.setToolTipText("End program");

// ตงคา Rollover Image exit_button.setRolloverEnabled(true);

exit_button.setRolloverIcon(point);

// เพม ActionListener color_button.addActionListener(this);

blue_button.addActionListener(this);

exit_button.addActionListener(this);

// เพม Button ทงหมดไปท JPanel add(color_button);

add(blue_button);

add(exit_button);

}

// สราง actionPerformed() เพอรองรบการคลก JButton public void actionPerformed(ActionEvent e){

// ค าสง getSource() เพอหาวาผใชงานคลกทปมใด Object button = e.getSource();

if(button == color_button) setBackground(Color.RED);

else if(button == blue_button) setBackground(Color.BLUE);

else System.exit(0);

}

}

public class ShowColor {

public static void main(String[] args) {

MyFrame frame = new MyFrame(500,100);

frame.setTitle("Test JPanel");

MyPanel panel = new MyPanel("JButton");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.20 แสดงการใชงาน ActionEvent กบ JButton

Page 21: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 275

จากโปรแกรม ShowColor.java ในสวน Method actionPerformed(ActionEvent e) มการใชค าสง Object button = e.getSource() เพอตรวจสอบวาผใชงานคลกปมใด โดยคาทสงกลบจากค าสงคอ Pointer Reference ของวตถทใหก าเนด ActionEvent ดงนนในกรณทมปมมากกวาหนงปม ถาอยากทราบวาปมใดถกกด สามารถใชค าสง getSource() และน าคาทไดมาตรวจสอบดวยค าสง if อกครง JCheckBox ในการตอบค าถามทมค าตอบทถกตองหลายคา (Multiple Correct Choices) ซงผสอบจ าเปนตองเลอกค าตอบทถกตองทงหมดจงไดคะแนน การออกแบบ GUI ทมลกษณะแบบนสามารถใช JCheckBox ได รปแบบ Constructor ของ JCheckBox คอ // สราง JCheckBox โดยไมมตวอกษรและรปภาพ JCheckBox();

// สราง JCheckBox โดยใชรปประกอบดวย JCheckBox(Icon icon);

// สราง JCheckBox โดยใชรปประกอบและถกเลอกไวเปนคาเรมตน JCheckBox(Icon icon, boolean selected);

// สราง JCheckBox โดยใชตวอกษรอธบาย JCheckBox(String text);

// สราง JCheckBox โดยใชตวอกษรอธบายและถกเลอกไวเปนคาเรมตน JCheckBox(String text, boolean selected);

// สราง JCheckBox โดยใชตวอกษรและรปภาพ JCheckBox(String text, Icon icon)

// สราง JCheckBox โดยใชตวอกษรและรปภาพและถกเลอกไวเปนคาเรมตน JCheckBox(String text, Icon icon, boolean selected)

จากตารางท 15.1 เมอผใชงานคลกท JCheckBox JVM จะสง ItemEvent ออกมา ถาตองการจบ ItemEvent ตองใชคลาสท Implement ItemListener และตองสราง Method ทชอ public void itemStateChanged(ItemEvent e)

โปรแกรม ShowJCheckBox.java แสดงการใชงาน JCheckBox โดยทถาผใชงานคลกท JCheckBox โปรแกรมจะแสดงวาผใชงานเลอกตวเลอกใด import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import java.util.Random;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

Page 22: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

276 การเขยนโปรแกรมภาษา Java

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ItemListener, ActionListener {

JCheckBox red_check, blue_check, yellow_check, green_check;

JLabel label;

JButton exit_button;

ImageIcon red, blue, yellow, green;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

setBorder(border);

setLayout(new GridLayout(6,1));

// สราง Icons red = new ImageIcon("red.gif");

blue = new ImageIcon("blue.gif");

yellow = new ImageIcon("yellow.gif");

green = new ImageIcon("green.gif");

// สราง JLabel โดยใหคาเรมตนเปน ‚‛ label = new JLabel("");

label.setBorder(BorderFactory.createLineBorder(Color.BLUE));

// สราง JCheckBox ทง 4 ตวเลอก red_check = new JCheckBox("Red");

blue_check = new JCheckBox("Blue");

yellow_check = new JCheckBox("Yellow");

// ให JCheckBox นถกเลอกไว green_check = new JCheckBox("Green", true);

// สราง Exit Button exit_button = new JButton("Exit");

exit_button.setToolTipText("End program");

// เพม ActionListener ใหกบปม Exit exit_button.addActionListener(this);

// เพม ItemListener ให JCheckBox ทง 4 ตวเลอก red_check.addItemListener(this);

blue_check.addItemListener(this);

yellow_check.addItemListener(this);

green_check.addItemListener(this);

// เพม JLabel และ JCheckBox รวมทง JButton ดวย add(label);

add(red_check);

add(blue_check);

add(yellow_check);

add(green_check);

add(exit_button);

}

public void itemStateChanged(ItemEvent e){

Object source = e.getItemSelectable();

if (source == red_check) {

label.setText("You have've checked red");

label.setIcon(red);

} else if (source == blue_check) {

Page 23: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 277

label.setText("You have've checked blue");

label.setIcon(blue);

} else if (source == yellow_check) {

label.setText("You have've checked yellow");

label.setIcon(yellow);

} else if (source == green_check) {

label.setText("You have've checked green");

label.setIcon(green);

}

if (e.getStateChange() == ItemEvent.DESELECTED) {

label.setText("You should select one choice");

}

}

public void actionPerformed(ActionEvent e) {

System.exit(0);

}

}

public class ShowJCheckBox {

public static void main(String[] args) {

MyFrame frame = new MyFrame(250,200);

frame.setTitle("Test JPanel");

MyPanel panel = new MyPanel("JCheckBox");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.21แสดงผลลพธจากโปรแกรม ShowJCheckBox.java JRadioButton JRadioButton มรปรางเปนชองวงกลม เหตผลทใชค าวา Radio เนองจากการท างานคลายปมเลน หยด หรอ กรอเทป ของเครองเลนเทปเพลง คอผใชงานสามารถเลอกปมใหท างานไดปมเดยวเทานน เชนถาเลอกปมหยดเทป ปมเลนเทปจะกระเดงขน ดงนนปม JRadioButton ออกแบบมาใหผใชงานเลอกเพยงตวเลอกเดยวเทานนในชวงเวลาหนง JRadioButton ตองใชคกบ ButtonGroup เพอรวมปม JRadioButton ไวดวยกน ถาไมใช ButtonGroup ส าหรบควบคม JRadioButton จะท างานเหมอนกบ JCheckBox ทกประการ รปแบบ Constructor ของ JRadioButton คลายของ JCheckBox คอ

Page 24: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

278 การเขยนโปรแกรมภาษา Java

JRadioButton();

JRadioButton(Icon icon);

JRadioButton(Icon icon, boolean selected);

JRadioButton(String text);

JRadioButton(String text, boolean selected);

JRadioButton(String text, Icon icon);

JRadioButton(String text, Icon icon, boolean selected);

โปรแกรม ShowJRadioButton.java แสดงการเปลยนส Background ของ JPanel โดยผใชงานเลอกเปลยนสของ JPanel ไดเพยงสเดยวตอครงเทานน import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import java.util.Random;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ActionListener {

JRadioButton red_radio, blue_radio, yellow_radio, green_radio;

JButton exit_button;

ImageIcon red, blue, yellow, green;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

setLayout(new FlowLayout());

red = new ImageIcon("red.gif");

blue = new ImageIcon("blue.gif");

yellow = new ImageIcon("yellow.gif");

green = new ImageIcon("green.gif");

// สราง JRadioButton ทง 4 ส โดยใหคาเรมตนเลอกทสเขยว red_radio = new JRadioButton("Red");

blue_radio = new JRadioButton("Blue");

yellow_radio = new JRadioButton("Yellow");

green_radio = new JRadioButton("Green", true);

// สราง ButtonGroup ใชในการรวมกลม JRadioButton ทสรางขน ButtonGroup group = new ButtonGroup();

group.add(red_radio);

group.add(blue_radio);

group.add(yellow_radio);

group.add(green_radio);

// สราง Exit button exit_button = new JButton("Exit");

exit_button.setToolTipText("End program");

Page 25: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 279

// เพม ActionListener ใหกบ Exit Button exit_button.addActionListener(this);

// เพม ActionListener ใหกบ JRadioButton red_radio.addActionListener(this);

blue_radio.addActionListener(this);

yellow_radio.addActionListener(this);

green_radio.addActionListener(this);

// เพม JComponent ทงหมดไปท JPanel add(red_radio);

add(blue_radio);

add(yellow_radio);

add(green_radio);

add(exit_button);

}

public void actionPerformed(ActionEvent e) {

Object select = e.getSource();

if(select == red_radio) setBackground(Color.RED);

else if(select == blue_radio) setBackground(Color.BLUE);

else if(select == yellow_radio) setBackground(Color.YELLOW);

else if(select == green_radio) setBackground(Color.GREEN);

else if(select == exit_button) System.exit(0);

}

}

public class ShowJRadioButton {

public static void main(String[] args) {

MyFrame frame = new MyFrame(300,150);

frame.setTitle("Test JRadioButton");

MyPanel panel = new MyPanel("JRadioButton");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.22 แสดงผลลพธจากโปรแกรม ShowJRadioButton.java

Text Component การท างานลกษณะ GUI บางครงเกยวของกบการแสดงผลตวอกษร เชนโปรแกรม Word Processing ดงนนการจดการขอมลทเปนตวอกษรนน เปนสงทหลกเลยงไมได การจดการตวอกษรใน GUI ใชคลาส JTextComponent โดยมคลาสลกแสดงในภาพท 15.23

Page 26: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

280 การเขยนโปรแกรมภาษา Java

ภาพท 15.23 แสดงโครงสรางของ JTextComponent

JTextField และ JPasswordField มหนาทรบขอมลตวอกษรจ านวนไมมากและไมเกนหนงบรรทด มการท างานคลายกบ JButton ซงผเขยนโปรแกรมสามารถควบคมการท างานของ JTextField และ JPasswordField ได เชนสงงานใหโปรแกรมตรวจสอบขอมลวาถกตองโดยทนท เมอผใชงานปอนขอมลเสรจ ทง JTextField และ JPasswordField มการสง ActionEvent ดงนนจ าเปนตองสราง Method actionPerformed(ActionEvent e) ดวยเพอรองรบการท างานของ ActionEvent การปอนขอมลตวอกษรทมมากกวาหนงบรรทดสามารถใช JTextArea คกบ JScrollPane ไดในกรณทไมสามารถแสดงขอมลไดทงหมด ถาตองการใหแสดงขอมลชนด HTML และรปภาพตางๆ สามารถใชคลาส JEditorPane และ JTextPane ได โปรแกรม ShowJTextField.java แสดงการใชงาน JTextField และ JPasswordField จ าลองการเขาสระบบ import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ActionListener{

JButton ok_button, exit_button;

JTextField account_text;

JPasswordField pass_text;

JLabel account_label, pass_label, result_label;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

// ตงคา GridLayout ขนาด 4 rows 2 cols setLayout(new GridLayout(4, 2));

// สราง JLabel ตางๆ account_label = new JLabel("Account name (try java)");

pass_label = new JLabel("Password (try test)");

result_label = new JLabel("");

JTextComponent

JTextFiled JPasswordField JTextArea

JEditorPane JTextPane

Page 27: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 281

result_label.setBorder(BorderFactory.createLineBorder(Color.BLUE));

// สราง JTextField จ านวน 10 columns เพอจ าลองการปองชอ Login account_text = new JTextField("Type your account here");

// ท า Hightlight ตวอกษร account_text.selectAll();

pass_text = new JPasswordField("");

// สราง Exit Button exit_button = new JButton("Exit");

// ตงคา Short-cut Key ALT+E exit_button.setMnemonic(KeyEvent.VK_E);

// ตงคา Tool Tip exit_button.setToolTipText("Click here to end the program");

// สราง OK Button ok_button = new JButton("OK");

// เพม ActionListener ใหปมตางๆ ok_button.addActionListener(this);

exit_button.addActionListener(this);

// เพม Jcomponent ทงหมดไปท JPanel add(account_label);

add(account_text);

add(pass_label);

add(pass_text);

add(ok_button);

add(exit_button);

add(result_label);

}

public void actionPerformed(ActionEvent e) {

Object button = e.getSource();

if(button == ok_button) {

String tmp = new String( pass_text.getPassword() );

if( account_text.getText().equals("java") && tmp.equals("test") ) {

result_label.setText("OK you can log in");

}

else {

result_label.setText("Don't try to hack it");

account_text.selectAll();

}

}

// จบการท างานเมอกดปม Exit Button else System.exit(0);

}

}

public class ShowJText {

public static void main(String[] args) {

MyFrame frame = new MyFrame(300,150);

frame.setTitle("Test JTextField");

MyPanel panel = new MyPanel("JTextField");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

Page 28: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

282 การเขยนโปรแกรมภาษา Java

ภาพท 15.24 แสดงผลลพธจากโปรแกรม ShowJTextField.java โปรแกรมตอไป ShowJTextArea.java แสดงการใชงาน JTextArea ส าหรบแสดงขอความทมจ านวนมากกวาหนงบรรทด import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ActionListener {

JTextField text;

JTextArea text_area;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

setLayout(new BorderLayout());

// สราง JTextField จ านวน 10 columns text = new JTextField("Type here");

// ท า Hightlight ตวอกษร text.selectAll();

// สราง JTextArea text_area = new JTextArea();

/* เพม ActionListener ใหกบ JTextField เมอผใชงานพมพขอความและกดปม Enter Method actionPerform() ถาถกเรยกใหท างาน */ text.addActionListener(this);

// เพม Jcomponent ไปท JPanel add(text,BorderLayout.NORTH);

Page 29: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 283

add(text_area, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

Object src = e.getSource();

if(src == text) {

// เมอผใชงานกด Enter ขอความทปอนใน JTextField // จะถกเพมไปท JTextArea text_area.append( text.getText() +'\n' );

text.selectAll();

}

}

}

public class ShowJTextArea {

public static void main(String[] args) {

MyFrame frame = new MyFrame(300,200);

frame.setTitle("Test JTextArea");

MyPanel panel = new MyPanel("JTextArea");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.25 แสดงผลลพธจากโปรแกรม ShowJTextArea.java JScrollPane จากภาพท 15.25 ในกรณทมขอความจ านวนหลายบรรทด ท าใหไมสามารถมองเหนขอความทงหมดใน JTextArea ดงนนเพอใหผใชงานสามารถมองเหนขอมลไดทกสวนใน JTextArea สามารถใชคลาส JScrollPane ซงมลกษณะเปน Scroll ทเลอนไปมาไดโดยใชเมาสคลกทปม Scroll โปรแกรม ShowJScrollPane.java ไดปรบปรงโปรแกรม ShowJTextArea.java โดยเพม JScrollPane เพอท าใหมองเหนขอมลไดทงหมด import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Page 30: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

284 การเขยนโปรแกรมภาษา Java

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ActionListener {

JTextField text;

JTextArea text_area;

JScrollPane scroll;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

setLayout(new BorderLayout());

text = new JTextField("Type here");

text.selectAll();

text_area = new JTextArea();

// สราง JScrollPane เพอบรรจ JTextArea scroll = new JScrollPane(text_area);

text.addActionListener(this);

add(text,BorderLayout.NORTH);

add(scroll, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

Object src = e.getSource();

if(src == text) {

text_area.append( text.getText() +‟\n‟ );

text.selectAll();

}

}

}

public class ShowJScrollPane {

public static void main(String[] args) {

MyFrame frame = new MyFrame(300,200);

frame.setTitle(“Test JscrollPane”);

MyPanel panel = new MyPanel(“JscrollPane”);

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.26 แสดงการใช JScrollPane

Page 31: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 285

การสราง JMenuBar และ JMenu การสราง Menu ใหกบ Windows ใชคลาส JMenuBar และ JMenu ซง JMenu สามารถบรรจ JMenuItem, JMenuCheckBoxMenuItem และ JRadioButtonMenuItem ไดดวยดงรป

ภาพท 15.27 แสดงชนดของ Menu

การเพมเมนให Windows มขนตอนดงตอไปน

1. สราง Menu Bar โดยใชคลาส JMenuBar และค าสง setJMenuBar() เพอใหแสดง Menu Bar บน Windows

2. สรางเมนหลกทแสดงบน JMenuBar โดยใชคลาส JMenu 3. สรางเมนยอยโดยใชคลาส JMenuItem และเพมใน JMenu 4. ส าหรบการสราง Checkbox Menu ใชคลาส JCheckboxMenuItem 5. การสราง Radio Menu ใชคลาส JRadioButtonMenuItem และจ าเปนตองใชคลาส ButtonGroup

ประกอบดวย เพอใหเมนทเปน Radio อยรวมกน เพราะ Radio Menu สามารถเลอกใชงานไดเพยงเมนเดยวเทานน

โปรแกรม CreateMenu.java แสดงการสราง Menu โดยผลลพธแสดงในภาพท 15.27 import java.awt.*;

import javax.swing.*;

class MenuFrame extends JFrame {

private JMenuBar menuBar;

JCheckBoxMenuItem

JMenuBar

JMenu

JMenuItem

JMenu

JRadioButtonMenuItem

Page 32: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

286 การเขยนโปรแกรมภาษา Java

private JMenu fileMenu, choicesMenu, colorMenu;

private JMenuItem newItem, openItem, closeItem, saveItem, printItem, exitItem,

recommendItem;

private JCheckBoxMenuItem audiCheck, bmwCheck, toyotaCheck,

hondaCheck;

private JRadioButtonMenuItem redRadio, blueRadio, blackRadio

public MenuFrame (int width, int height){

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

// สราง MenuBar menuBar = new JMenuBar();

// ตงคาให Windows แสดง MenuBar setJMenuBar(menuBar);

// เรยก Method addMenuFile() เพอตงคาตางๆ ให Menu File addMenuFile();

// เพม File Menu ใน MenuBar menuBar.add(fileMenu);

// เรยก Method addMenuChoices() เพอตงคาตางๆ ให Menu Choices addMenuChoices();

// เพม Choice Menu ใน MenuBar menuBar.add(choicesMenu);

}

// Method นใชในการตงคาตางๆ ให Menu File private void addMenuFile() {

fileMenu = new JMenu("File"); //สราง File Menu

newItem = fileMenu.add("New"); //เพม menu item

fileMenu.addSeparator(); //เพมเสนแบง Menu

openItem = fileMenu.add("Open..."); //เพม menu item

closeItem = fileMenu.add("Close"); //เพม menu item

saveItem = fileMenu.add("Save"); //เพม menu item

printItem = fileMenu.add("Print..."); //เพม menu item

// เปลยนให Menu Print อยในสถานะทใชงานไมได printItem.setEnabled(false);

fileMenu.addSeparator(); //เพมเสนแบง Menu

exitItem = fileMenu.add("Exit"); //เพม New menu item

}

// Method นใชในการตงคาตางๆ ให Menu Choices private void addMenuChoices() {

choicesMenu = new JMenu("Choices"); //สราง Choices Menu //เพม menu item recommendItem = choicesMenu.add("Recommend...");

choicesMenu.addSeparator(); //เพมเสนแบง Menu

Page 33: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 287

// เพม Checkbox menu item choicesMenu.add( audiCheck= new JCheckBoxMenuItem("Audi", true) );

choicesMenu.add( bmwCheck=new JCheckBoxMenuItem("BMW", true) );

choicesMenu.add( toyotaCheck = new JCheckBoxMenuItem("Toyota") );

choicesMenu.add( hondaCheck = new JCheckBoxMenuItem("Honda") );

// สราง Color menu colorMenu = new JMenu("Color");

choicesMenu.addSeparator();

// เพม Color menu ในเมน Choices choicesMenu.add(colorMenu);

// สราง ButtonGroup เพอท าให Radio button อยรวมกน // ท าใหมเมนเดยวเทานนทถกเลอกได ButtonGroup group = new ButtonGroup();

group.add(redRadio = new JRadioButtonMenuItem ("Red") );

group.add(blueRadio = new JRadioButtonMenuItem ("Blue") );

group.add(blackRadio = new JRadioButtonMenuItem ("Black", true) );

// เพม Radio ไปทเมน Color colorMenu.add(redRadio);

colorMenu.add(blueRadio);

colorMenu.add(blackRadio);

}

}

// Main Program

public class CreateMenu{

public static void main(String[] args) {

MenuFrame frame = new MenuFrame(400,200);

frame.setVisible(true);

}

}

การสราง Short-Cut Key ให Menu การเลอกเมนในระบบ Windows ในกรณทไมใชเมาสคลกโดยตรง สามารถใชปม ALT คกบปมตวอกษรได เรยกวา การตงคา Short-Cut Key ใหเมน ซงสามารถใชค าสง setMnemonic(int mnemonic) คา mnemonic อยในคลาส java.awt.event.KeyEvent ตวอยางของ KeyEvent คอ KeyEvent.VK_A หมายถงตวอกษร ‘A’ ตวอกษร VK มาจากค าวา Virtual Key ดงนนถาตองการตงคา Short-Cut Key ใหกบเมน File และ Choices ตองเพมค าสงดงตอไปนในโปรแกรม CreateMenu.java ทผานมา import java.awt.event.KeyEvent;

setJMenuBar(menuBar);

addMenuFile();

fileMenu.setMnemonic(KeyEvent.VK_F);

menuBar.add(fileMenu); // เพม File Menu ใน MenuBar addMenuChoices();

choicesMenu.setMnemonic(KeyEvent.VK_C);

menuBar.add(choicesMenu); // เพม Choice Menu ใน MenuBar …

Page 34: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

288 การเขยนโปรแกรมภาษา Java

ภาพท 15.28 แสดง Short Cut Key ใหบน JMenuBar

การเพม Short-Cut Key ใหกบ MenuItem เชน การกดปม ‚Ctrl + N‛ สามารถใชค าสง setAccelerator(KeyStroke keyStroke) โดยคา keyStroke สามารถใชคาคงทในคลาส java.awt.Event ได เชนคาปม Ctrl คอ CTRL_MARK ตวอยางการใชค าสง setAccelerator() คอ newItem.setAccelerator(KeyStroke.getKeyStroke(„N‟, Event.CTRL_MASK));

openItem.setAccelerator(KeyStroke.getKeyStroke(„O‟, Event.CTRL_MASK));

น าโปรแกรม CreateMenu.java แกไขใหมโดยเพม Short-Cut Key ดงตวอยาง private void addMenuFile() {

fileMenu = new JMenu("File"); // สราง File Menu

newItem = fileMenu.add("New"); // เพม menu item

newItem.setAccelerator(KeyStroke.getKeyStroke('N', Event.CTRL_MASK));

fileMenu.addSeparator(); // เพมเสนแบง Menu

openItem = fileMenu.add("Open..."); // เพม menu item

openItem.setAccelerator(KeyStroke.getKeyStroke('O', Event.CTRL_MASK));

closeItem = fileMenu.add("Close"); // เพม menu item

closeItem.setAccelerator(KeyStroke.getKeyStroke('C', Event.CTRL_MASK));

saveItem = fileMenu.add("Save"); // เพม menu item

saveItem.setAccelerator(KeyStroke.getKeyStroke('S', Event.CTRL_MASK));

printItem = fileMenu.add("Print..."); // เพม menu item

printItem.setAccelerator(KeyStroke.getKeyStroke('P', Event.CTRL_MASK));

printItem.setEnabled(false); // เปลยนให Menu Print อยในสถานะทใชงานไมได fileMenu.addSeparator(); // เพมเสนแบง Menu

exitItem = fileMenu.add("Exit"); // เพม New menu item

}

ภาพท 15.29 แสดง Short-Cut Key ของ Menu

Page 35: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 289

การใส Icon ใหกบ Menu การเพม Icon ใหกบ Menu สามารถท าไดโดยระบรปภาพ Icon ใน Constructor ตอนทสราง JMenuItem ตวอยางตอไปไดน าโปรแกรม CreateMenu.java มาแกไขโดยเปลยนค าสงใน Method addMenuFile() ตามแถบสเขมดงโปรแกรมขางลาง โดยใหระบชอของแฟมขอมลทเปนรปภาพ ในตวอยางระบเปน ‚open.jpg‛ private void addMenuFile() {

fileMenu = new JMenu("File"); // สราง File Menu

newItem = fileMenu.add("New"); // เพม menu item

newItem.setAccelerator(KeyStroke.getKeyStroke('N', Event.CTRL_MASK));

fileMenu.addSeparator(); // เพมเสนแบง Menu

openItem = new JMenuItem("Open", new ImageIcon("open.jpg"));

fileMenu.add(openItem);

openItem.setAccelerator(KeyStroke.getKeyStroke('O', Event.CTRL_MASK));

closeItem = fileMenu.add("Close"); // เพม menu item

closeItem.setAccelerator(KeyStroke.getKeyStroke('C', Event.CTRL_MASK));

saveItem = fileMenu.add("Save"); // เพม menu item

saveItem.setAccelerator(KeyStroke.getKeyStroke('S', Event.CTRL_MASK));

printItem = fileMenu.add("Print..."); // เพม menu item

printItem.setAccelerator(KeyStroke.getKeyStroke('P', Event.CTRL_MASK));

printItem.setEnabled(false); // เปลยนให Menu Print อยในสถานะทใชงานไมได fileMenu.addSeparator(); // เพมเสนแบง Menu

exitItem = fileMenu.add("Exit"); // เพม New menu item

}

ภาพท 15.30 แสดงการใสรป Icon ใหกบเมน

การจดการเมน (Menu Event) วธการรองรบการท างานของ Event ทเกดจาก JMenuItem, JRadioButtonMenuItem และ JCheckBoxMenuItem เมอผใชงานเลอก Menu มรปแบบดงตอไปน

Page 36: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

290 การเขยนโปรแกรมภาษา Java

public class ShowMenu implements ActionListener, ItemListener {

...

public ShowMenu() {

// เพม Action Listener ใหกบเมน MenuItem menu_item.addActionListener(this);

...

/ /สวน JRadioButtonMenuItem ใช Action Listener เหมอนกบ JMenuItem radio_menu.addActionListener(this);

...

// ส าหรบ JCheckBoxMenuItem ใช Item Listener เหมอนในตวอยางการใช JCheckBox check_menu.addItemListener(this);

...

}

public void actionPerformed(ActionEvent e) {

// ใชค าสง getSource() เพอหาวาเกดจาก MenuItem ใด MenuItem src = (MenuItem) e.getSource();

}

public void itemStateChanged(ItemEvent e) {

// ใชค าสง getSource() เพอหาวาเกดจาก JCheckBoxsMenuItem ใด JCheckBoxMenuItem src = (JCheckBoxMenuItem) e.getSource(); }

ปรบปรงโปรแกรม CreateMenu.java โดยเพมโปรแกรมในสวนทจดการในเรองของ Event และเปลยนชอโปรแกรมเปน ShowJMenu.java ซงแสดงการจดการเรองของ Menu อยางสมบรณ import java.awt.*;

import java.awt.event.KeyEvent;

import java.awt.event.*;

import javax.swing.*;

class MenuFrame extends JFrame implements ActionListener, ItemListener {

private JMenuBar menuBar;

private JMenu fileMenu, choicesMenu, colorMenu;

private JMenuItem newItem, openItem,

closeItem, saveItem, printItem, exitItem, recommendItem;

private JCheckBoxMenuItem audiCheck,

bmwCheck, toyotaCheck, hondaCheck;

private JRadioButtonMenuItem redRadio, blueRadio, blackRadio;

private JTextArea text;

public MenuFrame (int width, int height){

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setTitle("Test Menu");

// สราง MenuBar menuBar = new JMenuBar();

// ตงคาให Windows แสดง MenuBar setJMenuBar(menuBar);

addMenuFile();

Page 37: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 291

fileMenu.setMnemonic(KeyEvent.VK_F);

menuBar.add(fileMenu); // เพม File Menu ใน MenuBar addMenuChoices();

choicesMenu.setMnemonic(KeyEvent.VK_C);

menuBar.add(choicesMenu); // เพม Choice Menu ใน MenuBar // สราง JTextArea ส าหรบแสดงผลลพธจากการเลอกเมนตางๆ text = new JTextArea();

JScrollPane scroll = new JScrollPane(text);

getContentPane().add(scroll);

}

private void addMenuFile() {

fileMenu = new JMenu("File"); // สราง File Menu

newItem = fileMenu.add("New"); // เพม menu item

newItem.setAccelerator(

KeyStroke.getKeyStroke('N', Event.CTRL_MASK));

fileMenu.addSeparator(); // เพมเสนแบง Menu

openItem = new JMenuItem("Open", new ImageIcon("open.jpg"));

fileMenu.add(openItem); // เพม menu item

openItem.setAccelerator(

KeyStroke.getKeyStroke('O', Event.CTRL_MASK));

closeItem = fileMenu.add("Close"); // เพม menu item

closeItem.setAccelerator(

KeyStroke.getKeyStroke('C', Event.CTRL_MASK));

saveItem = fileMenu.add("Save"); // เพม menu item

saveItem.setAccelerator(

KeyStroke.getKeyStroke('S', Event.CTRL_MASK));

printItem = fileMenu.add("Print..."); // เพม menu item

printItem.setAccelerator(

KeyStroke.getKeyStroke('P', Event.CTRL_MASK));

// เปลยนให Menu Print อยในสถานะทใชงานไมได printItem.setEnabled(false);

fileMenu.addSeparator(); // เพมเสนแบง Menu

exitItem = fileMenu.add("Exit"); // เพม New menu item

// เพม ActionListener ใหกบ MenuItem newItem.addActionListener(this);

openItem.addActionListener(this);

closeItem.addActionListener(this);

saveItem.addActionListener(this);

printItem.addActionListener(this);

exitItem.addActionListener(this);

}

private void addMenuChoices() {

choicesMenu = new JMenu("Choices"); // สราง Choices Menu

// เพม menu item recommendItem = choicesMenu.add("Recommend...");

// เพมเสนแบง Menu

choicesMenu.addSeparator();

Page 38: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

292 การเขยนโปรแกรมภาษา Java

// เพม Checkbox menu item choicesMenu.add( audiCheck = new

JCheckBoxMenuItem("Audi", true) );

choicesMenu.add( bmwCheck = new

JCheckBoxMenuItem("BMW", true) );

choicesMenu.add( toyotaCheck = new JCheckBoxMenuItem("Toyota") );

choicesMenu.add( hondaCheck = new JCheckBoxMenuItem("Honda") );

// สราง Color menu colorMenu = new JMenu("Color");

choicesMenu.addSeparator();

// เพม Color menu ในเมน Choices choicesMenu.add(colorMenu);

// สราง ButtonGroup เพอท าให Radio button อยรวมกน // ท าใหมเมนเดยวเทานนทถกเลอก ButtonGroup group = new ButtonGroup();

group.add(redRadio = new JRadioButtonMenuItem ("Red") );

group.add(blueRadio = new JRadioButtonMenuItem ("Blue") );

group.add(blackRadio = new JRadioButtonMenuItem ("Black", true) );

// เพม Radio ไปทเมน Color colorMenu.add(redRadio);

colorMenu.add(blueRadio);

colorMenu.add(blackRadio);

// เพม ActionListener ใหกบ CheckBoxMenu audiCheck.addActionListener(this);

bmwCheck.addActionListener(this);

toyotaCheck.addActionListener(this);

hondaCheck.addActionListener(this);

//เพม ItemListener ใหกบ RadioButtonMenu redRadio.addItemListener(this);

blueRadio.addItemListener(this);

blackRadio.addItemListener(this);

}

public void actionPerformed(ActionEvent e) {

// ใชค าสง getSource() เพอหาวาเกดจาก MenuItem ใด JMenuItem src = (JMenuItem) e.getSource();

if(src == newItem) text.append("You selected New\n");

else if(src == openItem) text.append("You selected Open\n");

else if(src == closeItem) text.append("You selected Close\n");

else if(src == saveItem) text.append("You selected Save\n");

else if(src == printItem) text.append("You selected Print\n");

else if(src == exitItem) System.exit(0);

// ส าหรบตรวจสอบการเลอก JCheckBoxMenuItem else if(src == audiCheck) {

JCheckBoxMenuItem tmp = (JCheckBoxMenuItem) src;

if(tmp.getState()) text.append("You picked Audi\n");

}

else if(src == bmwCheck) {

JCheckBoxMenuItem tmp = (JCheckBoxMenuItem) src;

if(tmp.getState()) text.append("You picked BMW\n");

}

else if(src == toyotaCheck) {

Page 39: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 293

JCheckBoxMenuItem tmp = (JCheckBoxMenuItem) src;

if(tmp.getState()) text.append("You picked Toyota\n");

}

else if(src == hondaCheck) {

JCheckBoxMenuItem tmp = (JCheckBoxMenuItem) src;

if(tmp.getState()) text.append("You picked Honda\n");

}

}

public void itemStateChanged(ItemEvent e) {

// ใชค าสง getSource() เพอหาวาเกดจาก JCheckBoxsMenuItem ใด JRadioButtonMenuItem src = (JRadioButtonMenuItem) e.getSource();

if(src == redRadio) {

text.setForeground(Color.YELLOW);

text.setBackground(Color.RED);

}

else if(src == blueRadio){

text.setForeground(Color.YELLOW);

text.setBackground(Color.BLUE);

}

else{

text.setForeground(Color.YELLOW);

text.setBackground(Color.BLACK);

}

}

}

public class ShowJMenu{

public static void main(String[] args) {

MenuFrame frame = new MenuFrame(400,200);

frame.setVisible(true);

}

}

ภาพท 15.31 แสดงผลลพธจากโปรแกรม ShowJMenu การใช Mouse เพอวาดรป โปรแกรมตอไปแสดงการจบ Event จากเมาสเมอผใชงานกดปมเมาสคางไวพรอมทงเลอนเมาสไปจดทตองการ จะเกดเสนสด าตามเมาสทเลอนไป ดงโปรแกรม MousePaint.java ทแสดงวธการดกจบสญญาณจากเมาส โดยใช MouseListener Interface และ MouseMotionListener Interface

Page 40: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

294 การเขยนโปรแกรมภาษา Java

import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements MouseListener, MouseMotionListener{

JLabel label;

// เกบคาจด (x, y) ของเมาสกอนหนาทจะเลอนเมาส int cx, cy;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

setBorder(border);

setLayout( new BorderLayout() );

label = new JLabel("", JLabel.CENTER);

add(label,BorderLayout.SOUTH);

// เพม MouseListener และ MouseMotionListenter addMouseListener(this);

addMouseMotionListener(this);

}

// เกบคาเรมตน (x, y) เมอผใชงานกดปม Mouse public void mousePressed (MouseEvent e) {

cx=e.getX();

cy =e.getY();

}

public void mouseReleased (MouseEvent e) {}

public void mouseClicked (MouseEvent e){}

public void mouseEntered (MouseEvent e) {}

public void mouseExited (MouseEvent e) {}

public void mouseMoved(MouseEvent e){}

// เมอผใชงานเคลอนเมาสใหแสดงเสนโดยใชค าสง drawLine() public void mouseDragged(MouseEvent e){

Graphics g = getGraphics();

int x = e.getX();

int y = e.getY();

g.drawLine(cx, cy, x, y );

// เกบคา (x, y) ไปไวท cx และ cy ตามล าดบ cx = x; cy=y;

}

}

public class MousePaint {

public static void main(String[] args) {

MyFrame frame = new MyFrame(400,400);

frame.setTitle("Draw picture");

MyPanel panel = new MyPanel("Try to press and drag your mouse");

frame.getContentPane().add(panel);

Page 41: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 295

frame.setVisible(true);

}

}

ภาพท 15.32 แสดงผลลพธจากโปรแกรม MousePaint.java JComboBox JComboBox มลกษณะเปนตวเลอกใหผใชงานคลก โดยแสดงตวเลอกในหนงบรรทด และเมอผใชงานน าเมาสคลก จะปรากฏตวเลอกเปนลกษณะ Drop List

วตถประสงคการใชงาน JComboBox เพอตองการประหยดพนทในการแสดงตวเลอกทมจ านวนมาก ตวเลอกจะไมแสดงทงหมดจนกระทงผใชงานคลกท JComboBox และผใชงานสามารถเลอกตวเลอกไดเพยงตวเลอกเดยวเทานน โปรแกรม ShowJComboBox.java แสดงการใชงาน JComboBox import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ActionListener{

JComboBox choice;

JLabel pictureLabel;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

Page 42: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

296 การเขยนโปรแกรมภาษา Java

setBorder(border);

// ตงคา Layout ของ JPanel ใหเปน Border Layout setLayout( new BorderLayout() );

// สราง Array ของ Strings เพอใชเปนตวเลอก String[] listStrings = {"tweety.gif", "typing.gif","sun.gif",

"plamtree.gif","circle.gif"};

// สราง JLabel ส าหรบแสดงภาพทเลอก // โดยตงคาตวเลอกเรมตนเปน tweety.gif pictureLabel = new JLabel( new ImageIcon(listStrings[0]) ,

JLabel.CENTER);

// เพมตวเลอกใหกบ Combo Box choice= new JComboBox(listStrings);

// แสดงคาตวเลอกตวแรกหรอ index ต าแหนงท 0 choice.setSelectedIndex(0);

// เพม ActionListener ใหกบ JComboBox choice.addActionListener(this);

// เพม JLabel และ JComboBox ไปท JPanel add(pictureLabel, BorderLayout.CENTER);

add(choice, BorderLayout.SOUTH);

}

public void actionPerformed(ActionEvent e) {

// หาชอของภาพ เมอผใชงานมการเลอกตวเลอก String name = (String) choice.getSelectedItem();

// แสดงภาพทเลอกทาง JLabel pictureLabel.setIcon(new ImageIcon(name) );

}

}

public class ShowJComboBox {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,300);

frame.setTitle("Test JComboBox");

MyPanel panel = new MyPanel("Combo Box");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

Page 43: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 297

ภาพท 15.33 แสดงผลลพธจากโปรแกรม ShowJComboBox.java JList คลาส JList ใชในการแสดงตวเลอกหลายตวเลอกเปนลกษณะคอลมนยาวลงมา ผเขยนโปรแกรมสามารถก าหนดใหผใชงานเลอกตวเลอกไดครงละหลายตวเลอก ซงตางจาก JComboBox ซงเลอกไดเพยงตวเลอกเดยวเทานน การใชงาน JList ตองใหคลาสทเรยกใช JList ท าการ implements ListSectionListener (ดงตารางท 15.1) และตองสราง Method ชอ valueChanged() เพอรองรบการท างานเมอผใชงานมการเลอกขอมลจาก JList public void valueChanged(ListSelectionEvent e);

การก าหนดใหผใชงานสามารถเลอกขอมลใน JList ไดมากกวาหนงขอมล สามารถท าไดโดยใชค าสง setSelectionMode(int selectionMode) คา int selectionMode น ามาจากคลาส javax.swing.ListSeclectionModel ซงเปน Interface Class ใน Package javax.swing.event ม 3 คาคอ เลอกตวเลอกไดเพยงคาเดยว - javax.swing.ListSelectionModel.SINGLE_SELECTION

เลอกตวเนองแบบตอเนองโดยใชปม Shift ชวย - javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION

เลอกตวเลอกแบบตอเนอง (ปม Shift) และไมตอเนองโดยใชปม Ctrl ชวยได - javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION

หมายเหต คา MULTIPLE_INTERVAL_SELECTION เปนคาเรมตน ในกรณทไมไดมการตงคาของ Selection Mode โปรแกรม JList1.java แสดงการเปลยนสพนหลง โดยใช Selection Mode เปน

Page 44: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

298 การเขยนโปรแกรมภาษา Java

SINGLE_SELECTION ซงอนญาตใหผใชงานเลอกขอมลจาก JList ไดเพยงคาเดยวเทานน ในกรณทมขอมลอยใน JList เปนจ านวนมาก คลาส JScrollPane สามารถน ามาชวยในการบรรจ JList ไดอกดวย import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import javax.swing.event.*; // ส าหรบ ListSelectionEvent Class class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ListSelectionListener{

// ตวแปร JList ส าหรบใหผใชงานเลอกสทตองการ private JList colorSelected;

// ตวแปร listColor ส าหรบใชในการระบสใหกบ JPanel private Color[] listColor = {Color.black, Color.blue, Color.cyan,

Color.darkGray, Color.gray, Color.magenta,Color.orange, Color.pink, Color.red, Color.white, Color.yellow};

// ตวแปร listStrings เปนขอมลส าหรบแสดงใน JList private String[] listStrings = {"Black", "Blue", "Cyan", "Dark Gray", "Gray", "Magenta", "Orange", "Pink", "Red",

"White", "Yellow"};

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder (

new EtchedBorder(), name);

setBorder(border);

// ตงคา Layout Manager เปน FlowLayout setLayout( new FlowLayout() );

// สราง colorSelected โดยใชคา listStrings เปนขอมลใน JList colorSelected= new JList(listStrings);

// ใหแสดงขอมลเพยง 5 แถวเทานน colorSelected.setVisibleRowCount(5);

// ตงคา Mode เปนชนดทอนญาตใหเลอกเพยงตวเลอกเดยว colorSelected.setSelectionMode(

ListSelectionModel.SINGLE_SELECTION);

// เพม ListSelectionListener ส าหรบการดกจบ Event // เมอมการเลอกคาใน JList colorSelected.addListSelectionListener(this);

// สราง JScrollPane เพอบรรจ JList JScrollPane scroll = new JScrollPane(colorSelected);

add(scroll);

}

public void valueChanged(ListSelectionEvent e) {

Page 45: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 299

// หาต าแหนงทผใชงานคลกเลอก int i = colorSelected.getSelectedIndex();

// เปลยนสพนหลงของ JPanel setBackground( listColor[i] );

}

}

public class JList1 {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,200);

frame.setTitle("Test JList");

MyPanel panel = new MyPanel("JList");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.34 แสดงผลลพธจากโปรแกรม JList1.java โปรแกรม JList2.java แสดงการใชงาน JList ซงอนญาตใหผใชงานเลอกตวเลอกไดมากกวาหนงตวเลอก import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import javax.swing.event.*; // ส าหรบ ListSelectionEvent Class class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

Page 46: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

300 การเขยนโปรแกรมภาษา Java

class MyPanel extends JPanel implements ListSelectionListener{

// สรางตวแปร JList private JList colorSelected;

// ตวแปร display ใชในการแสดงผลลพธจาการเลอกตวเลอกใน JList private JLabel display = new JLabel("Display here");

// ตวแปร listStrings เปนขอมลส าหรบแสดงใน JList private String[] listStrings = {"Black", "Blue", "Cyan",

"Dark Gray", "Gray", "Magenta",

"Orange", "Pink", "Red",

"White", "Yellow"};

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder (

new EtchedBorder(), name);

setBorder(border);

// ตงคา Layout Manager เปน FlowLayout setLayout( new FlowLayout() );

// สราง colorSelected โดยใชคา listStrings เปนขอมลใน JList colorSelected= new JList(listStrings);

// ใหแสดงขอมลเพยง 5 แถวเทานน colorSelected.setVisibleRowCount(5);

// ตงคา Mode เปนชนดทอนญาตใหเลอกไดหลายตวเลอก colorSelected.setSelectionMode(

ListSelectionModel. MULTIPLE_INTERVAL_SELECTION);

// เพม ListSelectionListener ส าหรบการดกจบ Event // เมอมการเลอกคาใน JList colorSelected.addListSelectionListener(this);

// สราง JScrollPane เพอบรรจ JList JScrollPane scroll = new JScrollPane(colorSelected);

add(display);

add(scroll);

}

public void valueChanged(ListSelectionEvent e) { String st = "";

// ดงขอมลทผใชงานเลอก Object[] objectList = colorSelected.getSelectedValues();

// เตรยมขอมลเพอแสดงใน JLabel for(int i=0; i< objectList.length; i++) {

st += (String) objectList[i] + " / ";

}

// แสดง String ใน JLabel display.setText(st);

}

}

public class JList2 {

public static void main(String[] args) {

MyFrame frame = new MyFrame(200,200);

frame.setTitle("Test JList");

Page 47: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 301

MyPanel panel = new MyPanel("JList");

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.35 แสดงผลลพธจากโปรแกรม JList2.java ซงใชคา MULTIPLE_INTERVAL_SELECTION JSlider JSlider มลกษณะเปนตวเลอนซงผใชงานสามรถใช Mouse หรอ ปมลกศรซายและขวาบน Keyboard ดงภาพท 15.36

ภาพท 15.36 Jslider

การแสดงภาพ Tick ใชค าสง setPaintTicks(true) สวนค าสงทใชในการแสดง Label คอ setPaintLabels(true) เมอผใชงานเลอนตวเลอน สงผลให JSlider สง Event ทชอ ChageEvent (ตารางท 15.1) ดงนนถาผเขยนโปรแกรมตองการดกจบ ChangeEvent ตองก าหนดใหโปรแกรม implements ChangeListener และตองสราง Method ทชอ public void stateChanged (ChangeEvent e); // เพอรองรบการท างานของ Event JSlider ม 2 แบบ คอแบบแนวนอนและแนวตง ซงสามารถระบชนดรปแบบ JSlider ไดค าสงทสราง JSlider คอ JSlider (int orientation, int min, int max, int value);

// สราง JSlider ในแนวนอนโดยมชวงคาตงแต 0 ถง 200 โดยตงคาเรมตนเปนคา 0 JSlider (SwingConstants.HORIZONTAL, 0, 200, 0);

ตวเลอน

Label

Tick

Page 48: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

302 การเขยนโปรแกรมภาษา Java

คา SwingConstants.HORIZONTAL เปนการก าหนดใหสราง JSlider ในแนวนอน สวน SwingConstants.VERTICAL เปนการก าหนดใหสราง JSlider ในแนวตง สวนคาทไดจาก JSlider เมอผใชงานเลอนตวเลอนของ JSlider จะเปนคาจ านวนเตมบวกเทานน โปรแกรม ShowJSlider.java แสดงการใชงาน JSlider โดยก าหนดให JSlider ตวแรกดานขวามอใชในการปรบขนาดของภาพวงกลม และ JSlider อก 3 อนดานลางใชในการปรบคาของส แดง เขยว และ น าเงนดงภาพท 15.37 import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import javax.swing.event.*;

// คลาส PaintPanel ใชในการวาดรปวงกลม class PaintPanel extends JPanel {

// คาเสนผานศนยกลางของวงกลม private int diameter=20;

// คาส RGB private int red=0, green=0, blue=0;

public PaintPanel(String name) {

setBorder(BorderFactory.createTitledBorder(new

EtchedBorder(), name) );

}

// Method ทใชในการวาดรปวงกลม // โดยการ Override paintComponent() และเรยกใช Method ของคลาสแมดวย public void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(new Color(red, green, blue) );

g.fillOval(20, 20, diameter, diameter);

}

// ใชในการตงคาของเสนผาศนยกลางของวงกลม // Method นถกเรยกใชโดย JSlider แนวตงดานขวามอทใชปรบขนาดของวงกลม public void setDiameter(int d) {

if(d >= 20) diameter = d;

else diameter=20;

// ค าสงใหวาดรปใหม โดยเรยกให paintComponent() ท างานทางออม // ไมควรเรยก paintComponent() โดยตรง ใหเรยกโดยใช repaint() เทานน repaint();

}

// Method setRed() setGreen() setBlue() ใชในการตงคาของแมส // Method เหลานถกเรยกใชเมอผใชงานเลอน JSlider ทเปนการปรบคาของส public void setRed(int r) {

red = r;

repaint();

}

Page 49: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 303

public void setGreen(int g) {

green = g;

repaint();

}

public void setBlue(int b) {

blue = b;

repaint();

}

}

// JPanel ทบรรจ JSlider ทชอ Diameter มหนาทใชในการปรบขนาดของวงกลม class SizePanel extends JPanel {

JSlider diameter;

public SizePanel(String name) {

setBorder(BorderFactory.createTitledBorder(new

EtchedBorder(), name) );

setLayout(new BorderLayout());

// สราง JSlider ในแนวตง มชวง 0 ถง 300 diameter = new JSlider(SwingConstants.VERTICAL,0, 300, 0);

// ให Tick หลกหางกนชวงละ 30 diameter.setMajorTickSpacing(30);

// ให Tick รองหางกนชวงละ 10 diameter.setMinorTickSpacing(10);

// วาด Tick ของ JSlider diameter.setPaintTicks(true);

// วาดคาของชวง Tick diameter.setPaintLabels(true);

// เพม diameter JSlider ใน JPanel add(diameter);

}

}

// JPanel ส าหรบ JSlider ทมหนาทปรบคาของแมส RGB class CommandPanel extends JPanel {

// JSlider ส าหรบสแดง เขยว และ น าเงน JSlider redSlider, greenSlider, blueSlider;

public CommandPanel(String name) {

setBorder(BorderFactory.createTitledBorder(new

EtchedBorder(), name) );

// ตงคา Layout เปนตารางขนาด 3 แถว 1 คอลมน setLayout(new GridLayout(3, 1));

// สราง JSlider สแดง redSlider = new JSlider(SwingConstants.HORIZONTAL,0,255,0);

redSlider.setMajorTickSpacing(20);

redSlider.setMinorTickSpacing(5);

redSlider.setPaintTicks(true);

redSlider.setPaintLabels(true);

// ตงคา ToolTip เมอผใชงานน า Mouse ไปชคางไว จะมค าอธบายปรากฏขน redSlider.setToolTipText("Adjust Red Color");

// สราง JSlider สเขยว greenSlider = new JSlider(SwingConstants.HORIZONTAL,0,255,0);

Page 50: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

304 การเขยนโปรแกรมภาษา Java

greenSlider.setMajorTickSpacing(20);

greenSlider.setMinorTickSpacing(5);

greenSlider.setPaintTicks(true);

greenSlider.setPaintLabels(true);

greenSlider.setToolTipText("Adjust Green Color");

// สราง JSlider สน าเงน blueSlider = new JSlider(SwingConstants.HORIZONTAL,0,255,0);

blueSlider.setMajorTickSpacing(20);

blueSlider.setMinorTickSpacing(5);

blueSlider.setPaintTicks(true);

blueSlider.setPaintLabels(true);

blueSlider.setToolTipText("Adjust Blue Color");

// เพม JSlider ทง 3 ลงใน JPanel add(redSlider);

add(greenSlider);

add(blueSlider);

}

}

class MyFrame extends JFrame implements ChangeListener{

PaintPanel paintPanel;

CommandPanel commandPanel;

SizePanel sizePanel;

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setTitle("Test JSlider");

// สราง JPanel ส าหรบวาดวงกลม paintPanel = new PaintPanel("Paint");

// สราง JPanel ทบรรจ JSlider RGB commandPanel = new CommandPanel("Adjust Color");

// สราง JPanel ทบรรจ JSlider ทใชในการปรบขนาดของวงกลม sizePanel = new SizePanel("Diameter");

// เพม ChangeListener ใหกบ JSlider commandPanel.redSlider.addChangeListener(this);

commandPanel.greenSlider.addChangeListener(this);

commandPanel.blueSlider.addChangeListener(this);

sizePanel.diameter.addChangeListener(this);

// เพม JPanel ทง 3 ลงใน JFrame getContentPane().add(paintPanel, BorderLayout.CENTER);

getContentPane().add(commandPanel, BorderLayout.SOUTH);

getContentPane().add(sizePanel, BorderLayout.EAST);

setVisible(true);

}

// เมอมการเลอน JSlider ท าให Method นถกเรยกใช public void stateChanged(ChangeEvent e) {

// หาวาผใชงานเลอน JSlider ตวใด JSlider slide = (JSlider) e.getSource();

Page 51: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 305

// หาคาวา JSlider ทถกเลอนไปทใด และท าการเปลยนคาของ paintPanel if(slide == sizePanel.diameter)

// ในกรณทผใชงานเลอก diameter JSlider paintPanel.setDiameter( slide.getValue() );

else if (slide == commandPanel.redSlider)

// ในกรณทผใชงานเลอก red JSlider paintPanel.setRed( slide.getValue() );

else if (slide == commandPanel.greenSlider)

// ในกรณทผใชงานเลอก green JSlider paintPanel.setGreen( slide.getValue() );

else if (slide == commandPanel.blueSlider)

// ในกรณทผใชงานเลอก blue JSlider paintPanel.setBlue( slide.getValue() );

}

}

public class ShowJSlider {

public static void main(String[] args) {

MyFrame frame = new MyFrame(400,600);

}

}

ภาพท 15.37 ผลลพธจากโปรแกรม ShowJSlider.java

SizePanel

CommandPanel

PaintPanel

Page 52: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

306 การเขยนโปรแกรมภาษา Java

JProgressBar ท าหนาเปนตวบอกถงความคบหนาในการท างานดงภาพท 15.38 ซงอาจวางในแนวตงหรอแนวนอนได สวนมากใช JProgressBar ในกรณทตองการบอกใหผใชงานรอเนองจากโปรแกรมท างานนาน คาคงททใชในการระบการวางของ JProgressBar คอ JProgressBar.VERTICAL และ JProgressBar.HORIZONTAL

ภาพท 15.38 แสดง JProgressBar JProgressBar แสดงถงเวลาทใชในการท างานเปนรอยละ ค าสง Constructor ทใชในการสราง JProgressBar คอ JProgressBar pBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 1000);

คา 0 เปนคาเรมตนของของ JProgressBar และแสดงคาบน JProgressBar เปน 0% และคา 1000 เปนคามากทสดของ JProgressBar หรอ 100% โดยผใชงานจ าเปนตองใชค าสง setValue(int n) เพอให JProgressBar แสดงตวเลขเปน % เชน setValue(200) ท าให JProgressBar แสดง 20% โปรแกรม ShowJProgressBar.java แสดงการใช JProgressBar import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import javax.swing.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel{

final static int MAX = 1000;

JProgressBar pBar;

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

JProgressBar.VERTICAL

JProgressBar.HORIZONTAL

Page 53: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 307

setBorder(border);

// ตงคา Layout เปน FlowLayout setLayout( new FlowLayout() );

// สราง JProgressBar ในแนวนอนโดยมชวงคาเปน 0 ถง 1000 pBar = new JProgressBar(JProgressBar.HORIZONTAL,0,MAX);

// ตงคาเรมตนใหแสดง 0% ตอนเรมตนท างาน pBar.setValue(0);

// สงให JProgressBar แสดงคา % pBar.setStringPainted(true);

add(pBar);

}

}

public class ShowJProgressBar {

public static void main(String[] args) {

JLabel displayLabel = new JLabel("Working on it. Please wait ok?");

MyFrame frame = new MyFrame(200,150);

frame.setTitle("Test JProgressBar");

MyPanel progressPanel = new MyPanel("JProgressBar");

frame.getContentPane().add(progressPanel, BorderLayout.CENTER);

frame.getContentPane().add(displayLabel, BorderLayout.SOUTH);

frame.setVisible(true);

for(int i=0; i <= progressPanel.MAX; i++) {

// ค าสง sleep(10) ท าใหโปรแกรมหยดท างาน 10 Millisecond try {Thread.sleep(10);}

catch (InterruptedException e) {}

// ตงคาให JProgressBar แสดงคา % ทเพอขน progressPanel.pBar.setValue(i);

}

displayLabel.setText("Done");

}

}

ภาพท 15.39 แสดงผลลพธจากโปรแกรม ShowJProgressBar.java

JSplitPane JSplitPane มลกษณะเปนตวแบงการแสดง GUI ออกเปน 2 ดานดงภาพท 15.40 โดยผใชงานสามารถปรบความกวางของ Pane ไดโดยใช Mouse Drag and Drop ทเสนแบง Pane โปรแกรม ShowJSplitPane.java แสดงการใชงาน JSplitPane

Page 54: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

308 การเขยนโปรแกรมภาษา Java

import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import javax.swing.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel implements ListSelectionListener{

private JList pictureList;

JLabel pictureLabel;

// ตวแปร listStrings ส าหรบเกบชอของรปภาพ String[] listStrings = {"tweety.gif", "typing.gif","sun.gif","plamtree.gif","circle.gif"};

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(new

EtchedBorder(), name);

setBorder(border);

setLayout(new BorderLayout() );

// สราง JList เพอส าหรบ Pane ดานซายของ JSplitPane pictureList= new JList(listStrings);

pictureList.setVisibleRowCount(5);

pictureList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION );

pictureList.addListSelectionListener(this);

// เตรยม JLabel ทใชแสดงภาพส าหรบ Pane ดานขวา pictureLabel = new JLabel( new ImageIcon(listStrings[0]) ,

JLabel.CENTER);

// สราง JScrollPane ส าหรบ pictureList และ pictureLabel JScrollPane scrollList = new JScrollPane(pictureList);

JScrollPane scrollPicture = new JScrollPane(pictureLabel);

// สราง JSplitPane โดยดานขวาบรรจ scrollList // และดานขวาบรรจ scrollPicture JSplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT,

scrollList, scrollPicture);

// ตงคา One Touch Expandable ดงภาพท 15.40 splitPane.setOneTouchExpandable(true);

add(splitPane);

}

public void valueChanged(ListSelectionEvent e) {

String name = (String) pictureList.getSelectedValue();

pictureLabel.setIcon(new ImageIcon(name) );

}

}

public class ShowJSplitPane {

public static void main(String[] args) {

MyFrame frame = new MyFrame(300,150);

Page 55: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 309

frame.setTitle(“Test JSplitPane”);

MyPanel panel = new MyPanel(“JsplitPane”);

frame.getContentPane().add(panel);

frame.setVisible(true);

}

}

ภาพท 15.40 แสดงผลลพธของโปรแกรม ShowJSplitPane.java ค าสง setOneTouchExpandable(true) ใชในการสรางปมทผใชงานสามารถคลกเพอขยาย Pane ดายซาย

หรอขวาใหเตมทงหมดดงภาพท 15.41

ภาพท 15.41 แสดงการใช One Touch Expandable JToolBar JToolBar เปนเครองมอทท าหนาทเปน Short-Cut Command ซงชวยใหผใชงาน สงงานไดเรวขน โปรแกรม ShowJToolBar.java แสดงการใชงาน JToolBar import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

class MyFrame extends JFrame implements ActionListener{

JButton searchButton, refreshButton, printButton, homeButton;

JTextArea textDisplay;

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

One Touch Expandable

Page 56: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

310 การเขยนโปรแกรมภาษา Java

setDefaultCloseOperation(EXIT_ON_CLOSE);

// สรางปมตางๆ ทใชใน JToolBar searchButton = new JButton(new ImageIcon("search.jpg"));

refreshButton = new JButton(new ImageIcon("refresh.jpg"));

printButton = new JButton(new ImageIcon("print.jpg"));

homeButton = new JButton(new ImageIcon("home.jpg"));

// ตงคา ActionListerner ส าหรบปม searchButton.addActionListener(this);

refreshButton.addActionListener(this);

printButton.addActionListener(this);

homeButton.addActionListener(this);

// สราง JToolBar ในแนวนอนและตงชอ ‚Demo JToolBar‛ JToolBar toolBar = new

JToolBar("Demo JToolBar", JToolBar.HORIZONTAL);

// เพมปมทงหมดไปท JToolBar toolBar.add(searchButton);

toolBar.add(refreshButton);

toolBar.add(printButton);

toolBar.add(homeButton);

// สราง JTextArea ส าหรบแสดงผลเมอมการกดปมบน JToolBar textDisplay = new JTextArea();

// สราง JScrollPane เพอใชกบ JTextArea JScrollPane scroll = new JScrollPane(textDisplay);

getContentPane().add(toolBar, BorderLayout.NORTH);

getContentPane().add(scroll, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

JButton src = (JButton) e.getSource();

String choice="";

// ทดสอบวาผใชงานกดปมใด if(src == searchButton) choice = "Search button";

else if(src == refreshButton) choice = "Refresh button";

else if(src == printButton) choice = "Print button";

else if(src == homeButton) choice = "Home button";

/ /แสดงผลลพธทาง JTextArea textDisplay.append("You have clicked " + choice +"\n");

}

}

public class ShowJToolBar {

public static void main(String[] args) {

MyFrame frame = new MyFrame(300,300);

frame.setTitle("Test JToolBar");

frame.setVisible(true);

}

}

Page 57: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 311

ภาพท 15.42 แสดงผลลพธจากโปรแกรม ShowJToolBar.java JTabbedPane JTabbedPane เหมาะส าหรบการแสดง JComponent จ านวนมากในพนทจ ากด เพราะ JTabbedPane แบงพนทเปนสวนๆ ซงผใชงานสามารถเลอกสลบพนทท างานได โปรแกรม ShowJTabbedPane.java แสดงวธการใชงาน JTabbedPane import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import javax.swing.event.*;

class MyFrame extends JFrame{

public MyFrame(int width, int height) {

Toolkit tk = getToolkit();

Dimension screen = tk.getScreenSize();

setBounds( (screen.width - width)/2,

(screen.height - height)/2, width, height);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

}

class MyPanel extends JPanel{

public MyPanel(String name) {

TitledBorder border = BorderFactory.createTitledBorder(

new EtchedBorder(), name);

setBorder(border);

add(new JLabel("You can put Jcomponents here"));

}

}

public class ShowJTabbedPane {

public static void main(String[] args) {

MyFrame frame = new MyFrame(400,200);

frame.setTitle("Test JTabbedPane");

// สราง 3 JPanel เพอใชใน JTabbedPane MyPanel firstPanel = new MyPanel("First Panel");

JToolBar

Page 58: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

312 การเขยนโปรแกรมภาษา Java

MyPanel secondPanel = new MyPanel("Second Panel");

MyPanel thirdPanel = new MyPanel("Third Panel");

// สราง JTabbedPane JTabbedPane tabbedPane = new JTabbedPane();

// เพม JPanel ไปท JTabbedPane tabbedPane.addTab("First Pane",

new ImageIcon("x.gif"), firstPanel, "Display ToolTip here");

tabbedPane.addTab("Second Pane",

new ImageIcon("right.gif"), secondPanel, "Display ToolTip here");

tabbedPane.addTab("Third Pane",

new ImageIcon("point.gif"), thirdPanel, "Display ToolTip here");

/ /เพม JTabbedPane ไปท JFrame frame.getContentPane().add(tabbedPane);

frame.setVisible(true);

}

}

ภาพท 15.53 แสดงผลลพธจากโปรแกรม ShowJTabbedPane.java

การสราง Nested Class เพอจดการ Event ของ JComponent Nested Class คอคลาสทอยภายในคลาสอน วตถประสงคของการใช Nested Class เพอตองการรวมกลมของคลาสไวทดวยกน และไมตองการใหคลาสอนเขามาใชได การสราง Nested Class เหมอนการสรางคลาสทวไป ดงตวอยางโปรแกรม Outer.java public class Outer{

// คลาส Inside สามารถอางถงตวแปรของ Outer ได private int beAccessByInsideClass;

public class Inside {

// ใส Method ของ Inside คลาส ทน }

// Method ของคลาส Outer public void outerMethod() {

// แสดงวธการสรางคลาส Inside ภายใน Method ของ Outer Inside in = new Inside();

}

}

อางตวแปรของคลาส Outer ได

Page 59: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 313

ในคลาส Outer มคลาส Inside ซงเมอผานตวแปลภาษา Java แลว จะไดแฟมขอมลนามสกล Class จ านวน 2 แฟมขอมลคอ Outer.class และ Outer$Inside.class สงเกตวาคลาส Inside เปน Nested Class ของ Outer เนองจากม $ คนระหวางชอแฟมขอมล Method ของคลาส Inside สามารถใชตวแปรของ Outer ไดแมวาค าหลกหนาตวแปรจะเปน private กตาม สวน Method ของ Outer สามารถสราง Inside เหมอนการสรางวตถจากคลาสโดยทวไปดงในโปรแกรม Outer.java การสรางวตถคลาส Inside จากคลาสอนทไมใช Outer จ าเปนตองสราง Outer กอนทกครง เนองจาก Inside เปน Nested Class ในคลาส Outer วธการสราง Inside จากคลาสอนแสดงในโปรแกรม TestInside.java public class TestInside{

public static void main(String[] args) {

// สราง Outer กอน Outer outer = new Outer();

// สราง Inside จาก Outer Outer.Inside inside = outer.new Inside();

// หรอสามารถเขยนค าสงไดในบรรทดเดยว เชน Outer.Inside inside1 = new Outer().new Inside();

}

}

เหตผลทกลาวถงการสราง Nested Class เพราะสามารถน ามาใชในการจดการ Event ของ JComponent ได เพราะ nested Class สามารถอางตวแปรของคลาสหลกได โปรแกรม TestNested.java แสดงวธการจดการ Event จาก JButton โดยใช Nested Class import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

class MyFrame extends JFrame{

private JButton helloButton = new JButton("Hello");

private JButton exitButton = new JButton("Exit");

public MyFrame() {

setDefaultCloseOperation(EXIT_ON_CLOSE);

setTitle("Handling Event Using Nested Class");

Container content = getContentPane();

content.setLayout(new FlowLayout());

content.add(helloButton);

content.add(exitButton);

// สราง Nested Class เพอรองรบการท างานของ Event HandleEvent handle = new HandleEvent();

// เพม ActionListener ไปท Nested Class helloButton.addActionListener(handle);

exitButton.addActionListener(handle);

// ค าสง pack() ใชในการตงขนาดของ JFrame ใหพอดกบ // JComponent ใน JFrame ดงนน ไมตองใชค าสง setBounds() อก pack();

setVisible(true);

Page 60: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

314 การเขยนโปรแกรมภาษา Java

}

// Nested Class รองรบการท างานของ Event // สงเกตวา Nested Class สามารถอางตวแปรของคลาส Testnested ได class HandleEvent implements ActionListener{

public void actionPerformed(ActionEvent e) {

JButton click = (JButton) e.getSource();

// อางตวแปร helloButton ในคลาส TestNested ได if( click == helloButton) {

System.out.println("You click Hello Button");

}

else System.exit(0);

}

}

}

public class TestNested {

public static void main(String[] args) {

MyFrame frame = new MyFrame();

}

}

ภาพท 15.54 แสดงผลลพธจากโปรแกรม TestNested.java

Page 61: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

การเขยนโปรแกรมภาษา Java 315

สรป ในบทนกลาวถงวธการใชงาน JComponent ใน Package javax.swing และวธการจดการกบ Event ตางๆ ทเกดขนจาก JComponent JComponent ทอยในบทนประกอบดวย

JPanel การสราง Border ใหกบ JComponent JLabel JButton JCheckBox JRadioButton JTextField JPasswordField JTextArea JScrollPane การสราง Menu JComboBox JList JSlider JProgreesBar JToolBar JTabbedPane และสดทาย วธการใช Nested Class จดการ Event

Page 62: บทที่ JComponent และการจัดการอีเว้นท์lily.bu.ac.th/~thirapon.w/gim/OOP_files/Chapter15.pdf · 2012. 11. 9. · บทที่ 15

316 การเขยนโปรแกรมภาษา Java

แบบฝกหดทายบทท 15

1. อธบายวธการใชงาน JLabel 2. การใหคลาส Implements MouseListener ในคลาสนนตองสราง Method ใดบาง 3. อธบาย Low-level Event ตางๆ 4. ถาตองการใชรองรบการใชงาน JSlider ควรใหคลาส Implement Interface ใด และตองสราง Method

ใดบาง 5. อธบายความแตกตางของการใชงาน JCheckBox และ JRadioButton 6. อธบายสวนประกอบของ Text Component 7. JScrollpane ใชส าหรบงานประเภทใด 8. JComboBox และ JList มความแตกตางกนอยางไร 9. JTabbedPane มประโยชนอยางไร 10. อธบายขอดของการใช Nested Class จดการ Event

Programming Problems

1. จงเขยนโปรแกรมเครองคดเลขจาก Programming Problems บทท 14 ใหสมบรณ

2. จงเขยนโปรแกรมการใชเมาส Drag and Drop เพอวาดรปสเหลยมบน JPanel 3. จงเขยนโปรแกรมเลยนแบบโปรแกรม Paint เพอใชในการวาดรป 4. จงเขยนโปรแกรมเลยนแบบโปรแกรม NotePad 5. จงเขยนโปรแกรมจ าลองเกมหมากฮอส 6. จงเขยนโปรแกรมจ าลองเกมโอเอกซ

ใช JLabel