unit1-การสร้าง gui ด้วย swing

150
หนวยที1 การสราง GUI ดวย swing 1.1 บทนํา Graphic User Interface เปนการสรางจอภาพใหผูใชสามารถติดตอกับโปรแกรมไดงายและสะดวก ยิ่งขึ้น โดยนิยมสรางใหเปนจอภาพแบบกราฟก จึงเรียกวา Graphic User Interface หรือ GUI ในบท นี้จะกลาวถึงการนําเครื่องมือตางๆหรือ components มาใชสราง GUI เพื่อใหการเขียนโปรแกรมจา วามีความทันสมัยและมีประสิทธิภาพยิ่งขึ้น เครื่องมือหรือ components เหลานี้เปนคลาสที่อยูใน package javax.swing เชน class JButton ,class JCheckbox ,class JMenu ฯลฯ เปนตน ทั้งนี้แตละ class ก็จะมี constructor ของตนเองที่จะเรียกถูกเรียกใชเมื่อมีการสราง Object ใหมภายใต class ตางๆ ดังนั้นคําสั่งที่ใชในงานตางๆใน GUI จึงเปนคําสั่งในการสราง Object ใหมเสียเปนสวนใหญ นอกจากนี้ในแตละ component ก็จะมี Methods ตางๆมากมายเพื่อใหผูเขียนโปรแกรมสามารถ เรียกใชไดทันที โดยไมตองเสียเวลาสรางขึ้นมาใหมอีก 1.2 Swing Components Class ที่ใชในการสราง component ที่เปนแบบ GUI นั้นสวนหนึ่งมาจาก GUI Component ของ Swing ซึ่งเรียกใชจาก package javax.swing โดย GUI เหลานี้เปน GUI component ลาสุดของ Java2 ทั้งนีSwing components จะเรียกวาเปน “pure java component” เนื่องจากถูกสราง จัดการ และแสดงผลไดอยางสมบูรณภายใน Java ดังนั้นไมวาจะนําไปใชงานในแพลตฟอรมใด ก็จะยังคง แสดงผลลัพธที่ไมเปลี่ยนแปลง ซึ่งตางจาก AWT หรือ Abstract Windowing Toolkit (java.awt) เพราะ GUI ที่สรางจาก AWT จะปรับเปลี่ยนไปตามแพลตฟอรมที่ใช ถาใชตางกันก็อาจจะได ผลลัพธหรือรูปรางหนาตาของ GUI ที่แตกตางไปจากความตองการได นอกจากนั้นการใช AWT จะทําใหสิ้นเปลืองหนวยความจํามาก แต Swing จะใชหนวยความจํานอยมาก เรามักเรียก Swing component วา “lightweight component” และเรียก AWT วา “heavyweight components” Swing component มีอยูมากมายและจะขึ้นตนดวยตัว J เชน JButton JLabel JFrame เปน ตน โดยทุก component จะสืบทอดมาจาก class JComponent แต JFrame ,JApplet และ JDialog สืบ ทอดมาจาก class Frame ,class Applet และ class Dialog ตามลําดับ และถึงแมวา Swing component จะเปน component ที่พัฒนาตอมาจาก AWT แตเราก็ยังสามารถนําเอา AWT component บางตัวมา ใชทํางานรวมกับ Swing component ไดเชนกัน รูปที1.1 แสดงโครงสรางลําดับชั้นการสืบทอดของ Swing components

Upload: wittaya-botan

Post on 28-Jul-2015

1.465 views

Category:

Documents


12 download

TRANSCRIPT

Page 1: unit1-การสร้าง GUI ด้วย swing

หนวยที ่1 การสราง GUI ดวย swing

1.1 บทนํา Graphic User Interface เปนการสรางจอภาพใหผูใชสามารถติดตอกับโปรแกรมไดงายและสะดวกยิ่งขึ้น โดยนิยมสรางใหเปนจอภาพแบบกราฟก จึงเรียกวา Graphic User Interface หรือ GUI ในบทนี้จะกลาวถึงการนําเครื่องมือตางๆหรือ components มาใชสราง GUI เพื่อใหการเขยีนโปรแกรมจาวามีความทนัสมัยและมีประสิทธิภาพยิ่งขึ้น เครื่องมือหรือ components เหลานี้เปนคลาสที่อยูใน package javax.swing เชน class JButton ,class JCheckbox ,class JMenu ฯลฯ เปนตน ทั้งนีแ้ตละ class ก็จะม ี constructor ของตนเองที่จะเรียกถูกเรยีกใชเมื่อมีการสราง Object ใหมภายใต class ตางๆ ดังนั้นคาํส่ังที่ใชในงานตางๆใน GUI จึงเปนคําส่ังในการสราง Object ใหมเสยีเปนสวนใหญ นอกจากนี้ในแตละ component ก็จะม ี Methods ตางๆมากมายเพือ่ใหผูเขียนโปรแกรมสามารถเรียกใชไดทันที โดยไมตองเสียเวลาสรางขึ้นมาใหมอีก

1.2 Swing Components Class ที่ใชในการสราง component ที่เปนแบบ GUI นั้นสวนหนึ่งมาจาก GUI Component ของ Swing ซ่ึงเรียกใชจาก package javax.swing โดย GUI เหลานี้เปน GUI component ลาสุดของ Java2 ทั้งนี้ Swing components จะเรียกวาเปน “pure java component” เนื่องจากถกูสราง จัดการและแสดงผลไดอยางสมบูรณภายใน Java ดังนั้นไมวาจะนําไปใชงานในแพลตฟอรมใด ก็จะยังคงแสดงผลลัพธที่ไมเปลี่ยนแปลง ซ่ึงตางจาก AWT หรือ Abstract Windowing Toolkit (java.awt) เพราะ GUI ที่สรางจาก AWT จะปรบัเปลี่ยนไปตามแพลตฟอรมที่ใช ถาใชตางกันก็อาจจะไดผลลัพธหรือรูปรางหนาตาของ GUI ที่แตกตางไปจากความตองการได นอกจากนัน้การใช AWT จะทําใหส้ินเปลืองหนวยความจํามาก แต Swing จะใชหนวยความจํานอยมาก เรามกัเรียก Swing component วา “lightweight component” และเรียก AWT วา “heavyweight components” Swing component มีอยูมากมายและจะขึ้นตนดวยตวั J เชน JButton JLabel JFrame เปนตน โดยทุก component จะสืบทอดมาจาก class JComponent แต JFrame ,JApplet และ JDialog สืบทอดมาจาก class Frame ,class Applet และ class Dialog ตามลําดับ และถึงแมวา Swing component จะเปน component ที่พัฒนาตอมาจาก AWT แตเราก็ยงัสามารถนําเอา AWT component บางตัวมาใชทํางานรวมกับ Swing component ไดเชนกัน รูปที่ 1.1 แสดงโครงสรางลําดับชั้นการสืบทอดของ Swing components

Page 2: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 2

panel Applet JApplet

Frame JFrame

Dialog JDialog

Window JWindow

Object

Component

Container JComponent AbstractButto

JColorChoose

JComboBox

JLabel

JInternalFra

JLayerPane

JToolTip

JOptionPane

JPopupMen

JRootPane

JScrollPane

JSlider

JTabbedPan

JTree

JTextComponen

JButton

JMenuItem

JToggleButton

JFileChooser

DefaultListCellRender

JDeskTopPane

JMenuBar

JPanel

JProgressBa

JscrollBar

JSeparator

JSplitPane

JTable

JList

JViewPort

JEditorPane

JTextArea

JTextField

JCheckBoxMenuitem

JMenu

JRadioButtonMenuItem

JCheckBox

JRadioButton

javax.swing.text

javax.swing java.awt

java.applet

รูปแสดงโครงสรางลําดับชั้นการสืบทอดของ swing

Page 3: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 3

ส่ิงที่ Swing component ไดรับการสืบทอดมาจาก Container และ JComponent มีอยูมากมายทั้ง Method ตัวแปร และคุณสมบัติของ Component นั้นๆ ที่สําคัญไดแก คุณสมบัติท่ีไดจาก JComponent 1. class และ method ที่สนับสนุนการจัด Layout ตางๆ 2. class และ method ที่สนับสนุนการวาด component 3. class และ method ที่สนับสนุนการจัดการกับเหตกุารณ(Event) คุณสมบัติท่ีไดจาก Container 1. เกี่ยวกับการเพิ่ม component ลงใน Container 2. วิธีการจัดวาง Layout ของ Component Swing components จัดแบงออกเปนประเภทตางๆไดดังนี้

ชนิดของ Component Component Atomic control JLabel ,JButton ,JCheckBox ,JRadioButton

,JToggleButton ,JComboBox ,JScrollBar ,JSeparator ,JSlider ,JSpinner ,JProgressBar

Complex data component JTable ,JTree ,JList ,JFileChooser ,JColorChooser ,JOptionPane

Text component JTextField ,JFormatedTextField ,JPasswordField ,JTextArea ,JTextPane ,JEditPane

Menu component JMenuBar ,JMenu ,JPopupMenu ,JMenuItem ,JCheckBoxMenuItem ,JRadioButtonMenuItem

Layout container JPanel ,JScrollPane ,JSplitPane ,JTabbedPane ,JDeskTopPane ,JToolbar

Top-level window component (Top-level Swing Component)

JFrame ,JDialog ,JWindow ,JInternalFrame ,JApplet

Page 4: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 4

Container จากโครงสรางลําดับชั้นการสืบทอดของ swing ตามรูปที่ 1.1 Component ของ swing จะมีสวนหนึ่งที่เราเรียกวา Container โดย Container นี้จะใชสําหรับบรรจุ Components อ่ืนๆของ swing เพื่อนําขึ้นแสดงบนจอภาพ เราสามารถแบง Container ออกเปนกลุมไดดังนี ้Top-Level Container คือ Container ระดับบนสุด ไดแก JFrame ใชสราง window หลักของโปรแกรม JApplet ใชสราง window สําหรับ Application ที่เปดใน Browser JDialog ใชสราง window สําหรับสอบถาม JWindow ใชสราง window ที่ไมมีสวนหัวหรือขอบ General-Purpose Container คือ Container ระดับกลางสหรับไวใชประโยชนโดยทวัไปในงานตางๆ ไดแก JPanel JScrollPane JSplitPane JTabbedPane JtoolBar Special-Purpose Container คือ Container ระดับกลางสําหรับไวใชในงานเฉพาะ ไดแก JInternalFrame ใชสราง window ซอน window JlayeredPane JRootPane

ที่เหลือทั้งหมดถือวา Components ที่ไมสามารถจัดวางไดอิสระโดยจะตองจัดวาง Component ดังกลาวใน Container ชนิดใดชนิดหนึ่ง

กอนที่จะกลาวถึงรายละเอยีดของ Container และ Swing Components ชนิดตางๆ ภายใน package javax.swing มคีลาสที่ควรกลาวถึงกอนไดแก คลาส Dimension และ คลาส Box โดยทั้งสองคลาสเราจะมีการใชงานบอยๆ เพื่อชวยอํานวยความสะดวกในการจัดการ Component ตางๆ Class Dimension Class Diamension ใชเก็บขนาดของ Component (กวาง และสูง) ไมมีตําแหนง x,y ดังนั้นเราจึงสามารถจัดการขนาดของ Component ตางๆโดยใช Method ที่รับคา Argument เปน Dimension Object หรือ Method ที่คืนคาเปน Dimension Object ได

Page 5: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 5

คาคงที่และ Method ที่สําคัญของ Class Dimension มีดังนี้ คาคงที่/Method ความหมาย

public int height เก็บความสูงของ Dimension public int width เก็บความกวางของ Dimension public Dimension() สราง Dimension ที่มีคาเทากบั 0 public Dimension(int width, int height) สราง Dimension ที่มีขนาดเทากับ width และ

height ที่กําหนด public double getHeight() คืนคาความสูงของ Dimension เปน Double public double getWidth() คืนคาความกวางของ Dimension เปน Double public void setSize(double width , double height)

กําหนดขนาดของ Dimension เปน double

Public void setSize(int width , int height) กําหนดขนาดของ Dimension เปน int ใน Class Component มี Overload method “setSize()” ซ่ึงรับคาเปน Dimension Object เพื่อใชกําหนดขนาดใหกับ Component ตางๆเหมือนกับ Method “setSize(int,int)” ใน Class “Toolkit” มี Method หนึ่งที่จะใหคา Dimension ของจอภาพขณะนั้นออกมา คือ public Dimension getScreenSize() ตัวอยางที่ 1.1 แสดงการกําหนดขนาด Component ผาน Dimension และกําหนดใหแสดง Frame กลางจอภาพพอดีดวยการใชคุณสมบัติผาน Method getScreenSize() ของ Class Toolkit /*------------------file useDimension.java----------------*/ import java.awt.* ; import javax.swing.* ; public class useDimension extends JPanel { JButton b1,b2; JTextField text ; public useDimension() { setLayout(new FlowLayout()) ; b1 = new JButton("OK"); b2 = new JButton("Cancel"); text = new JTextField(10); add(text);

Page 6: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 6

add(b1); add(b2); } public static void main(String[] args) { JFrame f=new JFrame(); Toolkit tk = f.getToolkit(); Dimension screen =tk.getScreenSize(); //หาขนาด screen ของจอภาพ Dimension FrameSize = new Dimension(300,100); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(FrameSize); //กําหนดขนาดของ Frame ผาน Dimension Object Container c = f.getContentPane(); c.add(new useDimension()); int x=(screen.width-FrameSize.width)/2 ; //คํานวณตําแหนง x ที่อยูกลางจอพอด ี int y=(screen.height - FrameSize.height)/2 ; //คํานวณตําแหนง y ที่อยูกลางจอพอด ี f.setLocation(x,y); //กําหนดตําแหนง x,y ที่ตองการแสดง Component f.show(); } }

Page 7: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 7

การทํางานของโปรแกรม จากตัวอยางเรยีกใช Method getScreenSize() ของ Class Toolkit เพื่อใหไดคา Screen Dimension ของจอภาพแลวเก็บไวใน Dimension Screen จากนั้นสราง Dimension FrameSize Object เพื่อใชสําหรับกําหนดขนาดใหกับ Frame สุดทายเรียกใช Method setLocation() พรอมสง x และ y เปน parameter ใหกับ Method เพื่อใชเปนจุดเริ่มตนในการแสดง Frame ออกทางจอภาพ จากตัวอยางนีเ้ราจะเหน็วาเราสามารถกําหนดขนาดของ Component ผานทาง Dimension Object ไดเชนเดยีวกัน สวนการนํา Component ไปแสดงยังตําแหนงใดๆนั้นสามารถใช Method “setLocation()” โดยนําจดุ x และ y ที่ตองการนํา Component ไปแสดงยังจุดนั้นไดทันที Class Box

ใชสราง Component เล็กๆ ซ่ึงมองไมเห็นมาแทรกลงไประหวาง Component ส่ิงที่สรางขึ้นมานี้เรียกวา strut เพื่อใหเกิดชองวางระหวาง Component ทั้งแนวตั้งและแนวนอนเพื่อจดัการ Layout ของ Component โดยวิธีนี้เราไมจําเปนตองสรางเอง เพราะ Java มีมาใหแลว คือ class Box ซ่ึงเรียกไดจาก javax.swing.box

Constructor และ Method ที่สําคัญมีดังนี้

Constructor/Method ความหมาย Box(int axis) Create a Box container that displays its

components along the specified axis. static Component createGlue() Create an invisible “glue” component that can

be useful in a Box whose visible components have a maximum width (for horizontal box) or height (for a vertical box). The size of a glue component can expand fill the empty space between component

static Box createHorizontalBox() Creates a Box container that arranges its components from left-to-right.Components have a fixed width.

static Component createHorizontalGlue() Create a horizontal glue component. static Component createHorizontalStrut(int width) Creates an invisible component that’s always

Page 8: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 8

the same width, even if the container is widened.

static Component createRighdArea(Dimension d) Create an visible component that always has the same specified area, even if the container is resized.

static Box createVerticalBox() Create a Box container the arranges its components from top-to-bottom. Components have a fixed.

static Component createVerticalGlue() Creates a vertical glue component. static Component createVerticalStrut(int height) Create an invisible component that’s always

the same height , even if the container is lengthened.

AccessibleContext getAccessiblecontext() Gets the AccessibleContext associated with this JComponent.

void setLayout(LayoutManager) Throws an AWTError, because a Box container can only use a BoxLayout layout namager.

ตัวอยางที่ 1.2 แสดงการนําเอา Glue หรือ Component ที่มองไมเหน็มาแทรกเพื่อใหเกิดชองวางระหวาง Component ที่สรางในแบบของ BoxLayout /*--------------------file GlueDemo.java-----------------------*/ import java.awt.*; import javax.swing.*; public class GlueDemo extends JPanel { public GlueDemo() { setLayout(new BorderLayout()); Box oneToThree = Box.createHorizontalBox(); BoxLayout box_1_3_Layout = new BoxLayout(oneToThree,BoxLayout.X_AXIS); oneToThree.add(new JButton("1")); //สราง component วางขนาด 15 pixels โดยวางไวในแนวนอน oneToThree.add(Box.createHorizontalStrut(15));

Page 9: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 9

oneToThree.add(new JButton("2")); oneToThree.add(Box.createHorizontalStrut(15)); oneToThree.add(new JButton("3")); //สราง Box สําหรับใสปุมที่ 4,5,6 Box fourToSix = Box.createHorizontalBox(); BoxLayout box_4_6_Layout = new BoxLayout(fourToSix,BoxLayout.X_AXIS); fourToSix.add(new JButton("4")); //สรางปุมและ Component วางคั่นระหวางปุมเหลานี้ในแนวนอน fourToSix.add(Box.createHorizontalStrut(15)); fourToSix.add(new JButton("5")); fourToSix.add(Box.createHorizontalStrut(15)); fourToSix.add(new JButton("6")); //สราง Box สําหรับใสปุมที่ 7,8,9 Box sevenToNine = Box.createHorizontalBox(); BoxLayout box_7_9_Layout = new BoxLayout(sevenToNine,BoxLayout.X_AXIS); sevenToNine.add(new JButton("7")); //สรางปุมและ Component วางคั่นระหวางปุมเหลานี้ในแนวนอน sevenToNine.add(Box.createHorizontalStrut(15)); sevenToNine.add(new JButton("8")); sevenToNine.add(Box.createHorizontalStrut(15)); sevenToNine.add(new JButton("9")); //สราง Box ใหญสําหรับใส Box เล็ก Box intermediatePanel = Box.createVerticalBox(); BoxLayout intermediateLayout = new BoxLayout(intermediatePanel,BoxLayout.Y_AXIS); intermediatePanel.add(oneToThree);; //ใส component คั่นระหวาง Box ยอยๆ

Page 10: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 10

intermediatePanel.add(Box.createVerticalStrut(25)); intermediatePanel.add(fourToSix); intermediatePanel.add(Box.createVerticalStrut(25)); intermediatePanel.add(sevenToNine); add(intermediatePanel); } public static void main(String[] args) { GlueDemo app = new GlueDemo(); JFrame f= new JFrame("Glue and Strut Demo"); f.getContentPane().add(app); f.pack(); f.show(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } } ผลลัพธ

ตัวอยางที่ 1.3 แสดงการใชงาน Box ในอีกรูปแบบหนึ่ง /*--------------------file Box2.java-----------------------*/ import java.awt.*; import javax.swing.*; public class Box2 extends JPanel { public Box2() { Box box = Box.createVerticalBox();

Page 11: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 11

add(box); JLabel l1 = new JLabel("Times Roman Plain 36"); l1.setFont(new Font("TimesRoman",Font.PLAIN,36)); JLabel l2 = new JLabel("Times Roman Bold Italic 20"); l2.setFont(new Font("TimesRoman",Font.BOLD & Font.ITALIC,20)); JLabel l3 = new JLabel("Helvetica Plain 20"); l3.setFont(new Font("Helvetica",Font.PLAIN,20)); JLabel l4 = new JLabel("Helvetica Italic 18"); l4.setFont(new Font("Helvetica",Font.ITALIC,18)); JLabel l5 = new JLabel("Sans Serif Plain 16"); l5.setFont(new Font("SansSerif",Font.PLAIN,16)); JLabel l6 = new JLabel("Sans Serif Bold Italic 14"); l6.setFont(new Font("SansSerif",Font.BOLD & Font.ITALIC,14)); JLabel l7 = new JLabel("Monopaced Plain 14"); l7.setFont(new Font("Monospaced",Font.PLAIN,14)); JLabel l8 = new JLabel("Dialog Bold 12"); l8.setFont(new Font("Dialog",Font.BOLD,12)); box.add(l1); box.add(Box.createVerticalStrut(15)); box.add(l2); box.add(Box.createVerticalStrut(15)); box.add(l3); box.add(Box.createVerticalStrut(15)); box.add(l4); box.add(Box.createVerticalStrut(15));

Page 12: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 12

box.add(l5); box.add(Box.createVerticalStrut(15)); box.add(l6); box.add(Box.createVerticalStrut(15)); box.add(l7); box.add(Box.createVerticalStrut(15)); box.add(l8); } public static void main(String[] args) { Box2 app = new Box2(); JFrame f= new JFrame("Box Demo"); f.getContentPane().add(app); f.pack(); f.show(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } } ผลลัพธ

Page 13: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 13

การนํา Swing components มาใชงานสามารถทําไดโดยการสราง Component (Object) จาก class ที่ใชสราง component นั้นๆ เชนตองสราง button ก็จะตองสราง component จาก class JButton เปนตน หลังจากสราง component เสร็จแลว (ยกเวน Top-level window component) หากตองการนํา component นั้นมาแสดงบน Top-level window components ก็ใหทําการ add component นั้นลง contentpane ซ่ึงเปน container ของ Top-level window components โดยการสง component ดังกลาวเปน parameter ใหกบั method add() ของ container และหากตองการให Top-level window component มีการจัด Layout manager แบบใด ก็ใหจดัการผาน Container ของ Top-level window component นั้นๆ

เนื่องจาก Component ตางๆไดทําการ Implement และสืบทอดคุณสมบัติตางๆมาจาก Interface และ Class ตางๆมากมาย ดังนัน้เพื่อใหสามารถเรียกใช ตวัแปร และ Methods ของแตละ Component ไดสะดวก จึงไดสรุปเกี่ยวกับตัวแปร และ Method บางสวนที่ใชงานบอยๆ ของ Class หลักๆที่ขยายไปสู Class ที่ใชสราง Component ดังตารางตอไปนี ้

ตารางแสดง Method ของ Class Component ท่ีใชงานบอยๆ Method ความหมาย

public Color getBackground() คืนคาสี Background ของ Component นั้นๆเปน Object ของ Class Color

public Rectangle getBounds() คืนคา Bound ของ Component เปน Object ของ Class Rectangle

public Component getComponentAt(int x,int y) คืน Component ที่วางอยู ณ.ตําแหนง x,y public Component getComponentAt(Point p) คืน Component ที่วางอยู ณ.ตําแหนง point public Cursor getCursor() คืนคา Cursor ที่ใชใน Component ขณะนัน้ public Font getFont() คืนคา Font ที่ Component นั้นใชงานอยู public FontMetrics getFontMetrics(Font font) คืนคาตระกูล Font ตาม font ที่ระบุ public Color getForeground() คืนคาสี Foreground ของ Component public Graphics getGraphics() คืนคา Object ของ class Graphics public Point getLocationOnScreen() คืนคา Point ณ.ตําแหนงที่ Component วางอยู

บน top-level containers public String getName() คืนคาชื่อ Component นั้นๆ public Dimension getPreferredSize() คืนคา preferred size ของ Component เปน

Dimension Object

Page 14: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 14

public Dimension getSize() คืนคาขนาดของ Component เปน Dimension Object

public Toolkit getToolkit() คืนคา Toolkit Object(เครื่องมืออํานวยความสะดวกชนิดหนึ่ง)

public boolean isEnableed() คืนคา true เมื่อ Component นั้น Enable public boolean isFocuable() คืนคา true เมื่อ Component นั้น Focused public boolean isFocusOwner() คืนคา true เมื่อ Component นั้น Focused public boolean isVisible() คืนคา true เมื่อ Component นั้นมองเหน็ได public void requestFocus() กําหนดให Cursor มา Focus ที่ Component

นั้นๆ public void setBackground(Color c) กําหนดสี Background ใหกบั Component

Public void setBounds(int x,int y,int width,int height)

กําหนด Bounds ที่ตําแหนง x,y และความกวางความสูงเทากบั width และ height ใหกับ Component ซ่ึง Method นี้จะใชเมื่อมีการจัด Layout เปน XYLayout (null Layout)

public setBounds(Rectangle r) กําหนด Bounds ตาม r ซ่ึงเปน Object ของ Class Rectangle ใหกับ Component ซ่ึง Method นี้จะใชเมื่อมีการจัด Layout เปน XYLayout (null Layout)

public void setCursor(Cursor cursor) กําหนดการแสดง Cursor ตาม cursor ที่กําหนด public void setEnabled(boolean b) กําหนดให Component Enabled เมื่อสงคาเปน

true และ Disable เมื่อสงคาเปน false public void setFocusabled(boolean focusable) กําหนดให Component นัน้ๆ Focus ไดหรือไม

โดยหากสงคาเปน true ก็จะ Focus ได หากไมตองการใหสงคาเปน false

public void setFont(Font f) กําหนด Font ใหกับ Component public void setForeround(Color c) กําหนดสี Foreground ใหกับ Component public void setLocation(int x,int y) เล่ือนตําแหนง Component ไปยังจุดที่ตองการ public void setLocation(Point p) เล่ือนตําแหนง Component ไปยัง Point ที่ตองการ public void setName(String name) กําหนดชื่อใหกับ Component

Page 15: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 15

public void setSize(Dimension d) กําหนดขนาดใหกับ Component ตาม Dimension ที่กําหนด

public void setSize(int width,int height) กําหนดความกวางสูงใหกับ Component public void setVisible(boolean b) กําหนดการแสดงผล Component โดยหาก

ตองการใหมองเห็น Component ใหสงคา true และหากไมตองการใหมองเปนใหสงคา false

public void validate() กําหนดให Component มีความเปนปจจุบนัมากที่สุดใชงานในกรณีที่มีการปรับเปลี่ยนคาตางๆของComponent แลวตองการให Component นั้นแสดงคาปจจุบนัมากที่สุด

ตารางแสดง Method ของ Class Container ท่ีใชงานบอยๆ

Method ความหมาย public Component add(Component comp) เพิ่ม Component ใหกับ Container public void add(Component comp Object constraints)

เพิ่ม Component ใหกับ Containers โดย constraints หมายถึงการจดั Layout Managerเชน BorderLayout.NORTH

public int getComponentCount() คืนคาจํานวน Component ที่มีอยูใน Container public Component[] getComponent() คืนคา Array ของ Componentsที่มีอยูใน Container public LayoutManager getLayout() คืนคา Layout manager ของ Container นั้นๆ public Dimension getMaximumSize() คืนคา Maximum size ของ Container ที่เปน

Dimension Object public Dimension getMinimumSize() คืนคา minimum size ของ Container ที่เปน

Dimension Object public Dimension getPreferredSize() คืนคา preferred size ของ Container เปน Dimension

Object public void remove(Component comp) Remove component ออกจาก Container ตาม comp

ที่ระบุ public void removeAll() Remove component ทั้งหมดออกจาก Container public void setFont(Font f) กําหนด Font ที่ตองการใชงานใหกับ Container

Page 16: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 16

public void setLayout(LayoutManager mgr) กําหนดการจดัวาง Layout Manager ตาม mgr ที่กําหนด

public validate() ปรับปรุง Container ใหมีคาตางๆเปนปจจุบนัมากที่สุด(รวมถึง sub Container ดวย)

ตารางแสดง Method ของ Class Window ท่ีใชงานบอยๆ

Method ความหมาย public Window(Frame owner) Constructor ใชสราง Window โดยระบวุา

Frame ใดเปน Owner(ผูสราง) public Window(Window owner) Constructor ใชสราง Window โดยระบวุา

Window ใดเปน Owner(ผูสราง) public Toolkit getToolKit() คืนคา Toolkit Object public void dispose() ทําลาย window นั้นๆเพื่อคนืหนวยความจํา

ใหกับระบบปฏิบัติการนําไปใชงานอยางอืน่ตอไป

public void hide() กําหนดใหมองไมเห็น window ทางจอภาพสามารถใช setVisible(false) แทนได

public void pack() กําหนดใหขนาดของ window พอดีกับขนาดของ preferred size ของ Component ตาม Layout manager นั้นๆ

public void setCursor(Cursor cursor) กําหนดการใชงาน Cursor ใหกับ window public void show() กําหนดใหมองไมเห็น window ทางจอภาพ

สามารถใช setVisible(true) แทนได

ตารางแสดง Method ของ Class Frame ท่ีใชงานบอยๆ Method ความหมาย

public Fame() Constructor ใชสราง Frame วางๆขึ้นมา public Frame(String title) Constructor ใชสราง Frame พรอมระบุขอความ Title

Bar ตาม title ที่กําหนด Public Image getIconImage() คืนคา Icon ของ Frame กลับมาเปน Image Object Public String getTitle() คืนคา Title bar ของ Frame เปน String

Page 17: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 17

public void hide() กําหนดใหมองไมเห็น Frame ทางจอภาพสามารถใช setVisible(false) แทนได

public boolean isResizeable() ตรวจสอบวาสามารถใช Resize ขนาดของ Frame ไดหรือไมโดยจะคืนคา true หากสามารถ Resize ได

public void setIconImage(Image image) กําหนด Icon ใหกับ Frame ตาม Image ที่กําหนด public void setMaximizedBounds (Rectangle bound)

กําหนดขนาดของ Frame เมื่อมีการคลิกที่ปุม Maximize ตาม bounds ที่กําหนด

public void setMenuBar(MenuBar mb) กําหนด MenuBar ให Frame public void setResizeable(boolean resizable)

กําหนดใหสามารถ Resize ขนาดของ Frame ไดหรือไม โดยหากตองการใหสามารถ Resize ได ก็ใหสงคา true ถาไมตองการใหสงคา false

public void setTitle(String title) กําหนดขอความ TltleBar ใหกับ Frame ตาม title ที่กําหนด

public void show() กําหนดใหมองเปน Frame ทางจอภาพ สามารถใช setVisible(true) ทานได

ตารางแสดง Method ของ Class Dialog ท่ีใชงานบอยๆ

Method ความหมาย public Dialog(Dialog owner) Constructor ใชสราง Dialog แบบไมเปน modal

โดยระบวุามี Dialogใดเปน owner public Dialog(Dialog owner ,String title) Constructor ใชสราง Dialog แบบไมเปน modal

โดยระบวุามี Dialog ใดเปน owner และกาํหนด TitleBar ใหกบั Dialog ผาน title

public Dialog(Dialog owner ,String title ,boolean modal)

Constructor ใชสราง Dialog แบบสามารถเลือกใหเปน modal หรือไมก็ไดโดยระบวุามี Dialog ใดเปน owner และกําหนด TitleBar ใหกับ Dialog ผาน title และหากตองการให Dialog เปน modal ก็ใหสงคา true ใหกับ modal

public Dialog(Frame owner) Constructor ใชสราง Dialog แบบไมเปน modal โดยระบวุามี Frame ใดเปน Owner

Page 18: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 18

public Dialog(Frame owner ,boolean modal) Constructor ใชสราง Dialog โดยระบวุามี Frameใดเปน Owner และหากตองการให Dialog เปน modal ก็ใหสงคา true ใหกับ modal

public Dialog(Frame owner ,String title) Constructor ใชสราง Dialog แบบไมเปน modal โดยระบวุาม ี Frame ใดเปน Owner พรอมกําหนด TitleBar ใหกับ Dialog ผาน title

Public Dialog(Frame owner ,String title ,boolean modal)

Constructor ใชสราง Dialog โดยระบุวามี Frame ใดเปน Owner และหากตองการให Dialog เปน modal ก็ใหสงคา true ใหกับ modal พรอมกับสามารถกําหนดขอความ TitleBar ใหกับ Dialog ผาน title

public void dispose() ใชทําลาย Dialog(เปน Overrided Method ของ class Window)

public String getTitle() คืนคา Title ของ Dialog กลับมาเปน String public void hid() กําหนดใหมองไมเห็น Dialog ทางจอภาพ

สามารถใช setVisible(false) แทนได public boolean isModal() คืนคา true เมื่อ Dialog เปน modal public boolean isResizabe() คืนคา true ถา Dialog สามารถ Resize ได public void setModal(boolean b) กําหนดให Dialog เปน modal หรือไมโดยหาก

ตองการให Dialog เปน modal ใหสงคาเปน true public void setResizable(boolean resizeable) กําหนดให Dialog สามารถ Resize ไดหรือไม

โดยหากสงคาเปน true หมายถึงกําหนดให Dialog สามารถ Resizeได

ตารางแสดง Method ของ Class JComponent ท่ีใชงานบอยๆ

Method ความหมาย public Border getBorder() คืนคา Border ของ Swing Component เปน Border

Object public Graphics getGraphics() คืนคา Graphics Object public int getHeight() คืนคาความสูงของ Swing Component public Insets getInsets() คืนคา Inset Object ของ Swing Component นั้นๆ

Page 19: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 19

public Dimension getMinimumSize() คืนคาขนาดของ Minimum Size ของ Swing Component เปน Dimension Object

public Dimension getMaximumSize() คืนคาขนาดของ Maximum Size ของ Swing Component เปน Dimension Object

public Dimension getPreferredSize() คืนคา Prefered Size เปน Dimension Object public String getToolTipText() คืนคา Tool tip ของ Swing Component นั้นๆ public int getWidth() คืนคาความกวางของ Swing Component public void requestFocus() กําหนดให Cursor มา Focus ที่ Swing Component

นั้นๆ public boolean requestFocusInWindow() กําหนดให Cursor มา Focus ที่ top-level window นั้นๆ public void setBorder(Border borde) กําหนด Border ใหกับ Swing Component ตาม border

ที่กําหนด public void setBackground(Color bg) กําหนดสีพื้นหลังใหกับ Swing Component ตาม bg ที่

กําหนด public void setEnabled(boolean enable) กําหนดให Swing Component Enable หรือไม โดย

หากตองการให Enable ใหสงคา true public void setFont(Font font) กําหนดชนิด Font ที่ตองการนําไปใชกบัswing

Component ตาม font ที่กําหนด public setForeground(Color fg) กําหนดสีพื้นหนาใหกับ Swing Component ตาม fg ที่

กําหนด public void setMaximumSize(Dimension maximumSize)

กําหนด Maximum size ของ Swing Component ตาม maximumSize ที่กําหนด

public void setMinimumSize(Dimension minimumSize)

กําหนด Minimum size ของ Swing Component ตาม minimumSize ที่กําหนด

public void setPreferredSize(Dimension preferredSize)

กําหนด Preferred size ใหกับ Swing Component ตาม preferred size ที่กําหนด

public void setToolTipTex(String text) กําหนดขอความ Tool tip ใหกับ Swing Component ตาม text ที่กําหนด

public void setVisible(boolean aFlag) กําหนดให Swing Component สามารถมองเห็นไดหรือไมโดยสงคา true ถาตองการใหมองเหน็และสงคา false ถาไมตองการใหมองเห็น

Page 20: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 20

1.3 Container JFrame เปน Top-Level Container ตัวหนึง่ของ swing และเปนตวัที่มีความสําคัญที่สุด ซ่ึงตามปกติการสราง swing เรามักจะใช Jframe เสมอ โดยใชสําหรับสรางหนาตางที่ใหญที่สุดของโปรแกรม

ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class JFrame คาคงที่/Method ความหมาย

public static final int DISPOSE_ON_CLOSE ทําลายและปด Window โดยอัตโนมัติ public static final int EXIT_ON_CLOSE ออกจากโปรแกรมและปด Window โดย

อัตโนมัติ public static final int DO_NOTHING_ON_CLOSE

ปองกันการกดปุม Close(เมื่อกดแลวไมปด Window)

public static final int HIDE_ON_CLOSE ปดแลวซอน Window โดยอัตโนมัติ public JFrame() สราง Frame วางๆขึ้นมา public int getDefaultCloseOperation() คืนคาคงที่ที่ใชสําหรับจัดการกับ Frame ที่

กําหนดผาน Metod setDefaultCloseOperatio() public JFrame(String title) สราง Frame วางๆขึ้นมาพรอมกับกําหนด

ขอความ Title Bar ผาน title public JMenuBar getJMenuBar() คืนคา Menu Bar Object ของ Frame public Container getContentPane() คืนคา Content Pane ซ่ึงเปน Container ของ

Frame เพื่อใชสําหรับวาง Component ตัวอ่ืนๆลงไป

public void remove(Component comp) Remove Component ออกจาก Container ของ Frame

public void setContentPane(Container contentPane)

ใชกําหนด Content pane ใหกับ Frame ซ่ึงมักใชคูกับ Panel

public void setDefaultCloseOperation(int operation)

กําหนดการทํางานเมื่อกดปุม Close ของ Frame โดย operation จะหมายถึงคาคงที่ที่ไดกลาวถึงในตารางขางตน

public void setLayout(LayoutManager mng) กําหนด layout ใหกับ Content pane ของ Frame public void setMenuBar(JMenuBar menu) กําหนด Menu Bar ใหกับ Frame

Page 21: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 21

ตัวอยางที่ 1.4 แสดงการใชงาน JFrame /*---------------------------file MyFrame.java----------------------------*/ import java.awt.*; import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame jFrame = new JFrame("My Frame"); jFrame.setVisible(true); //jFrame.show(); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE); } } ผลลัพธ

Constructor ของ Class Jframe รับ prarameter string ที่เราตองการกาํหนดใหเปนชื่อของหนาตางที่เราสรางขึ้น ซ่ึงในที่นี้คือ My Frame (ลองขยายหนาตางดูจะเห็นคําวา My Frame) ตามปกติแลว Object หรือ Instant ของ Jframe จะมองไมเห็น เราตองสั่งใหแสดงผลดวย Method setVisible(true) หรือ Method show() เมื่อตองการใหแสดงผล และ setVisible(false) ถาไมตองการใหแสดงผล JFrame เปน Container แตเนือ่งจากในโปรแกรมเรายังไมไดบรรจุ Component ใดๆลงไป จึงแสดงเฉพาะสวนหวั ตวัอยางที่ 1.5 แสดงการใส Component(button) ลงใน Frame /*---------------------------file MyFrame2.java----------------------------*/ import java.awt.*; import javax.swing.*; public class MyFrame2 { public static void main(String[] args) { JFrame jFrame = new JFrame("My Frame");

Page 22: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 22

JButton button=new JButton("OK"); jFrame.getContentPane(); jFrame.add(button); jFrame.pack(); jFrame.setVisible(true); //jFrame.show(); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE); } } ผลลัพธ

การทํางานของโปรแกรมจะทําการสราง Frame ขึ้นมาจากนั้นสราง Button ขึ้นมาหนงึปุมแลว add ลงไปใน Frame จากผลลัพธเราจะเหน็วามปีุม OK ปรากฏอยูใน ContentPane ของ Fame ตัวอยางที่ 1.6 แสดงการสราง JFrame และการ Remove Component ออกจาก Frame /*------------------file CreateFrame.java -----------------*/ import java.awt.* ; import javax.swing.* ; public class CreateFrame { public static void main(String[] args) { JButton b1,b2; Container c ; Image logo; JFrame f = new JFrame("Test Frame"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); c=f.getContentPane(); c.setLayout(new FlowLayout()); b1 = new JButton("OK"); b2= new JButton("Cancel");

Page 23: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 23

c.add(b1); c.add(b2); f.setSize(200,100); f.show(); try { Thread.sleep(3000); c.remove(b1); c.validate(); c.repaint(); } catch (Exception e) { System.out.println(e.getMessage()); } } }

การทํางานของโปรแกรม จากตัวอยางสราง Frame f ขึ้นมาตามปกติโดยวางปุม b1 และ b2 ลงใน Container ของ Frame หลังจากนัน้หนวงเวลาไว 3 วินาที แลวทําการ Remove Component b1 ออกจาก Container หลังจากนั้นสั่งให Container ทําการ Validate แล Repaint ใหมอีกครั้งเพื่อใหได Frame ที่มีคาตางๆเปนปจจุบันมากทีสุ่ด ซ่ึงจากผลลัพธจะเหน็วารูปที่ 1 ประกอบดวยปุม 2 ปุมและรูปที่ 2 มีปุมเพียงปุมเดียวเพราะมีการ Remove ปุมที่ 1 ออกไปแลวนั่นเอง 1.4 JButton Button ใน Swing มีหลายประเภทไดแก AbstractButton (เปน Abstract Class ที่นิยามพฤติกรรมหรือการทํางานพื้นฐานที่ทุก Swing Button จะตองมี) , JButton , JMenuitem , JCheckBoxMenuItem , JMenu , JRadioButtonMenuItem , JToggleButton , JCheckBox , และ JRadioButton

Page 24: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 24

Button หลากหลายประเภทเหลานี้ จะจัดเรียงเปนลําดับชั้นเพื่อการเรียกใช Method ของกันและกนัดังนี ้

Constructor และ Method ท่ีสําคัญของ AbstractButton Constructor/Method ความหมาย

AbstractButton() No-argument constructor void doClick() Programmatically simulate the user activating, orclicking,

the button.Typically,this method is not called by application

Icon getDisableIcon() Return the icon that represents the disabled state of the button.

Icon getDisabledSelectedIcon() Return the icon that represents the disabled state and selected state of the button.

int getHorizontalAlignment() Gets the button’s policy for aligning its text an icon whithin its display area. The valid values are AbstractButton.LEFT, AbstractButton.CENTER ,or AbstractButton.RIGHT

int getHorizontalTextPosition() Gets the position in which the button text label is drawn relative to its icon.

int getIcon() Gets the default icon used when one is not specified. Insets getMargin() Gets the insets object that defines the margin between the

button’s border and label

JButton JMenuItem

JCheckBoxMenuItem JMenu

JCheckBox JRadioButton

JRadioButonMenuItem

JToggleButton

AbstractButton

JComponent

Page 25: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 25

int getMnemonic() Gets the mnemonic key that activates this button. Icon getPressedIcon() Returns the icon that represents the state when the button

is pressed. Icon getRolloverIcon() Gets the icon displayed when the button is in the rollover

state, that is,when the mouse is placed overed the button. Icon getRolloverSelectedIcon() Gets the icon used to display the button face when the

button is selected while in the rollover state. Icon getSelectedIcon() Gets the icon displayed on the button face when the

button is selected. Object[] getSelectedObjects() Returns an array of one element that contains the button’s

label if selected. String getText() Returns the text used as the button label. int getVerticalAlignment() Return the button’s vertical alignment, either

SwingConstants.TOP,SwingConstants.CENTER, or SwingConstants.BOTTOM.

int getVerticalTextPosition() Gets the vertical position in which the button labels is drawn,relative to its icon.

boolean isRolloverEnable() Indicates whether the rollover state is currently set for this button.

boolean isSelected() Return the disposition of selected state of the button. void setDisabledIcon(Icon disabled) Sets the icon used to display the disabled state for this

button. void setDisableSelectedIcon(Icon disSellec)

Sets the icon used to represent the selected disabled state.

void setEnabled(boolean b) Sets the enabled disposition of the button to either enable or disable it.

void setHorizontalAlignment(int align)

Sets the horizontal alignment of this button’s text and icon within the its display area. Valid value are SwingConstants.CENTER, SwingConstatnts.LEFT, or SwingConstants.RIGHT,or SwingConstants.RIGHT

void setHorizontalTextPosition(int Relative to the placement of its icon. Valid values are

Page 26: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 26

align) SwingConstants.CENTER,SwingConstants.LEFT, SwingConstants.RIGHT,SwingConstants.LEADING, of SwingConstants.TRAILING.

void setIcon(Icon defaulticon) Sets the default icon used by this button when no other is specified.

void setmarginIInsets insets) Sets the insets object used by the button. void setMnemonic(int mnemonic) Sets the mnemonic key represented by the numeric code

that represents the keyboard key that the activates this button.

void setMnemonic(char mnemonic) Sets the mnemonic key represented by the specified character.

void setPressedicon(Icon pressedIcon)

Sets the icon that is displayed to indicate the button is in the pressed state.

void setRolloverIcon(Icon rolloverIcon)

Sets the icon displayed when the button is in the rollover state,that is, when the mouse is over the button.

void setRolloverEnabled(boolean b) Sets the button to the rollover state. void setRolloverSelectedIcon(Icon rolloverSelectedIcon)

Sets the icon displayed when the button is selected while in th rollover state.

void setSelected(boolean b) Sets the disposition of the selected state to the value specified. A value of True means the button is selected.

void setSelectedIcon(Icon selectedIcon)

Sets the icon displayed when the button is selected.

void setText(String text) Sets the text used for the button’s label. void setVerticalAlignment(int alignment)

Sets the vertical alignment of this button’s text and icon within the button’s display area. Valid vaues are SwingConstants.CENTER , SwingConstants.TOP , and SwingConstants.BOTTOM

Void setVerticalTextPosition(int textPosition)

Sets the vertical position of this button’s text label relative to the placement if this icon. Valid vaues are SwingConstants.CENTER , SwingConstants.TOP , and SwingConstants.BOTTOM

Page 27: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 27

ในการติดตอกบัผูช่ัวไปมักพบวามีการใช Button หรือปุมในลักษณะตางๆเปนเครื่องมืออยูเสมอ เชน บน Toolbar ,DialogBox เปนตน ลักษณะของปุมเปนดังนี ้

การสรางปุมจะใช Method add() มาชวยในการใสปุมลงไปใน Content Pane โดยแบงออกเปน 3 รูปแบบคือ o แบบไมมีขอความบนปุม

JButton button = new JButton(); add(button);

o แบบมีขอความบนปุม JButton button = new JButton(“ขอความบนปุม”); add(button);

o แบบสั้น โดยไมตองกําหนดชื่อปุม add(new JButton(ขอความบนปุม”);

Method ที่ใชบอยๆไดแก setLabel ใชเปล่ียนชื่อปุม โดยจะนําชื่อใหมไปแทนชื่อเดิม เชน button.setLabel(“ช่ือใหม”); getLabel ใชสําหรับสอบถามชื่อปุม โดยจะสงคามาเปนชื่อ Label เก็บไวในตัวแปร เชน String variable = button.getLabel(); ตัวอยางที่ 1.7 แสดงการสรางปุมบน Frame แบบไมแสดงชื่อปุม /*---------------------------file Button1.java----------------------------*/ import java.awt.*; import javax.swing.*; public class Button1 { public static void main(String[] args) { JFrame jFrame = new JFrame("Create Buttons on Fame"); JButton button1=new JButton();

Page 28: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 28

JButton button2=new JButton(); JButton button3= new JButton(); jFrame.getContentPane(); jFrame.setLayout(new FlowLayout()); jFrame.add(button1); jFrame.add(button2); jFrame.add(button3); jFrame.pack(); jFrame.setSize(300,100); jFrame.setVisible(true); //jFrame.show(); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE); } }

ตัวอยางที่ 1.8 แสดงการสรางปุมบน Frame แบบแสดงชือ่ปุม /*---------------------------file Button2.java----------------------------*/ import java.awt.*; import javax.swing.*; public class Button2 { public static void main(String[] args) { JFrame jFrame = new JFrame("Create Buttons on Fame"); JButton button1=new JButton("OK"); JButton button2=new JButton("Cancel"); JButton button3= new JButton("Printer..."); jFrame.getContentPane();

Page 29: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 29

jFrame.setLayout(new FlowLayout()); jFrame.add(button1); jFrame.add(button2); jFrame.add(button3); jFrame.pack(); jFrame.setSize(300,100); jFrame.setVisible(true); //jFrame.show(); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE); } }

ตัวอยางที่ 1.9 แสดงการสรางปุมบน Frame แบบแสดงชื่อปุมเชนเดียวกับตวัอยางที่ 1.5 แตใชรูปแบบการสรางปุมแบบสั้น /*---------------------------file Button3.java----------------------------*/ import java.awt.*; import javax.swing.*; public class Button3 { public static void main(String[] args) { JFrame jFrame = new JFrame("Create Buttons on Fame"); jFrame.getContentPane(); jFrame.setLayout(new FlowLayout()); jFrame.add(new JButton("OK")); jFrame.add(new JButton("Cancel")); jFrame.add(new JButton("Printer...")); jFrame.pack();

Page 30: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 30

jFrame.setSize(300,100); jFrame.setVisible(true); //jFrame.show(); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE); } }

ตัวอยางที่ 1.10 แสดงการสรางปุมบน Frame แบบแสดงชื่อปุมเชนเดียวกับตวัอยางที่ผานมา แตมีการใชคําสั่ง สอบถามชื่อปุม(Method getLabel) และเปลีย่นขอความบนปุม(setLabel) /*---------------------------file Button4.java----------------------------*/ import java.awt.*; import javax.swing.*; public class Button4 { public static void main(String[] args) { JFrame jFrame = new JFrame("Create Buttons on Fame"); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE); JButton button1=new JButton("OK"); JButton button2=new JButton("Cancel"); JButton button3= new JButton("Printer..."); jFrame.getContentPane(); jFrame.setLayout(new FlowLayout()); jFrame.add(button1); jFrame.add(button2); jFrame.add(button3); String button1_name = button1.getLabel(); String button2_name = button2.getLabel();

Page 31: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 31

String button3_name = button3.getLabel(); JLabel l1 =new JLabel("Button1_name = "+button1_name); JLabel l2 =new JLabel("Button2_name = "+button2_name); JLabel l3 =new JLabel("Button3_name = "+button3_name); jFrame.add(l1); jFrame.add(l2); jFrame.add(l3); jFrame.pack(); jFrame.setSize(300,150); jFrame.show(); try { Thread.sleep(4000); button1.setLabel("Yes"); button2.setLabel("No"); button3.setLabel("Cancel"); jFrame.validate(); //Jframe.repaint(); } catch (Exception e) { System.out.println(e.getMessage()); } } }

Page 32: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 32

1.5 JLabel JLabel ใชสําหรับแสดงขอความหรือ Icon ใดๆบนจอภาพ โดยมสามารถแกไขขอควมหรือ Icon นั้นได เรียกลักษณะเชนี้วา Read-only text การสราง Label มี Constructor ที่ใชงานแตกตางกันดังนี ้

• JLabel label = new JLabel(); • JLabel label = new JLabel(“ขอความ”);

Method ที่สําคัญไดแก setText() ใชสําหรับเปลี่ยนชื่อขอความของ Label ใหม โดยใชรูปแบบ label.setText(“ขอความใหม”); getText() ใชสําหรับสอบถามถึงขอความที่แสดงเปน Label แลวเก็บผลลัพธไวในตัวแปร โดยใชรูปแบบดังนี ้ String vaiable = label.getText(); Constructors และ Methods ของ JLabel มีดังนี ้

Constructor/Method ความหมาย Jlabel No-argument constructor that creates a Jlabe

instance with no disp[lay string or image JLabel(Icon image) Creates a Jlabel instance with the specified

image. Jlabel (Icon image, int horizontalAligment) Creates a Jlabel instance with the specified image

horizontally aligned within its display ares using the specified alignment

JLabel(String text) Creates a Jlabel instance that displays the specified text

JLabel(String text , Icon icon , int horizontalAlignment)

Creates a JLabel instance that displays the specified text and image, aligned as indicated by the horizontal alignment argument.

JLabel(String text , int horizontalAlignment) Creates a Jlabel instance that uses the specified text and horizontal alignment.

Icon getDisabledIcon() Returns the icon used to represent the disabled state of the label.

Page 33: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 33

int getDisplayedMnemonic() Returns the keycode that represents the label’s mnemoic key

int getHorizontalAlignment() Returns the label’s horizontal alignment within its display area.

int getHorizontalTextPosition() Returns the horizontal position of the label’s text ,relative to its image.

Icon getIcon() Returns the graphic icon image that the label displays.

int getIconTextGap() Returns the amount of space between the label’s test and its icon

Component getlabelFor() Gets the component labeled by this label String getText() Returns the label’s text string. int getVerticalAligment() Returns the label’s vertical alignment within its

display area. int getVerticaltextPosition() Returns the vertical position of the label’s text,

relative to its image. void setDisabledIcon(Icon disabledIcon) Sets the icon that tepresents the disabled state of

gthe label. void setDisplayedMnemonic(char aChar) Sets the list mnemonic character represented by

the specified char value void setDisplayedMnemonic(int key) Sets the list mnemonic character represented by

the specified integer key code void setHorizontalAlignment(int alignment) Sets the label’s horizontal alignment void setHorizontalTextPosition(int textPosition)

Sets the label text’s horizontal position relative to its image

void setIcon(Icon icon) Sets the icon this component will display. void setIconTextGap(int iconTextGap) St the space between the label’s text and icon void setLabelFor(Component c) Sets the component labeled by this label void setText(String text) Sets the text(a single line only) displayed as part

of this label

Page 34: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 34

void setVerticalAlignment(int alignment) Sets the vertical alignment of the label’s display attributes ,namely,text and icon

void setVerticalTextPosition(int textPosition) Sets the vertical position of th label’s text , relative to its icon image

ตัวอยางที่ 1.11 แสดงการสราง Label /*-----------------------file Label1.java------------------------*/ import java.awt.* ; import javax.swing.* ; public class Label1 extends JFrame { public Label1() { setTitle("ตัวอยางการสราง Label"); Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(new JLabel("Division of Information Technology")); c.add(new JLabel("Department of Information Technology & Communication")); c.add(new JLabel("Khonekaen technical Collage")); } public static void main(String[] args) { Label1 f = new Label1(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(350,100); f.show(); } }

Page 35: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 35

ตัวอยางที่ 1.12 การสราง Label พรอมกับเปลี่ยนขอความ Label ดวย Method setText() /*-----------------------file Label2.java------------------------*/ import java.awt.* ; import javax.swing.* ; public class Label2 extends JFrame { public Label2() { setTitle("ตัวอยางการสราง Label"); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel l1=new JLabel("Java appicaton"); JLabel l2=new JLabel("Java applet"); JLabel l3=new JLabel("Java Swing"); c.add(l1); c.add(l2); c.add(l3); setSize(350,100); show(); try { Thread.sleep(4000); l1.setText("Java"); l2.setText("Awt"); l3.setText("Swing"); } catch (Exception e){ System.out.println(e.getMessage()); } } public static void main(String[] args) { Label2 f = new Label2(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } }

Page 36: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 36

ตัวอยางที่ 1.13 แสดงการสราง Label พรอมดวย Icon /*--------------------file Label3.java-----------------------*/ import java.awt.*; import javax.swing.*; public class Label3 extends JFrame { public Label3() { super("การสราง Label พรอม Icon"); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel lb1 = new JLabel("label with text"); lb1.setToolTipText("This is label1"); c.add(lb1); Icon fish = new ImageIcon("goldFish.gif"); JLabel lb2= new JLabel("label with text and icon",fish,SwingConstants.LEFT); lb2.setToolTipText("This is label2"); c.add(lb2); JLabel lb3=new JLabel(); lb3.setText("label with icon and text at bottom"); lb3.setIcon(fish); lb3.setHorizontalTextPosition(SwingConstants.CENTER);

Page 37: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 37

lb3.setVerticalTextPosition(SwingConstants.BOTTOM); lb3.setToolTipText("This is label3"); c.add(lb3); setSize(275,170); show(); } public static void main(String[] args) { Label3 f = new Label3(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } }

1.6 JCheckBox CheckBox ทําหนาที่คลายกบัสวิต on-off หรือ yes-no ทุกๆครั้งที่คลิก checkbox จะเปลี่นสถานะจาก on เปน off หรือจาก off เปน on อยางใดอยางหนึ่ง Checkbox ประกอบดวย 2 สวนคือช่ือและสถานะ ช่ือเปนเท็กซซ่ึงแสดงไวถัดจากตัวกลองสี่เหล่ียมที่เปน checkbox ในขณะที่สถานะเปน boolean แสดงการถูกเลือหรือเช็ค ปกติแลวสถานะของ checkbox เปน false หรือ off เราสามารถสราง checkbox ไดหลายวิธี โดยใช class CheckBox ดังนี ้o การสราง checkbox โดยไมมช่ืีอ(คําอธิบายที่อยูตอทายกรอบสี่เหล่ียม

JCheckBox check = new JCheckBox(); o การสราง checkbox พรอมชื่อ

JCheckBox check = new JCheckBox(“ขอความ”); o การสราง chckbox พรอมกับสถานะ

JCheckBox check = new JCheckBox(“ขอความ” ,null , true);

Page 38: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 38

เมื่อ null ใชอางถึง checkbox group ที่เปนเจาของ checkbox นํามาใชในกรณีที่สรางปุม checkbox ดวย checkbox group แตปกติแลว checbox group เปน null สวน true หมายถึงใหใสเครื่องหมายถูก ไวที่ checkbox ดวย ถาไมตองการเครื่องหมายถูกใหกําหนดเปน false ลักษณะของ CheckBox Chechbox มี Methods ที่สําคญหลาย Method เชน getLabel() ใชสําหรับถามชื่อบน Checkbox setLabel () ใชสําหรับเปลี่ยนขอความทีแ่สดงใน Checkbox setSelected() ใชกําหนดสถานะของ Checkbox ตัวอยางที่ 1.14 แสดงการสราง Checkbox /*--------------------------file CheckBox1.java----------------------------*/ import java.awt.* ; import javax.swing.*; public class CheckBox1 extends JFrame { JLabel label1; JCheckBox check1; public CheckBox1() { setTitle("Test Checkbox"); Container c = getContentPane(); c.setLayout(new FlowLayout()); label1= new JLabel("Test Checkbox"); c.add(label1); //create checkbox check1=new JCheckBox("Click me if you like me"); c.add(check1); } public static void main(String[] args) {

Page 39: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 39

CheckBox1 f = new CheckBox1(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,100); f.show(); } }

1.7 JRadioButton ปุม radio มีไวเพื่อใหผูใชเลือกตัวเลือกไดเพียวตวัเลือกเดยีวภายในกลุมเดียวกัน การสรางและใชงานจะคลายกบั checkbox โดยจะใช class JRadioButton เพื่อสราง และใช class ButtonGroup เพื่อจัดกลุมของ radio Class JRadioButton มี constructosr และ Methods ที่สําคัญดังนี้

Constructor/Methods ความหมาย JRadioButton() No-argument constructor, which constructs a

radio button that has an empty label. JRadioButton(Icon icon) Constructs a radio button that displays the

specified icon. JRadioButton(Icon icon,boolean selected) Constructs a radio button that displays the

specified icon ,and that is initially in the indicates selection state.

JRadioButton(String text) Constructs a radio button that display the specified string as its text label.

JRadioButton(String text , boolean selected Constructs a radio button that display the specified string as its text label. and that is initially in the indicates selection state.

JRadioButton(String text ,Icon icon) Constructs a radio button that display the

Page 40: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 40

specified string as its text label ,and icon. JRadioButton(String text , Icon icon ,boolean selected)

Constructs a radio button that display the specified string as its text label and icon and that is initially in the selected state.

Class ButtonGroup มี Constructor และ Method ที่สําคัญดังนี ้

Constructors/Methods ความหมาย ButtonGroup() No-argument constructor, which constructs

anew button group object. void add(AbstractButton b) Adds the specified button to the button group. Enumeration getElements() Returns all buttons that are currently members

of this button group. ButtonModel getSelection() Return the currently selected button boolean isSelected(ButtonModel m) Indicates if the specified button is selected void remove(AbstractButton b) Removes the specified button from the button

group. void setSelected(ButtonModel m , boolean b) Set the specified button to the state represented

by the specified button model object. ตัวอยางที่ 1.15 แสดงการสราง RadioButton /*-------------------------file Radio1.java---------------------------*/ import java.awt.* ; import javax.swing.* ; public class Radio1 extends JFrame { JLabel label1; JRadioButton radio1,radio2,radio3; ButtonGroup buttonGroup; public Radio1(String title) { super(title);

Page 41: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 41

Container c=getContentPane(); c.setLayout(new FlowLayout()); label1 = new JLabel("Please, select that you like"); c.add(label1); buttonGroup = new ButtonGroup(); radio1=new JRadioButton("Favorite language is Java"); radio2=new JRadioButton("Favorite language is VB"); radio3=new JRadioButton("Favorite language is C++"); c.add(radio1); c.add(radio2); c.add(radio3); buttonGroup.add(radio1); buttonGroup.add(radio2); buttonGroup.add(radio3); } public static void main(String[] args) { Radio1 f= new Radio1("Radio Button Demo"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,150); f.show(); } }

Page 42: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 42

1.8 JComboBox ComboBox บางที่จะเรยีกวา drop-down list เนื่องจากสามารถเลื่อน scrollbar ขึ้นลง เพื่อคนหาตัวเลือกที่ตองการได การสราง ComboBox จะสรางจาก class JcomboBox ซ่ึงมี Constructors และ Methods ที่สําคัญดังนี้

Constructors/Methods ความหมาย JcomboBox() No-argument constructor that constructs a new

combo box JcomboBox(ComboBoxModel mode) Constructs a new combo box that uses the specifed

model to stoe its elements JcomboBox(Object[] items) Constructs a new combo box that stores the items in

the specified array JComboBox(Vector items) Constructs a new combo box that stores the items in

the specified vector void addItem(Object anItem) Add the specified item to this combo box Object getItemAt(int idex) gets the item located in the specifid index in this

combo box int getItemCount() Gets the number of items currently stored by combo

box int getMaximumRowCount() Gets the maximm number of items that can be

displayed without using a scroll bar int getSelectedIndex() Return the index of the selection item Object getSelectedItem() Gets the iem that is currently marked as selected Object[] getSelectedObjects() Returns an array whose elements is the single

selected item of this combo box void hidePopup() Closed the pop-up window used by the combo box to

display its elements void insertItemAt(Object item, int index) Inserts the specified item at the specified index boolean isEditable() Indicates whether the combo box items can be edited boolean isPopupVisible() Indicates if the pop-up that displays the conmbo box

items is visible void removeAllItem() Removes all items from this combo box

Page 43: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 43

void removeItem(Object item) Removes the specified item from this combo box void removeItemAt(int index) Removes the item at the index indicated from the

combo box void setEditable(boolean flag) Sets the editing policy for this combo box and

indicates if items can be edited void setEnabled(boolean enabled) Sets the enabled state of this combo box to either

enabled or disabled void setMaximumRowCount(int count) Sets the maximum number of rows that this combo

box can store void setPopupVisible(boolean v) Sets whether or not this combo box makes its pop-up

window visible void setSelectedIndex(int anIndex) Set the item represented by the specified void setSelectedItem(Object anObject) Set the state of the specified object to selected void showPopup() Display the pop-up window of this combo box ตัวอยางที่ 1.16 แสดงการสราง Combo box /*---------------------file JComboBox1.java-------------------*/ import java.awt.*; import javax.swing.*; public class JComboBox1 extends JFrame { public JComboBox1(String title) { super(title); Container c = getContentPane(); c.setLayout(new FlowLayout());

String[] daysweek = {"Sunday","Monday","Tuesday","Wednestday","Thursday","Friday" ,"Saterday"};

JComboBox combo1 = new JComboBox(daysweek); combo1.setEditable(true); combo1.setAlignmentX(Component.LEFT_ALIGNMENT); combo1.setMaximumRowCount(10); combo1.setSelectedIndex(2);

Page 44: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 44

c.add(combo1); JLabel label = new JLabel("select day of the week"); label.setHorizontalTextPosition(SwingConstants.CENTER); c.add(label); } public static void main(String[] args) { JComboBox1 f = new JComboBox1("Test ComboBox"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,150); f.show(); } } 1.9 JList JList เปน Component ตัวหนึ่งใน Swing ใชสําหรับสรางรายการ(List) ตัวเลือก ซ่ึงสามารถเลื่อนรายการเพื่อเลือกรายการใดรายการหนึ่งโดยเฉพาะ หรือเลือกหลายรายการในครั้งเดยีว การสรางตัวเอกรายการแบบ List นี้สารถสรางไดจาก Class JList การสรางตัวเลือกดวย JList สามารถกําหนดได 2 ชนิดคอื

1. ชนิดเลือกไดรายการเดยีว (Single-selection List) แบบนี้ผูใชสามารถเลือกรายการที่ตองการไดเพยีงรายการเดียว

2. ชนิดเลือกไดหลายรายการเดยีว (Multiple-selection List) แบบนี้ผูใชสามารถเลือกรายการที่ตองการไดมากกวาหนึ่งรายการ

Page 45: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 45

JList มี Constructors และ Method ท่ีสําคัญดังนี ้Constructors/Methods ความหมาย

JList() No-argument constructor. It constructs a Jlist with an empty data model.

JList(ListMode dataModel) Creates a JList populated with elements contained in the specified model.

JList(Object[] listData) Creates a JList populated with the elements in the specified array.

JList(Vector listData) Creates a JList populated with the elements in the specified vector.

void addSelectionIntevl(int anchor, int lead) Sets the list’s selection to be the union of the specified interval and the list’s current selection.

void clearSelection() Clear the list’s selection protectd ListSelectionModel createSelectionModel)

Returns an instance of DefaultListSelectionModel.

void ensureIndexIsVisible(int idex) Scrolls the viewport, if any, to make the element represented by the specified index completely visible.

protected void fireSelectionValueChanged(int firstIndex int lastIndex, boolean isAdiJusting)

Notifies registered listeners of a change in the list’s selection model.

int getAnchorSelectionIndex() Returns the value that representes the low index that marks the current selection from the most recent addSelectionInterval or setSelectionInterval call.

Rectangle getCellBounds(int index1, int index2)

Returns the bounds of the items contained in the range specified by the two index arguments.

ListCellRenderer getCellRenderer() Returns the object that renders the list items. int getFirstVisibleIndex() Returns the index of the first visible call,that is

,the cell in the upper-left coner of the JList.It returns -1 if nothing is visible or if the list is

Page 46: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 46

empty int getFixedCellHeight() Returns the value of the fixedCellHeight

variable. int getFixedCellWidth() Returns the value of the fixedCellWidth

property. int getLastVisibleIndex() Returns the index of the last visible cell,that is,

the cell in the lower right corner of the JList.It returns -1 if nothing is visible or if the list is empty.

int getLeadSelectionIndex() Returns the value of the index that marks the “lead” item of the set of selected itms.

int getMaxSelectionIndex() Returs the largest selected cell index. int getMinSelectionIndex() Returns the smallest selected cell index. ListModel getModel() Retrns the data model used by this JList to

store its elements. Dimension getPreferredScrollable ViewportSize()

Computes the sze of the view port needed to display the number of rows represented by the visibleRowCount variable.

Object getPrototypeCellValue() Returns the cell width used to represent the width of the cells for all the list’s elements.

int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)

Returns the value of the bloack increment,which is used to scroll the list by one block.

boolean getScrollableTracks ViewportHeight() Indicates if the heght of thisJList changes when the height of its Jviewport,if any,changes.

boolean getScrollableTracks ViewportWidth() Indicates if the heght of thisJList changes when the width of its Jviewport,if any,changes.

int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)

Returns the amount by which the list is scrlled during a units scroll event.

int getSelectedIndex() Returns the index of the first seleted item int[] getSelectedIndices() Returns an array of the indices of all the

Page 47: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 47

selected iems. Object getSelectedValue() Returns the value of the first selected item, or

null if nothing is selected Object[] getSelectedValues() Returns an array of the values of the selected

elements. Color getSelectionBackground() Returns background color used to paint the

selected cells. Color getSelectionForeground() Returns color used to paint the foreground of

the selected cells. int getSelectionMode() Indicates whether the selection policy is single-

item or multi-item. ListSelectionModel getSelectionMode() Returns he selection model object boolean getValueIsAdjusting() Indicates the adjustment state of the data

model, that is, the value of the model’s isAdjusting property.

int getVisibleRowCount() Return the preferred number of visible rows. Point indexToLocation(int index) Returns the point that represents the oriin of the

list item specified by the index argument. boolean isSelectedIndex(int index) Indicates if the element at the specified index is

seleted. boolean isSelectionEmpty() Indicates if there are any list elements

currently selected. int locationoIndex(Point location) Converts a point relative to the JList

component’s upper left corner to the index of the cell at the location.

void removeSelectionInterval(int index0 ,int index1)

Sets the list’s selection to be the difference between the specified interval and the current selection.

void setFixedCellHeight(int height) Defines the height of every cellin the list. void setFixedCellWidth(int width)

Defines the width of every cell in the list

Page 48: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 48

void setListData(Object[] listData) Constructs a ListModel object from the specified array of Objects and sets it to be the list’s model object.

void setListData(Vector listData) Constructs a ListModelobject from the specified Vector and sets it to be the list’s model object.

void setPrototypeCellValue(Object prototypeCellValue)

Sets the value of the list’s fixedCellWidth and fixedCellHeght variables.

void setSelectedIndex(int index) Sets the list’s selection to be the specified single cell.

void setSelectedIndices(int[] indices) Sets the list’s seletion to be the cells represented by the array of indices

void setSelectValue(Object anObject, boolean shouldScroll)

Sets the specified object to be the selected element of this list

void setSelectionBackground(Color selectionBackground)

Sets the color used to paint the background of selected cells.

void setSelectionForeground(Color selectionForeground)

Sets the color used to paint the foreground of selected cells.

void setSelectionInterval(int anchor, int lead) Sets the list’s selection to be the cells containedin the specified interval

void setSelectionMode(int selectionMode) Sets the selection policy for the list,either single-item or multiple-item selections

void setValueIsAjusting(boolean b) Sets the adjustment state of the data model. If tis is TRUE, only one selectiob events is fired when all the selections have stabilized,for example, when the user stops dragging the mouse

void setVisibleRowCount(int visibleRowCount)

Sets the preferred number of list rows to be displayed without using scrollbar

Page 49: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 49

ตัวอยางที่ 1.17 แสดงการสราง List แบบ Single-selection list /*---------------file SingleJList.java-------------*/ import java.awt.*; import javax.swing.* ; public class SingleJList extends JFrame { JLabel listStatus; JList list; String datelist[] = {"Sunday","Monday","Tuesday","Thursday","Friday","Saturday"}; public SingleJList() { setTitle("JList Test"); Container c=getContentPane(); c.setLayout(new FlowLayout()); list = new JList(datelist); list.setVisibleRowCount(4); //กําหนดไมใหเลือกไดมากกวา 1 ตัวเลือก list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); c.add(new JScrollPane(list)); } public static void main(String[] args) { SingleJList f = new SingleJList() ; f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,150); f.show(); } }

Page 50: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 50

ตัวอยางที่ 1.18 แสดงการสราง List แบบ Multiple-selection list /*---------------file MultipleJList.java-------------*/ import java.awt.*; import javax.swing.* ; public class MultipleJList extends JFrame { JLabel listStatus; JList list; String datelist[] = {"Sunday","Monday","Tuesday","Thursday","Friday","Saturday"}; public MultipleJList() { setTitle("MultipleJList Test"); Container c=getContentPane(); c.setLayout(new FlowLayout()); list = new JList(datelist); list.setVisibleRowCount(5); //กําหนดไมใหเลือกไดมากกวา 1 ตัวเลือก list.setFixedCellHeight(15); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //กําหนดใหใช Scrollpane c.add(new JScrollPane(list)); } public static void main(String[] args) { MultipleJList f = new MultipleJList() ; f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,150); f.show(); } }

Page 51: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 51

การเลือกรายการจาก List ทําไดโดยคลิกเมาสรายการที่ 1 แลวกดปุม ctrl พรอมกลับคลิกเลือกรายการตอไป 1.10 JTextField และ JPasswordField JTextField และ JPasswordField เปน Component หนึ่งใน Swing ซ่ึงมีโครงสรางการสืบทอด ดังนี ้

โดยมี Constructors และ Methods ที่สําคัญดังนี ้

Constructors / Methods ความหมาย JTextComponent() NO-argument constructor.It creates a new

JTextComponent static KeyMap addKeymap(String nm,Keymap parent)

Add a new keymap to the set of keymaps available to all text component

void copy() Copies the currently selected text to the system clipboard.

JPasswordField JTextPane

JTextField JTextArea JEditorPane

Javax.swing.text JTextComponent

JComponent

Page 52: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 52

void cut() Transfers the currently selected text to the system clipboard and deletes the contents from the text component.

AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Jcomponent.

Action[] getActions() Retrieves the list of editor commands. Caret getCaret() Retrieves the caret object associated with the

text component. The caret marks the current position in the document affected by editing actions.

Color getCaretColor() Indicates the current color used to display the caret.

int getCaretPosition() Returns the offset within the document from the beginning of the current caret position.

Color getDisabledTextColor() Indicates the color currently used to display disabled text.

Document getDocument() Fetches the document model object associated with this component’s text editor.

char getFocusAccelerator() Returns the key accelerator character that results in the target text component acquiring the keyboard focus.

Highligher getHilighlighter() Retrieves the highlighter object that does highlighting.

InputMethodRequests getInputMethodRequests()

Return an input method handler. This object handles input method requests for the text component.

Keymap getKeymap() Retrieves this text component’s currently active keymap.

static Keymap getKeymap(String nm) Retrieves the keymap with the specified name, which was previously added to the document used by this text component.

Page 53: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 53

Insets getMargin() Returns the insets object that represents the space between the text component’s border and its text.

Dimension getPreferredScrollable ViewportSize()

Returns the preferred size of the text component.

int getScrollableBlockIncrement(Rectangle visibleRect,int orientation,int direction)

Returns the scroll block increment amount that will expose one complete block of rows or columns as a result of a scroll operation.

boolean getScrollableTracks ViewportHeight() Indicates if this text component’s height should match the height of any view port the presents a view of its content.

boolean getScrollableTracks ViewportWidth() Indicates if this text component’s width should match the height of any view port the presents a view of its content.

int getScrollableUnitIncrement(Rectangle visbleRect, int orientation,int direction

Returns the scroll unit increment amount that will expose one complete row or column as result of scroll operation.

String getSelectedText() Returns this component’s currently selected text.

Color getSelectedTextColor() Retrieves the color currently used to display text that is selected.

Color getSelectionColor() Retrieves the color currently used to indicate selected text.

int getSelectionEnd() Returns the end position of the selected text. int getSelectionStart() Returns the start position of the selected text. String getText() Returns the text component’s text content. String getText(int offs,int len) Retrieves the subset of the text component’s

text delineated by two offsets, which represent caret position.

TextUI getUI() Fetches the user-interface factory for this text-oriented editor.

Page 54: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 54

boolean isEditable() Indicates whether or not the content of this component can be editor.

boolean isFocusTraversable() Returns true if this component can acquire the keyboard focus.

boolean isOpaque() Indicates if this component it completely opaque.

static void loadKeymap(Keymap map,JTextComponent , KeyBinding[] bindings , Action[] actions)

Loads an existing keymap with a set of key bindings

Rectangle modeToView(int pos) Converts the given position in the text component’s document to a location in the component’s view.

void moveCarePosition(int pos) Repositions the caret/ It sets a mark where the caret was located the last time setCarePosition was calles

protected String paramString() Returns a string representation of this JTextComponent.

void paste() Copies the contents of the system clipboard into this component’s text model.

void read(Reader in , Object desc) Initializes this component’s text content from a stream.

void removeCareListener(CareListener listener) Removes a previously registered listener for caret events.

static Keymap removeKeymap(String nm) Removes the specified keymap, which was previously added to the document, from the set of available keymaps.

void removeNotify() Notifies this component that it has been removed from the container in which it existed.

void replaceSelection(String content) Replaces the currently selected text with the specified string.

Page 55: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 55

void select(int selectionStart , int selectionEnd) Marks as selected the text delineated by the specified start and end positions.

void selectAll() Selects all the text in the text component. void setCare(Caret c) Set the caret to be used by this text

component. void setCaretColor(Color c) Set the color used to render the caret void setCaretPosition(int position) Sets the position of the caret for text insertion

operations. void setDisabledTextColor(Color c) Sets the color used to display text that is

marked disabled. void setDocument(Document doc) Set the document object used by this text

component. void setEdiable(boolean b) Specifies whether or not this text component

is editable. void setEnabled(boolean b) Sets the enabled state of the component. void setFocusAccelerator(char aKey) Sets the key accelerator whose activation will

cause the receiving text component to get the focus.

void setHighlighter(Highlighter h) Sets the highlighter used by the component. void setKeymap(Keymap map) Sets the keymap used by the component. A

keymap binds keys to actions. void setMargin(Insets m) Sets the text component’s insets object, which

specifies the amount of space between the component border.

void setOpaque(boolean o) Sets whether or not the UI should be opaque. void setSelectedTextColor(Color c) Sets the color used to display text marked

selected. void setSelectionColor(Color c) Sets the color used to highlight selected text. void setSelectionEnd(int selectionEnd) Sets the selection end to the specified offset

position within the document.

Page 56: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 56

void setSelectionStart(int selectionStart) Sets the selection start to the specified offset position within the document.

void setText(String t) Sets the text component’s contained text to the specified text.

void setUI(TextUI ui) Sets user-interface factory for this text-oriented editor

void updateUI() Reloads the pluggable UI. int viewToModel(Point pt) Produces the character position offset from

the beginning of the document, which represents the character closest to the specified point.

void write(Writer out) Loads the text compoment’s contents by reading the specified stream

JTextField และ JPasswordField ใชในการสรางและรับขอมูลจากผูใช โดยผูใชสามารถแกไขขอมูลที่ปอนเขามาไดดวย แตมีขอจํากัดวาจะรับขอมูลไดเพียง 1 บรรทัดเทานั้น โดย JPasswordField จะแสดงขอมูลที่ผูใชปอนเขามาเปนเครื่องหมาย * JTextField มี Constructors และ Methods ดังนี ้

Constructors / Methods ความหมาย JTextField() No-argument constructor, which constructs a

new text field JTextField(Document doc, String text , int columns)

Constructs a new JTextField that stores the specified text using the qiven text storage model and the given number of columns.

JTextField(int columns) Constructs a new text field with the specified number of columns and no initial content.

JTextField(String text) Constructs a new text field that initially contains the specified text.

JTextField9String text , int columns) Constructs a new text field with the specified text and number of column

Page 57: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 57

AccessibleContext getAccessibleContext() Get accessibleContext associated with this JTextField

Action[] getActions() Returns the list of editor commands. int getColumns() Returns the number of columns in this text

field int getHorizontalAligment() Returns the horizontal alignment of the text BoundRangeModel getHorizontalVisibility() Returns the range of text that is currently

visible Dimension getPreferredSize() Returns the preferred size of this text field. int getScrollOffset() Gets the scroll offset. String getUIClassID() Gets the class ID for a UI boolean isValidateRoot() Indicates whether or not calls to revalidate this

component will be processed by validating this component itself

void posActionEvent() Dispatches action events to registered listeners void removeActionListener(ActionListener l) Removes the specified action listener from the

notification list void scrollRectToVisible(Rectangle r) Scroll the field left or right void setActionCommand(String command) Sets the name of the string that represents the

name of the action command. void setColumns(int columns) Sets the number of columns and invalidates

the layout so the component will be redraw with the new number of columns

void setFont(Font f) Sets the font used to display the content void setHorizontalAligment(int alignment) Sets the horizontal alignment of the text void setScrollOffset(int scrollOffset) Sets the scroll offset

Page 58: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 58

JPasswordField มี Constructors และ Methods ดังนี ้Constructors / Methods ความหมาย

JPasswordField() No-argument constructor, which constructs a new JPasswordField

JPasswordField(Document doc, String txt, int columns)

Constructs a new JPasswordField with the specified number of columns and that uses the specified document storage model

JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.

JPasswordField(String text , int columns) Constructs a new JPasswordField with the specified number of column s and no content

void copy() Transfers the currently selected text range to the system clipboard.

void cut() Transfers the currently selected text range to the system clipboard, removing the contents from the model.

boolean echoCharIsSet() Returns true if this JPasswordField echos characters typed by the user

AccessibleContext getAccessibleContext() Gets the accessibleContext associated with this JPasswordField.

char getEchoChar() Returns the echo character char[] getPassword() Returns the text component’s currently

contained text. String getUIClassID() Returns the name of the LookAndFeel class

that renders this component protexted String paramString() Returns a string representation of this

JPasswordField void setEchoChar(char c) Sets the character used to echo user typing

Page 59: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 59

ตัวอยางที่ 1.19 แสดงการใชงาน JTextField และ JPasswordField /*-----------------------file JTextFieldTest.java----------------------*/ import java.awt.*; import javax.swing.*; public class JTextFieldTest extends JFrame { JTextField text1,text2,text3; JPasswordField password; public JTextFieldTest(String title) { super(title); Container c=getContentPane(); c.setLayout(new FlowLayout()); //สรางและกําหนดความกวางของ JTextField ที่ 1 เปน 10 คอลัมน โดยไมมี //ขอความใดๆ text1 = new JTextField(10); c.add(text1); //สรางและกําหนดความกวางของ JTextField ที่ 2 text2 = new JTextField("Enter text here"); c.add(text2); //สรางและกําหนดความกวางของ JTextField ที่ 3 โดยแสดงขอความ //และกําหนดไมใหสามารถแกไขขอความ //โดยใชคําสั่ง setEditable(false) text3 = new JTextField("Uneditable text field",20);

text3.setEditable(false); c.add(text3); //สราง JPasswordField password= new JPasswordField("Hidden text"); c.add(password); }

Page 60: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 60

public static void main(String[] args) { JTextFieldTest f = new JTextFieldTest("JTextField and JPasswordField Test"); f.setDefaultCloseOperation(EXIT_ON_CLOSE); f.setSize(320,100); f.setVisible(true); } }

จอภาพแสดงผลเริ่มตน

จอภาพเมื่อพิมพขอความลงไป

1.11 JTextArea JTextArea ใชสําหรับรับหรือแสดงขอความจํานวนมาก เพราะสามารถแสดงไดหลายบรรทัด และมีสกรอบารสําหรับเล่ือนดูขอมูลใหทั้งในแนวตั้งและแนวนอน เราสามารถสราง textarea ไดจาก class JTextArea โดยมี Constructors และ Methods ที่สําคัญดังนี้

Constructors /Methods ความหมาย JTextArea() No-argument constructor that constructs a nw

JTextArea JTextArea(Document doc) Constructs a new JTextArea whose content is

initialized to display the text in the specified document

JTextArea(Document doc, String text,int rows,int columns)

Constructs a new JTextArea with the specified number of rows and columns, initialized to the contents of the specified document

JTextArea(int row, int column) Constructs a new JTextAra with the specified

Page 61: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 61

number of rows and columns , but initialized with no content

JTextArea(String text) Constructs a new JTextArea that display the specified text

JTextArea(String text,int rows , int columns) Constructs a new JTextArea with the specified number of rows and columns, initialized to contain the specified text

void append(String str) Appends the specified text to the end of the document

Protected Document createDefaultMode() Creates the document mplementation that is used by default if none is specified in a constructor

AccessibleContext getAcessibleContext() Get the AccessibleContext associated with this JTextArea

int getColumns() Returns the number of columns that this text area display

protected int getColumnWidth() Gets the width in pixels of a display column int getLineCount() Returns the number of lines of content contined

in the text area component int getLineEndOffset(int line) Determins the offset of the character at the end

of the secified lice, relative to the beginning of the document

int getLineOffOffset(int offset) Translates the specifiedncharacter offset, relative to the beginning of the document, into a line number

int getLineStartOffset(int line) Returns the offset of the first character of the specified line, relative to the beginning of the document

boolean getLineWrap() Indicates the line-wrapping policy of the text area

Dimension getPreferredScrollable Returns the preferred size of the viewport that

Page 62: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 62

ViewportSize() contains this component Dimension getPreferredSize() Returns the preferred size of the text area protected int getRowHeight() Indicates the height of a row int getRow() Returns the number of rows in the text area boolean getSrollabeTracks ViewportWidth() Indicates if he text area’s view port forces the

text area to have the view port’s width int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)

Returns the unit increment that enables one whole row to be scrolled up or down

int getTabSize() Gets the number of character equivalent to a tab

String getUIClassID() Returns the class ID for the UI boolean getWrapStyleWord() Gets the wrap-style used when wrapping is

enabled void insert(String str, int pos) Insertsthe specified textat the specified position boolean inManagingFocus() Disables the traversal effect of tabs protected String paramString() Returns a string representation of the text area

instance protected void processComponentKeyEvent(KeyEvent e)

Consumes TAB and Shift-TAB events

void replaceRange(String str, int start, int end) Replaces the txt delineated by the specified start and end position with the new text specified.

void setColumns(int columns) Sets this text area’s number of columns. void setFont(Font f) Sets the current font used to display the text

area’s content void setLineWrap(boolean wrap) Sets the line-wrapping policy of the text area void setRow(int rows) Sets the number of rows for this text area Void setTabSize(int size) Sets the number of characters to be equivalent

to a tab void setWrapStyleWord(boolean word) Sets the wrap style used when line wrapping is

enabled

Page 63: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 63

ตัวอยางที่ 1.20 แสดงการใชงาน JTextBox /*-------------------------file TextAreaDemo.java--------------------------------*/ import java.awt.*; import javax.swing.*; public class TextAreaDemo extends JPanel { public TextAreaDemo() { //สราง Container แบบ Box Box box = Box.createVerticalBox(); //กําหนดขนดของจอภาพ Dimension dim =new Dimension(100,600); StringBuffer str = new StringBuffer(); str.append("Stretch (a bolw) to the very full,\n"); str.append("And yo will wish you had stopped in time.\n"); str.append("Temper a (sword-edge) o its very sharpest \n"); str.append("And the wdge will not last long. \n"); str.append("When gold and jade fill yor hall, \n"); str.append("You will not be able to keep them safe. \n"); str.append("To be proud with wealth and honor \n"); str.append("is to sow th seeds of one's own downfull. \n"); str.append("Retire when your work is done \n"); str.append("Such is Heaven's way, \n"); //สราง TextArea ดานบน JTextArea textArea1 = new JTextArea(str.toString(),6,25); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setFont(new Font("Serif",Font.PLAIN,18)); //สรางขอความที่จะนําไปแสดงไวที่ textareaที่ 1 (ดานลาง) str=new StringBuffer(); str.append("To yield is to be preserved whole \n");

Page 64: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 64

str.append("To be bent is to become straight \n"); str.append("To be hollow is to be filled. \n"); str.append("To be tattered is to be renewed. \n"); str.append("To be in want is to possess. \n"); str.append("To have plenty is to be confused.\n"); //สราง TextArea ที่สอง(ดานลาง) JTextArea textArea2 = new JTextArea(str.toString(),6,25); textArea2.setLineWrap(true); textArea2.setWrapStyleWord(true); textArea2.setFont(new Font("Serif",Font.ITALIC,18)); //สราง ScrollPane ไวใน TextArea JScrollPane sp1 = new JScrollPane(textArea1); JScrollPane sp2 = new JScrollPane(textArea2); box.add(sp1); box.add(Box.createVerticalStrut(20)); box.add(new JScrollPane(textArea2)); add(box); } public static void main(String[] args) { TextAreaDemo app = new TextAreaDemo(); JFrame f=new JFrame("Text Area Demo"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.getContentPane().add(app); f.pack(); f.show(); } }

Page 65: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 65

1.12 JScrollBar JScrollBar ใชสําหรับสรางแถบแนวตั้งและแนวนอน เพื่อใหผูใชเล่ือนขึ้นลงซายหรือขวา เพื่อเปล่ียนคาหรือขอดูคาตัวเลือกอื่นๆที่เหลือ ดังรูป

e

Absolu

Page

การเลื่อนสกรอบารทําได 3 วิธีไดแก

1. Line โดยใชปุมลูกศรที่อยูขวามือหรปจจุบันจะถูกบวกหรือลบดวยคาที่กํา1 ตําแหนง

Lin

te

ือดานลาง เมื่อใชเมาสคลิกบนลูกศร คาตําแหนงหนดเพื่อเปลี่ยนบรรทัด การเลื่อนนั้นจะเลื่อนครั้งละ

Page 66: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 66

2. Page โดยคลิกเมาสที่ชองวางระหวางตัวเล่ือนและหวัลูกศร จะเปนการเพิ่มหรือลดครั้งละมากๆ ปกติจะเลื่อนครั้งละ 10 ตําแหนง

3. Absolute โดยลากตัวเล่ือนไปในทิศทางใดทิศทางหนึ่ง ตัวเล่ือนคือปุมสี่เหล่ียมเล็กๆ ที่อยูภายในแถบสกรอบาร อาจเรียกไดอีกชื่อหนึ่งวา “Slider Button”

การสรางสกรอบารนี้จะสรางจาก class JScrollBar ดังตวัอยางตอไปนี ้ ตัวอยางที่ 1.21 แสดงการใชงาน JScrollbar /*-----------------------file ScrollBarDemo.java-------------------------*/ import java.awt.* ; import javax.swing.* ; public class ScrollBarDemo extends JFrame { private JLabel redLabel,greenLabel,blueLabel; private JScrollBar red,green,blue; private JPanel colorPanel; public ScrollBarDemo() { setTitle("Color Select"); setSize(300,200); Container c = getContentPane(); JPanel p = new JPanel(); p.setLayout(new GridLayout(3,2)); //create Label and ScrollBar p.add(redLabel = new JLabel("Red 0")); p.add(red=new JScrollBar(Adjustable.HORIZONTAL,0,0,0,255)); red.setBlockIncrement(16); p.add(greenLabel = new JLabel("Green 0")); p.add(green=new JScrollBar(Adjustable.HORIZONTAL,0,0,0,255)); green.setBlockIncrement(16);

Page 67: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 67

p.add(blueLabel = new JLabel("Blue 0")); p.add(blue=new JScrollBar(Adjustable.HORIZONTAL,0,0,0,255)); blue.setBlockIncrement(16); c.add(p,"South"); colorPanel = new JPanel(); colorPanel.setBackground(new Color(0,0,0)); c.add(colorPanel,"Center"); } public static void main(String[] args) { JFrame f= new ScrollBarDemo(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.show(); } }

1.13 JSlider Slider เปนแถบที่ใชเล่ือนไปบนแถบซึ่งอาจเปนแกนแนวนอนหรือแนวตั้งก็ได โดยบนแกนนี้มักจะกําหนดไวเปนตัวเลข และมีเครื่องหมาย thumb สําหรับใชเล่ือนไปบน Slider การเลื่อน thumb นี้จะทําใหคาบนแกนเปลี่ยนแปลงไป

นอกจากการเลื่อน Thumb แลว เรายังสามารถเปลี่ยนแปลงคาบนแกนไดโดยการคลิกลงไปบน Slider ไดเลยโดย Thumb จะเลื่อนตามไปเอง

Page 68: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 68

บนแกนจะมีตวัเลขแสดงไวพรอมกับเสนแบง (tick marks) ในแตละหนวยของตัวเลขดวยโดยเสนแบงนีจ้ะมีทั้งเสนทีแ่บงเปนหนวยใหญ(major tick marks) และเสนแบงหนวยยอย(minor tick marks) เราสามารถกําหนดใหแสดงหรือไมแสดงเสนเหลานี้ พรอมทั้งปรับเปลี่ยนหนวยของตัวเลขไดดวย

ถาไมใชเมาสก็สามารถใชปุมลูกศรขึ้นลง หรือ PgUp , PgDn เพื่อเล่ือน thumb ไดหรือใชปุม Home เพื่อไปที่ตําแหนงเลขต่ําสุด หรือปุม End เพื่อไปที่ตําแหนงเลขสูงสุดก็ได การสราง Slider สามารถสรางไดจาก class JSlider ซ่ึงมี Constructors และ Methods ใหใชดังนี้

Constructors / Methods ความหมาย

JSlider() No-agument constructor. It creates a horizontal slider with an initial value of 50

JSlider(BounderRangeModel brm) Creates a horizontal slider using the specified model

JSlider(int orientation) Creates a slider with the specified orientation and an initial value of 50 by default

JSlider(int min, int max) Creates a horizontal slider with the specified minimum and maximum values, and with an initial value of 50 by default

JSlider(int min , int max , int value) Creates a horizontal slider with the specified minimum, maximm, and initialvalues.

JSlider(int orientation,int min,int max,int value)

Creates a slider with the secified orientation, minimum,maximum, and initial value

Hashtable createStandardLabels(int increment)

Creates a hashtable that stores the labels for the slider’s has marks. The hash marks appear at each interval specified by the increment argument, from the minimum to maximum vaues.

Hashtable createStandardLabels(int increment,int start)

Creates a hashtable that stores the labels for the slider’s has marks, which appear at each interal specified by the increment argument, starting at the secified starting value.

Page 69: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 69

protected void fireStateChanged() Notifies listeners of the occurrence of aChangeEvent on this slider

AccessibleContext getAccessibleContext() Gets the AccessibleContext associates wih this JComponent

int getExtent() Returns the values of the slider’s Extent, which is the range of values spanned by the slider’s knob

boolean getInverted() Returns true if the slider’s scale is marked I inverse, that is, descending from left-to-right or top-to-bottom.

Dictionary getLabelTable() Returns the dictionary object tat stores an associatve set of labels and values.

int getMajorTickSpacing() Rturns the valueof theinterval at which major ticks are spaced.

int getMaximum() Returns the maximum value supported by the slider.

int getMinimum() Returns the minimum value supported by the slider.

int getMinorTickSpacig() Returns the value of the interval at which minor ticks are spaced.

BoundedRangeModel getModel() Returns the data model that defines the slider’s minimum, maximum, and current value prperty

int getOrientation() Returns this slider’s orientation, either JSlider.VERTICAL or JSlider.HORIZONTAL

boolean getPaintLabeles() Indcates if labels are painted. boolean getPaintTicks() Indicates if tick marks are painted. boolean getPaintTrack() Indicates if the track, the area in which the slider

slides, should be painted. boolean getSnapToTicks() Indicates if the knob position and the slider’s

data value are always set to th value of the tick mark that is closest to the point where the user

Page 70: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 70

positioned the knob. SliderUI getUI() Gets the UI object that implements the L&F

forthis component. String getUIClassID() Returns the name of the L&F class that renders

this component. int getValue() Returns the slider’s value. boolean getValueISAdjusting() Indicates if theb slider’s knob is currently begin

dragged. protected String paramString() Returns the string representation of this JSlider void removeChangeListener(ChangeListener l) Remove a listener previously registerd for

change event notification void setExtent(int extent) Sets the slide’s extent, which is the size of the

range spanned by the slider’s knob. void setIverted(boolean b) Sets the policy for marking the tick slider’s

marks. A value of true indicates that the marks should be drawn descending from left-to-right for from top-to-bottom.

void setLabelTable(Dictionary labels) Sets the dictionary that stores the association between slider values and their labels.

void setMajorTickSpacing(int n) Sets the major tick spacing interval void setMaximum(int maximum) Sets the maximize value of the model void setMinimum(int minimum) Sets the minimize value of the model void setMinorTickSpacing(int n) Set s the minor tick spacing interval void setMode(BoundedRangeModel newModel)

Sets the slider’s model to the specified object

void setOrientation(int orientation) Sets the scrollbar’s orientation. Valid values are JSlider.VERTICAL or JSlider.HORIZONTAL

void setPaintLabels(boolean b) Sets the policy for a painting labels on the slider. void setPaintTicks(boolean b) Sets the policy for painting tick marks on the

slider void setPaintTrack(boolean b) Sets the plicy for painting the track on the slider

Page 71: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 71

void setSnapToTicks(boolean b) Sets the policy for positioning the knob. If true, the knob is always positioned at the tick mark cleses to the location where it was last placed by the user.

void setUI(SliderUI ui) Sets the UI oject that implements the Look and Feel for this component

void setValue(int n) Sets the slider’s curret value. void setValueIsAdjusting(boolean b) Sets the state to indicate if the model’s value is

currenly adjusting. protected void updateLabelUIs() Update the label UIs with the latest versions

from the UIFactory. This is called internallywhen the UIFactory notifiesthe slider that the Look & Feel has changed.

void updateUI() Notifies the UIFactory that the Lok & Feel has changed.

ตัวอยางที่ 1.22 แสดงการสราง Slider ทั้งแนวตั้งและแนวนอน /*--------------------file SliderDemo.java--------------------------*/ import java.awt.* ; import javax.swing.* ; public class SliderDemo extends JPanel { public SliderDemo() { JLabel msg = new JLabel("Set your ideal temperature(Celsius)"); //create horizontal slider JSlider horSlider = new JSlider(); horSlider.setMinimum(-20); //defined minimume values horSlider.setMaximum(50); //defined maximum values horSlider.setValue(27); //defined initial values horSlider.setPaintTicks(true); //กําหนดใหมีเสนขีดใหญและเสนขีดยอย

Page 72: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 72

horSlider.setPaintLabels(true); //กําหนดใหแสดงตัวเลขดวย horSlider.setMajorTickSpacing(10); //ระยะหางระหวางเสนขีดใหญ horSlider.setMinorTickSpacing(1); //ระยะหางระหวางเสนขีดเล็ก //กําหนดขนาดจอภาพ Slider กวาง 350,60 px horSlider.setPreferredSize(new Dimension(350,60)); //create vertical slider JSlider verSlider = new JSlider(JSlider.VERTICAL,-30,120,72); verSlider.setPaintTicks(true); verSlider.setPaintLabels(true); verSlider.setMajorTickSpacing(10); verSlider.setMinorTickSpacing(5); verSlider.setPreferredSize(new Dimension(60,300)); Box box = Box.createVerticalBox(); //สราง box แบบดานบนและดานลาง box.add(horSlider); box.add(verSlider); add(box); } public static void main(String[] args) { JFrame f = new JFrame("Slider Demo"); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); SliderDemo app = new SliderDemo(); f.getContentPane().add(app); f.pack(); f.show(); } }

Page 73: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 73

1.14 JMenu , JMenuBar ,JMenuItem ใชในการสรางเมนูหลักและเมนูยอย เพื่อใหผูใชเลือกคําสั่งตางๆจากเมนู ซ่ึงสามารถสรางขึ้นไดจาก class JMenuBar ,JMenu และ JMenuItem โดย class ดังกลาวมี Constructors และ Methods ที่สําคัญดังนี้ Constructors และ Methods ที่สําคัญของ JMenu

Constructors/Methods คําอธิบาย JMenu() No-arguments constructor. I creates a new

JMenu with no text Label. JMenu(String s) Creates a new JMenu with thespecified string

as its text lael. JMenu(String s, boolean b) Creates a new JMenu with the specified string

as its text label. The boolean argument specified whether or not the menu is tear-off menu. A tear-off menu can exist in its own window even after the pop-up window of its parent menu is closed.

Page 74: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 74

Component add(Component c) Appends the specified component to the end of the menu.

JMenuItem and(JMenuItem menuItem) Appends the specified menu item to the end of the menu.

JMenuItem add(String s) Creates a new item with the specified text. The menu item is appended to the end of the menu.

void addMenuListener() Adds the specified listener for menu events on this menu.

void addSeparator() Appends a new separator to the end of the menu. Separator are rendered as raised horizontal line.

void doClick(int pressTime) Programmatically perform a selection of the menu that simulates the user clicking on the menu.

Component getComponent() Returns the component that paints this menu. int getDelay() Returns the value of the time delay that

transpires before the menu’s pop-up is popped up or down.

JMenuItem(getItem(int pos) Returns the JMenuItem located at the specified position.

int getItemCount() Returns the number of items on the menu, including separator.

Component getMenuComponent(int n) Returns the component at the specified position int getMenuComponentCount() Returns the number of componentin the menu Components[] getMenuComponents() Returns an array of the menu’s subcomponents. JPopupMenu getPopupMenu() Returns this menu’s pop-up menu. MenuElement[] getSubElements() Returns an array of the submenu components

for this menu. String getUIClassID() Returns the name of Look and Feel class tha

renders this component.

Page 75: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 75

MenuItem insert(Action a, int pos) Insert a new menu item at the specified position in the menu. The specified Actionobject is registered as an actonlistener on the new menu item.

JMenuItem insert(JMenuItem mi, int pos) Inserts the specifed JMenuItem at the specifed position.

void insert(String s, int pos) Constructs a new menu item with the specified text and insert it at the specified position.

void insertSeparator(int index) Inserts a separator at the specified position. boolean isMenuComponent(Component c) Return true if the specified component is a

submenu of this menu. boolean isPopupMenuVisible() Indicates if the menu’s pop-up window is

visible. boolean isSelected() Indicates if the menu is currently selected

(poped up) boolean isTearOff() Inicates if the menu is a tear-off menu-that is, if

it can be torn from its cotaining menu or menu bar.

boolean isisTopLevelMenu() Idicates if the menu is a top-level menu, that is, if it is the direct child of a menu bar.

void MenuSelectionChanged(boolean isIncluded)

Changes the selection state of this menu.

void remove(Component c) Removes the specified component from this menu.

void remove(int pos) Removes the menu item located at the specified indexfrom this menu.

void remove(JMenuItem item) Removes the specified menu item from this menu

void removeAl() Removes all this menu’s items. void setAccelerator(KeyStroke keystroke) Does nothing for the JMenu class. void setDelay(int d) Sets the delay time that transpires before the

Page 76: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 76

munu’s pop-up menu is poped up or down. void setMenuLocation(int x, int y) Sets the location of the pop-up menu

component void setModel(ButtonModel newModel) Sets the data model for the menu item void setPopupMenuVisible(boolean b) Sets the visibility of the menu’s pop-up

portion. void setSelected(boolean b) Sets the selection status of the menu. Construcstors และ Methods ของ class JMenuBar

Connstructors / Methods คําอธิบาย JMenuBar() No-argument constructor.It creates a new menu bar JMenu add(JMenu c) Appends the specified menu to the end of the

menubar. AccessibleContext getAccessibleContext() Gets the acessibleContext associated with this menu

bar. Component getComponent() Returns the component that is used to paint the

menu bar. The component determines if event occurs inside the menu bar.

Component getComponentAtIndex(int i) Returns the componentat the specified index int getComponentIndex(Component c) Returns the index of the specified component. JMenu getHekpMenu() Gets the help menu for the menu bar. The help

menu is the far right menu. Insets getMargin() Returns the insets object that defined the margin

between the menu bar’s border and its menu. JMenu getMenu(int index) Reurns the menu located at the specified position in

the menu bar int getMenuCount() Returns the number of menu elements in the menu

bar. SingleSelectionMode getSelectionModel() Returns the model object used by the menu bar. MenuElement[] getSubElements() Returns array of all the menus contained in this

menu bar

Page 77: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 77

boolean isBorderPainted() Indicates if the menu bar’s policy is t paint its border.

boolean isManagingFocus() Indicates if the menubar manages focus events internally.

boolean isSelected() Indicates if one of the menu bar’s menu elements is currently selectd.

void menuSelectionChange(boolean isIncluded)

Currentsly does nothing, but must be implemented to fulfill the requirement to implement the MenuElement interface.

void setBorderPainted(boolean s) Sets the menu bar’s policy for painting its border. void setHelpMenu(JMenu menu) Sets the help menu for this menu bar, which appears

when the user selects the Help menu. The help menu is always placedto the far right of the menu.

void setMargin(Insets margin) Sets the insets object that defines the margin between the menu bar’s border and its menus.

void setSelected(Compont sel) Sets the currenty selected component; results in a change tothe state of themenu bar’s selection model.

void setSelectionModel (SingleSelecionModel model)

Set the model object used by the menu bar.

void setUI(MenuBarUI ui) Sets the L&F object that renders this component. Construcstors และ Methods ของ class JMenuItem

Constructors / Methods คําอธิบาย JMenuItem() No-argument constructor. It creates a menu

itemwith no defined text or icon. JMenuItem(Icon icon) Creates a menu item that displays the specified

icon. JMenuItem(String text) Creates a menu item that displays the specified

text. JMenuItem(String text , Icon icon) Creates a menu item that displays both the

Page 78: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 78

specified text and icon. JMenuItem(Stringtext, int mnemonic) Creates a menu item that displays the specified

text and keyboard mnemonic, represented by an underline beneath the mnemonic character in the menu item’ s text.

Ketstroke getAccelerator() Returns the DeyStroke object that is the accelerator for the menu itex.

AccessibleCntext getAccessileContext() Gets the AccessibleContext associated with this menu item.

Component getComponent() Returns the component used to paint the menu item.

MenuElement[] getSubElements() Returns the an array of the submenu components of this menu item. This menu item must be a menu to contain submenus.

String getUIClassID() Retums the name of the L&F class that reners this component.

Protected void init (String text, Icon icon) Initializes the string and icon displayed for the menu item with the specified quantities.

boolean isArmed() Indicates whether the menu item is Armed. An armed button is one that has been pressed but not released.

Void menuSeectionChanged (boolean isIncluded)

Sets the menu item’s state when it is selected or deselected. It is called by the MenuSelectionManager, not applications.

void setAccelerator(KeyStroke keystroke) Set the KeyStroke object that represents the key combination which selects the menu item. This is equivalent to the user selecting the menu item.

void setArmed(boolean b) Sets the state of the menu item to Armed or Not Armed.

void setEnabled(boolean b) Sets the enabled or disabled state of the menu item.

Page 79: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 79

ตัวอยางที่ 1.23 แสดงการสรางเมนู /*----------------------file Menus.java------------------------*/ import java.awt.* ; import javax.swing.* ; public class Menus extends JFrame { public Menus() { super("Menus Demo"); Container c = getContentPane(); Font f14 = new Font("SansSerif",Font.PLAIN,14); Dimension dim = new Dimension(0,10); //สราง Menu1 JMenu menu1 = new JMenu("Menu 1"); //สรางเมนูยอยของ Menu1 JMenuItem mi1 = new JMenuItem("Menu Item 1"); mi1.setMnemonic('1'); JMenuItem mi2 = new JMenuItem("Menu Item 2"); mi2.setMnemonic('2'); JMenuItem mi3 = new JMenuItem("Menu Item 3"); mi3.setMnemonic('3'); //สรางเมนูหลักชื่อ Nested Menu JMenu menu1_1 = new JMenu("Nested Menu"); //สรางเมนูยอยของ Nested Menu JMenuItem mi1_1 = new JMenuItem("15 Love"); mi1_1.setHorizontalAlignment(SwingConstants.LEFT); JMenuItem mi1_2 = new JMenuItem("30 Love"); JMenuItem mi1_3 = new JMenuItem("40 Love"); JMenuItem mi1_4 = new JMenuItem("Game");

Page 80: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 80

//ใสเมนูยอยลงใน Nested Menu menu1_1.add(mi1_1); menu1_1.add(mi1_2); menu1_1.add(mi1_3); menu1_1.add(mi1_4); //ใสเมนูยอยทัง้สี่ลงในเมนูใหญคือ Menu 1 menu1.add(mi1); menu1.add(mi2); menu1.add(mi3); menu1.addSeparator(); //ใสเสนคั่น menu1.add(menu1_1); //สรางเมนูหลักของ Menu 2 และ Menu 3 โดยจะถูกนาํไปวางตอจากเมนูเดิมที่มีอยูแลว JMenu menu2 = new JMenu("Menu 2"); JMenu menu3 = new JMenu("Menu 3"); //สรางเมนูยอยของ menu 2 JCheckBoxMenuItem cbmi1 = new JCheckBoxMenuItem("Check box 1"); JCheckBoxMenuItem cbmi2 = new JCheckBoxMenuItem("Check box 2"); JCheckBoxMenuItem cbmi3 = new JCheckBoxMenuItem("Check box 3"); //ใสเมนูยอยลงใน Menu 2 menu2.add(cbmi1); menu2.add(cbmi2); menu2.add(cbmi3); menu2.addSeparator(); //สรางเมนูยอยโดยกําหนดเปน Radio button JRadioButtonMenuItem rbmi1 = new JRadioButtonMenuItem("Radio 1");

Page 81: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 81

JRadioButtonMenuItem rbmi2 = new JRadioButtonMenuItem("Radio 2"); JRadioButtonMenuItem rbmi3 = new JRadioButtonMenuItem("Radio "); //จัดกลุมของ Radio button ButtonGroup bg = new ButtonGroup(); bg.add(rbmi1); bg.add(rbmi2); bg.add(rbmi3); //ใส radio button ลงใน Menu 2 menu2.add(rbmi1); menu2.add(rbmi2); menu2.add(rbmi3); //สราง MenuBar JMenuBar menubar = new JMenuBar(); //ใส Menu1 ,Menu 2, Menu 3 ลงใน menubar menubar.add(menu1); menubar.add(menu2); menubar.add(menu3); setJMenuBar(menubar); } public static void main(String[] args) { Menus f=new Menus(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,250); f.show(); } }

Page 82: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 82

1.15 Popup Menu Popup Menu คือ Menu ที่จะปรากฏขึ้นเมื่อคลิกเมาสปุมขวา โดยสามารถสรางขึ้จาก Class JPopupmenu ซ่ึงมี Constructors และ Methods ที่สําคัญดังนี ้

Constructors/Methods ความหมาย public JPopupMenu() สราง Popup Menu public JPopupMenu(String label) สราง Popup Menu โดยระบุช่ือผาน label เพื่อ

ใชอางถึงในการทํางาน public JPopupMenu add(JMenuItem menuItem) เพิ่ม Menu Item ใหกับ Popup Menu public void addSeparator() แทรกเสนคั่นระหวาง Menu Item ใน Popup

Menu public Component getComponent() คืนคา Component กลับมา public int getComponentIndex(Comonent c) คืนคาตําแหนง Component ที่ระบุ pulic void setBorderPainted(boolean b) กําหนดการแสดง Border ใหกับ Popup Menu

โดยหากสงคาเปน True (Default) หมายถึงใหแสดง Border และหาสงคาเปน false จะไมแสดง Border

public void setPopupsize(Dimension d) กําหนดขาดใหกับ Popup Menu ตาม Dimension ที่กําหนด หากไมไดเรียกใช Method นี้ Popup Menu จะถูกคํานวณขนาดใหพอดีกับ Component ที่ add ลงไป

public void show(Component invoker,int x,int y) ส่ังใหแสดง Popup Menuที่ตําแหนง x,y โดย invoker คือ Component ที่นํามาแสดง

Page 83: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 83

เมื่อสราง Popup Menu เสร็จแลว หากเราตองการใหแสดง Popup Menu ณ.ตําแหนงที่คลิกเมาสขวา เราะตองทําการตรวจสอบ Event ของเมาสดวยวามีการคลิกเมาสที่ตรงจุดใด หลังจากนั้นจึงเรียกใช Method show() เพื่อแสดง Popup Menu ณ.ตําแหนง ตัวอยางที่ 1.24 แสดงการสราง Popup Menu /*---------------------------file PopupMenuTest.java----------------------------*/ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PopupMenuTest extends JPanel { JPopupMenu pm; JMenuItem item1,item2,item3,item4,item5; //Constructor public PopupMenuTest() { setLayout(new FlowLayout()); item1=new JMenuItem("Copy"); item2=new JMenuItem("Cut"); item3=new JMenuItem("Move"); item4=new JMenuItem("Export"); item5=new JMenuItem("Import"); pm=new JPopupMenu(); pm.add(item1); pm.add(item2); pm.add(item3); pm.addSeparator(); pm.add(item4); pm.add(item5); item3.setEnabled(false); add(pm);

Page 84: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 84

addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(e.isPopupTrigger()) //ถาเปน Mouse Event ของ Popup menu trigger pm.show(e.getComponent(),e.getX(),e.getY()); } }); } public static void main(String[] args) { JFrame f=new JFrame("Popup Menu Test"); PopupMenuTest app = new PopupMenuTest(); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); c.add(app,BorderLayout.CENTER); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(250,200); f.show(); } } ผลลัพธ

1.16 JProgresBar JProgressBar ใชในการแสดงผลการปฏิบัติงานของโปรแกรม โดยจะแสดงเปนจอภาพแบบ Dialog box พรอมแถบสวาง (Progress Bar) เพือ่แสดงจํานวนเปอรเซ็นตทีโ่ปรแกรมทํางานไปแลว โดยแถบสวางจะขยับเพิ่มไปเรื่อยๆจนกระทั่งครบ 100 % ซ่ึงหมายถึงโปรแกรมทํางานเสร็จสมบูรณแลว

Page 85: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 85

การสราง Progress Bar จะใชคลาส JProgressBar ซ่ึงสามารถแสดงไดทั้งแนวตัง้และแนวนอน โดยมี Constructor และ Methods ที่ใชงานบอยๆดังนี้

Constuctors /Methods ความหมาย JProgressBar() No-argument constructor that creates a

horizontally oriented progress bar JProgressBar(BoundedRangeModel newModel) Creates a horizontal progress bar that uses

specified model. JProgressBar(int orient) Creates a progress bar with the specified

orientation, either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL

JProgressBar(int min, int max) Creates a horizontal progress bar with the specified minimum and maximum values

JProgressBar(int orient, int min, int max) Creates a progress bar using the specified orientation and minimum and maximum values

AccessibleContext getAccessibleContext() Get the AccessibleContext associated with this progress bar

int getMaximum() Returns the maximum value of the progress bar’s model

int getMinimum() Returns the minimum value of the progress bar’s model

BoundedRangeModel getModel() Returns the data model used by the progress bar

int getOrientation() Returns the progress bar’s orientation, either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL

double getPercentComplete() Returns the value that represents the percent complete for the progress bar

String getString() Returns the current value of the progress string, which displays a string representation of the percent complete

Page 86: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 86

ProgressBarUI getUI() Returns the L&F object that renders this component

String getUIClassID() Returns the name of the L&F class that renders this component

int getValue() Returns the current value of the model boolean inBorderPainted() Indicates if a border is painted around the

progress bar boolean inStringPainted() Indicates if the progress bar will paint a

progress string onto the progress bar protected void paintBorder(Graphics g) Paints the progress bar’s border, if the

BorderPainted property is True protected String paramString() Returns a string representation of the

JProgressBar void setBorderPainted(boolean b) Sets the progress bar’s policy for painting its

border void setMaximum(int n) Sets the model’s maximum value to x void setMinimum(int n) Sets the model’s minimum value to x void setModel(BoundedRangeModel newModel) Sets the data model used by the JProgressBar void setOrientation(int newOrientation) Sets the progress bar’s orientation to the

specified value, which must be either JProgressBar.VERTICAL or JProgressBAr.HORIZONTAL

void setString(String s) Sets the value of the progress string void setStringPainted(boolean b) Sets the progress bar’s policy for painting the

progress string void setUI(ProgressBarUI ui) Sets the L&F object that render this component void setValue() Sets the model’s current value to x void updateUI() Notification from the UIFactory that the L&F

has changed

Page 87: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 87

ตัวอยางที่ 1.24 แสดงการสราง Progress bar /*---------------file JProgressBarDemo.java---------------*/ import java.awt.*; import javax.swing.*; public class JProgressBarDemo extends JFrame { JLabel message; JProgressBar pb; public JProgressBarDemo() { super("Progress Bar Demo"); Box box= Box.createVerticalBox(); Dimension dim = new Dimension(0,10); Container c = getContentPane(); message = new JLabel("This lebel is not part of the progress bar"); pb = new JProgressBar(0,100); pb.setMaximum(100); pb.setValue(0); pb.setStringPainted(true); box.add(message); box.add(Box.createRigidArea(dim)); box.add(pb); c.add(Box.createVerticalStrut(30),BorderLayout.NORTH); c.add(Box.createHorizontalStrut(30),BorderLayout.WEST); c.add(box,BorderLayout.CENTER); c.add(Box.createHorizontalStrut(30),BorderLayout.SOUTH); c.add(Box.createHorizontalStrut(30),BorderLayout.EAST); } private void updatebar() { for(int i=0;i<=100;i++) { pb.setValue(i); //แสดงตวัเลขเปนเปอรเซ็นตในแถบ Progress Bar

Page 88: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 88

try { Thread.sleep(50); } catch(InterruptedException e) { } } } public static void main(String [] args) { JProgressBarDemo f = new JProgressBarDemo(); f.pack(); f.setVisible(true); f.updatebar(); //ส่ังให Progress Br เริมทํางานจาก method updatebar() f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } }

1.17 JSplitPane JSplitPane ใชในการสรางเพื่อแบงจอภาพออกเปน 2 สวน โดยสามารถแบงไดทั้งแนวตั้งและแนวนอน ซ่ึงมี Constructors และ Methods ดังนี้

Constructors / Methods ความหมาย JSplitPane() No-arg constructor. It constructs a new

JSplitPane that arranges its child components adjacent horizontally.

JSplitPane(int newOrientation) Constructs a new JSpliPane with the specified orientation.

JSplitPane(int newOrientation, Boolean newContinuousLayout)

Constructs a new JPlitPane with the specified orientation and redrawing behavior. If true, the

Page 89: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 89

components redraw continuously as the divider is repositioned.

JSplitPane(int orientation, boolean newContinuousLayout, Component newLeftComponent, Component newRightComponent)

Constructs a new JSplitPane with the specified orientation, redrawing behavior and specified components.

JSplitPane(int orientation, Component newLeftComponent, Component newRightComponent)

Constructs a new JPlitPane with the specified orientation and with the specified components. This new constructor does not do continuous redrawing.

AccessibleContext getAccessibleContext() Get the AccessibleContext associated with this JComponent.

Component getBottomComponent() Returns the bottom or right component. int getDividerLocation() Gets the location of the divider from the L&F

implementation. int getDividerSize() Gets the size of the divider. int getLastDividerLocation() Gets the divider’s last location Component getLeftComponent() Returns the top or left component. int getMaximumDividerLocation() Returns a UI specific value for the maximum

location of the divider. int getMinimumDividerLocation() Returns a UI specific minimum location value

of the divider. int getOrientation() Returns the split pane’s orientation. Component getRightComponent() Returns the right or bottom component Component getTopComponent() Returns the top or left component. splitPaneUI getUI() Returns the SplitPaneUI that is providing the

current L&F. String getUIClassID() Returns the name of the L&F class that renders

this component. boolean isContinuousLayout() Indicates the currently set redrawing behavior. boolean isOneTouchExpandable() Indicates if the pane has a UI widget to

Page 90: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 90

collapse or expand the divider. void remove(Component component) Removes the specified child component from

the pane. void remove(int index) Removes the child component at the specified

index. void removeALL() Removes both child components from the pane. void resetToPreferredSizes() Recalculates the layout to accommodate the

preferred size of the children components. void setBottomComponent(Component comp) Places the specified component below or the

the right of the divider. void setContinuousLayout (boolean newContinueousLayout)

Sets the redraw behavior, either to redraw continuously or not as the divider is repositioned.

void setDividerLocation (double propertionalLocation)

Sets the location of the divider to a point that represents a percentage of the JSplitPane’s height or width.

void setDividerLocation(int location) Sets the divier’s location. void setDividerSize(int newSize) Sets the divider’s size. void setLastDividerLocation(int newLastLocation)

Remembers the specified location as the last location of the divider.

void setLeftComponent(Component comp) Sets the component above or to the left of the divider.

void setOneTouchExpandable(boolean newValue)

Sets the policy for the JSplitPane to provide a UI widget on the divider to quickly expand/collapse the divider.

void setOrientation(int orientation) Sets the pane’s orientation, which determines if it is split horizontally or vertically.

void setRightComponent(Component comp) Sets the specified component to the bottom or right of the divider.

void setTopComponent(Component comp) Sets the component above or to the left of the divider.

Page 91: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 91

void setUI(SplitPaneUI ui) Sets the L&F object that renders this component.

void updateUI() Notifies the pane that the L&F has changed. Notification originates form the UIManager object.

ตัวอยางที่ 1.26 แสดงการสราง Split Pane /*--------------------------fileJSplitPaneDemo.java-----------------------*/ import java.awt.*; import javax.swing.* ; import javax.swing.border.*; public class JSplitPaneDemo extends JPanel { public JSplitPaneDemo() { //สราง splitpane แนวนอน JSplitPane splitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); //split pane สามารถมีได 2 containers ดังนั้นจึงสราง panel ไวในจอภาพดานซายและตีเสน // ลอมรอบ (border) เพื่อใหเห็นขอบเขตไดอยางชัดเจน JPanel left1= new JPanel(); left1.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); //สรางเสนกรอบลอมรอบ left1.add(new JScrollPane(createList1())); splitPane1.setLeftComponent(left1); //สรางอีก Panel หนึงไวทางจอภพดานขวา JPanel right1 = new JPanel(); right1.add(new JScrollPane(createList2())); right1.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); //สรางเสนกรอบลอมรอบ splitPane1.setRightComponent(right1); add(splitPane1);

Page 92: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 92

} //สราง List ไวในจอภาพดานซาย Component createList1(){ Font f14 = new Font("SansSerif",Font.PLAIN,14); String[] philosophers = {"Aristotle","Confucius","Laotze","Pascal","Plato","Rousseau","Socrates"}; //สราง List และ property ตางๆ JList singleSelectionList = new JList(); singleSelectionList.setVisibleRowCount(4); singleSelectionList.setFont(f14); singleSelectionList.setListData(philosophers); Box singleSelectionBox = Box.createVerticalBox(); //สราง Box ฝงซาย JLabel singleSelectionLabel = new JLabel("My Favorite Philosophers"); singleSelectionBox.add(singleSelectionLabel); singleSelectionBox.add(Box.createRigidArea(new Dimension(0,10))); //แบงพื้นที่ของ Box //ใส scroll pane ลงใน box JScrollPane scrollPane = new JScrollPane(singleSelectionList); //สราง scroll pane โดยกหนดใหเลือกตัวเลือกไดเพยีงตวัเลือกเดยีว scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); //กําหนดใหแสดง Scroll bar ในแนวตั้งตลอดเวลา singleSelectionBox.add(scrollPane); return singleSelectionBox; }

Page 93: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 93

//สราง List ไวในจอภาพดานขวา Component createList2(){ Font f14 = new Font("SansSerif",Font.PLAIN,14); String[] painter = {"Michelangelo","Rembrandt","Renoir","da Vinci","van Gogh","Monet","Manet","Picasso"}; //สราง List และ property ตางๆ JList singleIntervalList = new JList(); singleIntervalList.setVisibleRowCount(4); singleIntervalList.setFont(f14); singleIntervalList.setListData(painter); Box singleIntervalBox = Box.createVerticalBox(); //สราง Box ฝงขว JLabel singleIntervalLabel = new JLabel("My Favorite Artists"); singleIntervalBox.add(singleIntervalLabel); singleIntervalBox.add(Box.createRigidArea(new Dimension(0,10))); //แบงพื้นที่ของ Box //ใส scroll pane ลงใน box JScrollPane scrollPane = new JScrollPane(singleIntervalList); singleIntervalBox.add(scrollPane); return singleIntervalBox; } public static void main(String[] args) { JFrame f = new JFrame("JSplit Pane Demo"); JSplitPaneDemo app = new JSplitPaneDemo(); f.getContentPane().add(app); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); }

Page 94: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 94

}

1.17 JTabbedPane JTabbedPane ใชในการสราง pane ยอยๆหลายๆ pane โดยแตละ pane จะถูกเก็บไวในแตละ Tab เมื่อคลิกเพื่อเลือก tab ใด กจ็ะแสดงจอภาพของ pane นั้นๆออกมาให โดยม ี Constructors และ Methodsตางๆ ใหใชงานดังนี้

Constructors / Methods ความหมาย JTabbedPane() No-arg constructor. It creates an empty tabbed

pane. JTabbedPane(int tabPlacement) Creates a new, empty tabbed pane. Any new

tabs will be added to the side specified by the argument, which can be TOP, BOTTOM, LEFT, or RIGHT.

Component add (Component component) Adds the specified component to the pane with a new tab whose name is taked from the name of the component.

Component add (Component component, int index)

Adds the specified component at the specified tab index. The tab name is taken from the name of the component.

Void add(Component component, Object constraints)

Adds a component to the tabbed pane.

Void add(Component component, Object constraints, int index)

Adds a component at the specified tab index.

Page 95: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 95

Component add (String title, Component component)

Adds a component whose tab has the name specified.

Void addChangeListener (ChangeListener 1) Adds a listener for change events. Void addTab(String title, Component component)

Adds a component whose tab has he specified title.

Void addTab(String tile, Icon icon, Component component)

Adds a component whose tab has the specified title and icon. Either the string or icon can be null.

Void addTab(string title, Icon icon, Component component, String tip)

Adds a component whose tab ahs the specified string and icon. The specified ToolTip text is set on the tab.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this JComponent.

Color getBackgroundAt(int index) Returns the background color of the tab at the specified index.

Rectangle getBoundsAt(int index) Returns the bounds of the tab at the specified index.

Component getCompontAt(int index) Returns the bounds of the tab at the specified index.

Icon getDisabledIconAt(int index) Returns the disabled icon for the tab at the specified index.

Color getForegroundAt(int index) Returns the foreground color of the tab at the specified index.

Icon getIconAt(int index) Returns the icon of the tab at the specified index.

SingleSelectionModel getModel() Returns this tabbed pane’s model. Component getSelecteComponent() Returns the tabbed pane’s currently selected

component. int getSelectedIndex() Returns the currently selected index. int getTabCount() Returns the number of tabs contained in the

tabbed pane.

Page 96: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 96

int getTabPlacement() Returns the side at which the tabs are placed in this tabbed pane.

int getTabRunCount() Returns the number of rows (for top or bottom placement) or columns (for left or right placement) currently used ot display the pane’s tabs.

String getTitleAt(int index) Returns the title of the tab at the specified index.

String getTollTipText(MouseEvent event) Returns the ToolTip text for the component that is located at the position where the mouse event occurred.

TabbedPaneUI getUI() Returns the UI object that implements the L&F for this component.

String getUIClassID() Returns the name of the UI class that implements the L&F for this component.

int indexOfcomponent (Component component)

Returns the index of the tab that contains the specified component.

int indexOfTab(Icon icon) Returns the index of the first tab with the specified icon.

int indexOfTab(String title) Returns the index of the first tab with the specified title. Returns -1 if no tab has the specified title.

void insertTab (String title, Icon icon, Component component, String tip, int index

Inserts a component at the specified index. The new tab displays the specified text and icon. If not null

Boolean isEnabledAt(int index) Indicates if the tab located at the specified index is currently enables.

void remove(Component component) Removes the specified component’s tab. void removeAll() Removes ass the pane’s tabs. void removeChangeListener (ChangeListener 1)

Removes a listener for change evens form this tabbed pane.

Page 97: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 97

void remove TabAt(int index) Removes the tab at the specified index. void setBackgroundAt (int index, Color foreground)

Sets the background color of the tab at the specified index to the specified color.

void setComponentAt (int index, Component component)

Sets the specified component to be located at the specified index.

void setDisabledIconAt (int index, Icon disabledIcon)

Sets the specified icon to indicate the disabled state for the tab at the specified index.

void setEnabledAt (int index, boolean enabled)

Indicates if the tab at the specified index is enabled or not.

void setForegroundAt (int index, Color foreground)

Sets the foreground olor of the tab at the specified index to the specified color. If the color is null, the tab’s foreground color will be set to the foreground color of the tabbed pane.

void setIconAt (int index, Icon icon) Sets the specified icon to be the icon of the tab at the specified index.

void setModel (SingleSelectionModel model) Sets the pane’s model to the indicated object. void setSelectedComponent (Component c) Sets the specified component to the selected

state. void setSelectedIndex (int index) Sets the tab at the specified index to the

selected state. void setTabPlacement (int tabPlacement) Specifies that the tabs should be placed on the

side specified for this pane-TOP, LEFT, or BOTTOM.

void setTitleAt (int index, String title) Sets the title of the tab at the specified index to the specified string.

void setUI(TabbedPaneUI ui) Set the UI object that implements the L&F for this component.

void updateUI() Notifies the pane that the L&F has changed.

Page 98: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 98

ตัวอยางที่ 1.27 แสดงการสราง Tabbed Pane /*-------------------file JTabbedPaneDemo.java--------------------*/ import java.awt.*; import javax.swing.*; public class JTabbedPaneDemo extends JPanel { public JTabbedPaneDemo() { Box box = Box.createVerticalBox(); Dimension dim = new Dimension(500,50); //สราง panel สําหรับรองรับ tab 1 tab และสราง label ไวใน tab ดวย JPanel panel1 = new JPanel(); JLabel label1 = new JLabel("Looking at panel1"); panel1.add(label1); //สรางอีก 4 panel JPanel panel2 = new JPanel(); JLabel label2 = new JLabel("Looking at panel2"); panel2.add(label2); JPanel panel3 = new JPanel(); JLabel label3 = new JLabel("Looking at panel3"); panel3.add(label3); JPanel panel4 = new JPanel(); JLabel label4 = new JLabel("Looking at panel4"); panel4.add(label4); JPanel panel5 = new JPanel(); JLabel label5 = new JLabel("Looking at panel5"); panel5.add(label5);

Page 99: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 99

//สราง Tabbed pane JTabbedPane tabbedPane1 = new JTabbedPane(); tabbedPane1.setPreferredSize(new Dimension(400,200)); //ใส Panel ทั้ง 5 ลงใน Tabbed pane tabbedPane1.add("Panel 1",panel1); tabbedPane1.add("Panel 2",panel2); tabbedPane1.add("Panel 3",panel3); tabbedPane1.add("Panel 4",panel4); tabbedPane1.add("Panel 5",panel5); box.add(tabbedPane1); add(box); } public static void main(String[] args) { JTabbedPaneDemo app = new JTabbedPaneDemo(); JFrame f = new JFrame("Tabbed Pane Demo");

f.getContentPane().add(app); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } }

Page 100: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 100

1.18 JFileChooser JFileChooser ใชสําหรับสราง Component ที่ใชในการเลือก File หรือ Save File แตอยางไรก็ตาม FileChooser ไมสามารถเรียกไฟลขึ้นมาไดจริงๆเปนแตเพยีงใหสํารวจรายชื่อไฟลใน Directory หรือ Folder ที่ระบุไวเทานั้น สําหรับ Constructors และ Method ของ JFileChoose มีดังนี ้

Constructors / Methods ความหมาย JFileChooser() No-arg constructor. It creates a JFileChooser

that displays the contents of the user’s home directory.

JFileChooser(File currentDirectory) Creates a JFileChooser that displays the contents of the directory specified vby the path argument.

JFileChooser(File currentDirectory, FileSystemView fsv)

Creates a jfileChooser that specifies file system view to use to display the cntents of the specified directory.

JFileChooser(FileSystemView fsv) Creates a JFileChooser that used the specified FileSystemView to assess the underlying file system.

JFileChooser(String currentDirectoryPath) Creates a JFileChooser that displays the contents of the directory represented by the specified string.

JFileChooser(String currentDirectoryPath, Creates a JFileChooser that uses the specified

Page 101: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 101

FileSystemView fsv) file system view to display the contents of the directory represented by the specified string.

boolean accept(File f) Indicates if the specified file should be displayed-True if yes; False otherwise.

void addActionListener(ActionListener l) Adds an ActionListener to the button. void addChoosableFileFilter(FileFilter filter) Adds a filter to the list of filters that appear in

the Files of Type combo box. void approveSelection() Changes the object’s state in response to being

called by the UI when the user hits the Aprove button, also known as the Open or Save button.

void cancelSelection() Changes the object’s state in response to being called by the UI when the user hits the cancel button.

void changeToParentDirectory() Sets the directory viewed by the file chooser to be the parent of the currently viewed directory.

void ensureFilesVisible(File f) Scrolls the display to make the specified file visible.

FileFilter getAcceptAllFileFilter() Returns the file filter that accepts all matches. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this

JFileChooser. JComponent getAccessory() Returns the accessory component int getApproveButtonMnemonic() Returns the mnemonic for the Approve button.

The Approve button is the Open or Save button by which the user approves the operation.

String getApproveButtonText() Returns the text used in the Approve Button in the FileChooserUI.

String getApproveButtonToolTipText() Returns the Approve button’s ToolTip text. FileFilter[] getChoosableFileFilters() Retrieves an array of all the file filters that the

user can select. File getCurrentDirectory() Returns a file object that represents the current

directory.

Page 102: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 102

String getDescription(File f) Returns a string that describes the specified file.

String getDialogTitle() Retrieves the string displayed in the file chooser’s title bar.

int getDialogType() Returns the type of the file chooser dialog. FileFilter getFileFilter() Returns the file filter that is currently selected. int getFileSelectionMode() Returns the mode currently used for file

selection. FileSystemView getFileSystemView() Returns the fileSystem view object currently

used. FileView getFileView() Returns the file view currently used, The file

view provides a platform-independent view of a file.

Icon getIcon(Flie f) Returns the icon for the secified file or file category to which the file belongs. The icon used is governed by the underlying file system.

String getName(File f) Returns the string name of the specified file. File getSelectedFile() Returns the file object that represents the

currently selected file. File[] getSelectedFiles() Returns an array of file objects that represents

all files currently selected. String getTypeDescription(File f) Returns the type of the fie represented by the

specified file argument. FileChooserUI getUI() Gets the UI object that implements the L&F

for ths component String getUIClassID() Returns a string that specifieds the name of the

L&F class that renders this component boolean isDirectorySelectionEnabled() Indicates whether or not directories can be

selected, based on the current file selection mode

boolean isFileHidingEnabled() Indicates the file chooser’s policy for

Page 103: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 103

displaying hidden files, that is, those that are not shown by default

boolean isFileSelectionEnabled() Indicates iffiles can be selected, based on the current file selection mode

boolean isMultiSelectionEnabled() Indicates whether multiple file selection is allowed

boolean isTraversable(File f) Indicates whether te specified directory can be viewed

protected String paramString() Returns a string representation of this JFileChooser

void removeActionListener(ActionListener) Remoes an ActionListener from the button boolean removeChoosableFileFilter (FileFilter f)

Removes the specifiled filter from the set of file display filters.

void rescanCurrentDirectory() Causes the UI to rescan its list of files in the currently viewed directory

void resetChoosableFileFilters() Resets the set of file display filters to its intial state.

void setAccessory(JComponent newAccessory) Set the accessory component void setApproveButtonMnemonic (char mnemonic)

Sets the approve button’s mnemonic key using the specified character.

void setApproveButtonMnemonic (int mnemonic)

Sets the mnemonic for the Approve Button t the key represented by the specified numeric key code.

void setApproveButtonText (String approveButtonText)

Sets the text used in the Approve button in the FileChooserUI

void setApproveButtonText (String toolTipText)

Sets the ToolTip text for the Approve Button

void setCurrentDirectory(File dir) Sets the currentdirectory to that represented by the specified file object

void setDialogTitle(String dialogTitle) Sets the file chooser’s string title, displayed in the title of its window.

Page 104: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 104

void setDialogType(int dialogType) Sets the type of this dialog; alid values are JFileChooser.OPEN_DIALOG, JFileChooser.SAVE_DIALOG,or JFileChooser.CUSTOM_DIALOG.

void setFileFilter(FileFilter filter) Sets the current filter used to filter files displayed in the view.

void setFileHidingEnabled(boolean b) Sets the polcy for hiding files. void setFileSelectionMode(int mode) Sets the ile chooser’s behavior for selecting file

system elements to display; valid values are JFileChooser.FILES_ONLY, JFileChooser.DIRECTORIES_ONLY,or JFileChooser.FILES_AND_DIRECTORIES.

void setFileSystemView(FileSystemView fsv) Sets the file system view used by the file chooser to discern and represent platform-specified file system information in a platform-independent manner.

void setFileView(FileView fileView) Sets the file view used by the file chooser to retrieve UI information

void setMultiSelectionEnabled(boolean b) Sets the selection policy of the file chooser to that represented by the argument. A value of true allows multiple selections; false allows single selections.

void setSelectedFile(File selectedFile) Sets the specified ile to the selected state. void setSelectedFile(File[] selectedFiles) Sets each of the files in the specified array to

the selected state, if the file chooser currently allows multiple selections.

protected void setup(FileSystemView view) Set the configuration of the file chooser to use the specified file system view.

int showDialog(Component parent,String ApproveButtonText)

Displays a custom dialog with the specified text as the Approve button text. The specified parent is this file chooser.

Page 105: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 105

int showOpenDialog(Component parent) Pops up a file chooser with an Open File Approve button. The L&F determines the Approve button text.

int showSaveDialog(Component parent) Pops up a file chooser with a Save File Approve button. The L&F determines the Approve button text.

ตัวอยางที่ 1.28 แสดงการสราง FileChooser /*-----------------file JFileChooserDemo.java---------------------*/ import java.awt.*; import javax.swing.*; import java.io.*; public class JFileChooserDemo extends JPanel { public JFileChooserDemo() { //สราง File Chooer พรอมกบักําหนดชื่อ Directory ที่ตองกรใหแสดง // ใหเห็นเมื่อมกีารเลือกดูไฟล JFileChooser fc = new JFileChooser(new File("/usr/local")); //สรางฟอนตที่ใชแสดงชื่อไฟล fc.setFont(new Font("SansSerif",Font.PLAIN,14)); Box box =Box.createVerticalBox(); box.add(Box.createRigidArea(new Dimension(0,10))); box.add(fc); add(box); } public static void main(String[] args) { JFileChooserDemo app = new JFileChooserDemo(); JFrame f = new JFrame("JFileChooser Demo"); f.getContentPane().add(app); f.pack();

Page 106: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 106

f.setVisible(true); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } }

1.19 JToolTip เปนขอความสัน้ๆที่ใชในการแสดงคําอธิบายใหกับ Component ใดๆ เมื่อเรานําเมาสไปชี้ที ่Component นั้นๆ มี Constructors และ Methods ดังนี ้

Constructors / Methods ความหมาย JToolTip() No-arg constructor that creates aToolTip AccessibleContext getAccessibleContext() Gets the AccessibeContext associated with this

component JComponent getComponent() Returns the component that the ToolTip

represents String getToolTipText() Returns the text that is displayed when the

ToolTip is activated ToolTipUI getUI() Returns the L&F object that renders this

Page 107: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 107

component String getUIClassID() Returns the name of the L&F class that renders

this component protected String paamString() Returns a string representation of this

JToolTip void setComponent(JComponent c) Sets the component that the TolTip will

represent void setToolTipText(string tipText) Sets the text that is displayed when the ToolTip

is activated void updateUI() Indcates that the L&F has changed ตัวอยางที่ 1.29 แสดงการสราง ToolTip /*------------------------file ToolTips.java ------------------------*/ import java.awt.* ; import javax.swing.* ; public class ToolTips extends JPanel { public ToolTips() { JButton button1= new JButton("Do Something"); button1.setToolTipText("Describes what means to 'do something'"); JButton button2 = new JButton("Do Nothing"); button2.setToolTipText("T think his is pretty self-explanatory"); add(button1); add(button2); } public static void main(String[]args) { JFrame f = new JFrame("Tool Tips Demo"); ToolTips app = new ToolTips(); f.getContentPane().add(app); f.pack(); f.setVisible(true);

Page 108: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 108

f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); } }

1.20 JColorChooser ใชสราง Dialog ใหผูใชเลือกสี ประกอบดวย Constructors และ Methods ที่สําคัญดังนี้

Constructors / Methods ความหมาย public JColorChooser() สราง ColorChooser โดยมีคาเริ่มตนเปน

color.white public JColorChooser(Color c) สราง ColorChooser โดยมีคาเริ่มตนตามที่

กําหนด public Color getColor() คืนคาสีที่เลือกจาก Color chooser กลับมา pubic static Color showDialog(Component component,String title,Color initialColor) throws HeadlessException)

สรางและแสดง ColorChooser ในแบบ modal dialog โดยเมือ่เลือกสีเสร็จแลวและมกีารกดปุม OK dialog ก็จคืนคาสีที่เลือกกลับมา แตถาปุม Cancle ก็จะคนืคาสีปจจุบัน โดย Component คือ parent component ที่สราง dialog ขึ้นมา tile คือขอความ title bar ที่ตองการกําหนดและ initialColor คือคาสีเร่ิมนที่ตองการเลือก

ตัวอยางที่ 1.30 แสดงการสราง ColorChooser /*------------------file ColorChooser.java------------------*/ import java.awt.*; import javax.swing.* ; import java.awt.event.*;

Page 109: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 109

public class ColorChooser extends JPanel implements ActionListener { JButton button1; JTextArea text1; Color c = Color.white; public ColorChooser() { setLayout(new FlowLayout()); button1=new JButton("Select Color"); text1=new JTextArea(4,15); text1.setBackground(c); add(button1); add(text1); button1.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==button1) { c=JColorChooser.showDialog(this,"Select Color",c); text1.setBackground(c); } } public static void main(String[] args) { JFrame f = new JFrame("Color Chooser Demo"); ColorChooser app = new ColorChooser(); f.getContentPane().add(app); f.setLayout(new FlowLayout()); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.pack(); f.show(); } }

Page 110: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 110

1.24 JTable Package javax.swing มี class JTable ที่ใชสําหรับสรางตารางเพื่อนําเสนอขอมูล ประกอบดวย Constructor และ Method ที่สําคัญดังนี้

Constructors/Methods คําอธิบาย public JTable() สรางตารางโดย default data model, default

column model และ default selection model

Page 111: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 111

public JTable(int numRows, int numColumn) สรางตารางโดยใช data table model และมจีํานวนแถวและคอลมันเทากับ numRows และ numColumn ที่กําหนด

public JTable(Object[][] rowData, Objet[] columnNames)

สรางตารางโดยกําหนดขอมลูใหแตละแถวผาน rowData และกําหนด columnNames ผาน columnNames

public JTable(TableModel tm) สรางตารางจาก data table model public JTable(Vector rowData, Vector columnNames)

สรางตารางจาก Vector โดย rowData หมายถึงขอมูลที่จะนํามาแสดงใน table ซ่ึงมีลักษณะเปนเวกเตอร 2 มิติ และ columnNames คือ Vector สองมิติที่ใชสําหรับกําหนดชื่อคอลัมน โดยปกติจะเปน String

public void clearSelection() เคลียรคอลัมนและแถวทีเ่ลือกไว public int getAutoResizeMode() คืนคา auto resize mode ของ table คา default เปน

AUTO_RESIZE_SUBSEQUENT_COLUMNS public String getColumnName(int column) คืนคาชื่อคอลัมนที่ระบ ุpublic TableModel getModel() คืนคา data model ของ table เปน TableModel

Object public int getRowCount() คืนคาจํานวนแถว public getColumnCount() คืนคาจํานวนคอลัมน public void setAutoResizeMode(int mode) กําหนดการ auto resize table โดยคา mode ที่

สามารถกําหนดไดคือ AUTO_RESIZE_OFF AUTO_RESIZE_NEXT_COLUMN AUTO_RESIZE_SUBSEQUENCT_COLUMNS AUTO_RESIZE_LAST_COLUMN AUTO_RESIZE_ALL_COLUMNS

public void stGridColor(Color gridColor) กําหนดสีใหกบั grid ผาน gridColor public setModel(TableModel dataModel) กําหนด data table model ใหกับ table public void setPreferredScrollableViewportSize

กําหนกขนาดของ table ที่จะแสดงโดยหากกําหนดขนาดที่ตองการแสดงเล็กกวาพื้นทีข่อง

Page 112: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 112

(Dimension size) tableที่ตองการใชงาน table ก็จะสราง Scroll bar ใหอัตโนมต ิ

public void setSelectionMode (int selectionMode)

กําหนด Mode การเลือกขอมูลในแตละแถวและคอลัมน โดยคา Mode ที่เปนไปไดคือ ListSelectionModel.SINGLE_SELECTION ListSelectionModel.SINGLE_INTERVAL_

public void setSelectionModel(ListSelectionModel newModel)

กําหนด mode การเลือกผาน ListSelectionModel Object

public void setShowGrid(boolean showGrid) กําหนดใหแสดง Grid(true) เปน default และไมแสดง(false)

public void setValueAt(Object aValue, int row, int column)

กําหนดคาใหกับ table ผาน aValue ในตําแหนงที ่row และ column ที่กําหนด

ตัวอยางที่ 1.31 แสดงการสรางตาราง /*------------------------file UseTable1.java -----------------------------*/ import java.awt.* ; import javax.swing.*; import java.util.*; public class UseTable1 extends JPanel { Object[][] data = { {"แดง","รักชาติ","วายน้ํา",new Integer(22),new Boolean(false)}, {"เขียว","รักชาติ","วายน้ํา",new Integer(22),new Boolean(false)}, {"เหลือง","รักชาติ","วายน้ํา",new Integer(22),new Boolean(false)}, {"สม","รักชาติ","วายน้ํา",new Integer(22),new Boolean(false)}, {"ดํา","รักชาต"ิ,"วายน้ํา",new Integer(22),new Boolean(false)} }; Object[] columnNames = {"First Name","Last Name","Sport","# of Years","ทานเนื้อสัตว"}; JTable tb;

Page 113: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 113

public UseTable1() { tb = new JTable(data,columnNames); JScrollPane scPane = new JScrollPane(tb); //กําหนดใหแสดงผล table ตามขนาด Dmension หากพืน้ที่ Container

//มีขนาดเล็กกวาขนาดของ Table ที่กําหนดใหแสดงโปรแกรมจะสรา SCroll bar //ใหอัตโนมัติ ลองเปลี่ยนคา Dimension ดูก็จะเห็นผล

tb.setPreferredScrollableViewportSize(new Dimension(450,70)); tb.setFont(new Font("Cordia New",0,20)); add(scPane); } public static void main(String[] args) { JFrame f=new JFrame("Use Table"); Container c=f.getContentPane(); c.setLayout(new FlowLayout()); c.add(new UseTable1(),BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.pack(); f.show(); } }

Page 114: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 114

1.24.1 Table Model หากเราตองการสราง Table จาก Data table model กส็ามารถทําไดโดยการสราง Table จาก constructor ที่มีการรับ parameter ที่มี Reference กับ Interface “TableModel” ไปใหกับ Table ดังกลาว ซ่ึง interface “Table Model” นี้จัดเก็บอยูใน Package “javax.swing.table” ใชสําหรับให class นําไป implement เพื่อสรางเปน data table mdel แตใน Package ดังกาวไดเตรียม Class ที่ได implement interface นี้ไวเรียบรอยแลว เราสามารถนํา class นี้ไปใชงานไดทันท ีโดย class นี้มีช่ือวา “DefaultTableModel” ทํางานรวมกับ Table เราก็สามารถจัดการขอมูลตางๆ เชน การกําหนดคาใหกับ cell ใน Table เปนตน ผานทาง DefaultTableModel ไดโดยตรง ตารางดานลางนีเ้ปน Method ที่สําคัญของ TabelModel

Method ความหมาย public DefaultTableModel() สรางDefaultTableModel ที่มีขนาด Row และ

Column เทากับ 0 public DefaultTableModel(int rowCount,int columnCount)

สราง DefaultTableMode โดยระบุขนาด Row และ Clumn เทากับ RowCount และ ColumnCount ที่กําหนดตามลําดับ

public DefaultTableModel(Object[][],Object[] columnNames)

สราง DefaultTableModel จาก array 2 มิติชนิด Object และระบุช่ือ column จาก array หนึ่งมิติชนิด Object

Public DefaultTableModel(Object[],columnNames,int rowCount)

สราง DefaultTableModel โดยระบุจํานวนและช่ือคอลัมนจาก array หนึ่งมิติชนิด Object และระบุจํานวนแถวที่ตองการสรางผาน rowCount

public DefaultTableModel(Vector columnNames,int rowCount)

สรางDefaultTableModel โดยระบุจํานวนและช่ือคอลัมนจาก Vector และระบุจํานวนแถวที่ตองการสรางผาน rowCount

public int getColumnCount() คืนคาจํานวน column ของ DefaultTableModel public int getRowCount() คืนคาจํานวน row ของ DefaultTableModel public Object getValueAt(int row, int column) คืนคา Object ในตําแหนง row และ column public void removeRow(int row) Remove แถวออกจาก data table model ตาม

index ที่กําหนด public void setValueAt(Object aValue,int rw,int column)

กําหนดขอมูลใหกับ data table model ในตําแหนงที่ row และ column ที่กําหนด

Page 115: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 115

ตัวอยางที่ 1.32 แสดงการสราง Table จาก DefaultTableModel /*-------------------------file UseTable2.java -------------------------*/ import java.awt.* ; import javax.swing.* ; import javax.swing.table.*; public class UseTable2 extends JPanel { JTable tb; DefaultTableModel calendarModel; final String[] day = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; //constructor public UseTable2() { calendarModel=new DefaultTableModel(day,5); tb=new JTable(calendarModel); JScrollPane scPane = new JScrollPane(tb); tb.setPreferredScrollableViewportSize(new Dimension(450,90)); tb.setFont(new Font("Cordia New",0,18)); int num=1; for(int j=0;j<calendarModel.getRowCount();j++) { for(int i=0;i<calendarModel.getColumnCount();i++) { if(num>31) break; else calendarModel.setValueAt(new Integer(num++),j,i); } } add(scPane); } public static void main(String[] args) { JFrame f = new JFrame("Use Default Table Model"); Container c= f.getContentPane();

Page 116: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 116

c.setLayout(new FlowLayout()); c.add(new UseTable2(),BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.pack(); f.show(); } }

1.25 Container JWindow Window เปน top-level Container ตัวหนึง่ที่สามารถแสดงใหเห็นบนจอภาพไดเปนตัวแรก โดยไมตองบรรจุไวใน Component ตัวอ่ืน แตส่ิงที่ Window แตกตางจาก Frame ก็คือ Window ไมมี title ,menu bar ,border และเราไมสามารถใชเมาสทําการยายตําแหนงการแสดงไปยังตําแหนงอืน่ไดเหมือนกับ Frame หรือ Dialog การสราง Window สามารถสรางไดจาก Class JWindow ซ่ึงจะมี Default Layout Manager เปน Border Layout Method ของ Class JWindow ท่ีสําคัญ

Method ความหมาย public JWindow() สราง Window วางๆขึ้นมา public JWindow(Frame owner) สราง Window โดยมี Frame เปน Owner public JWindow(Window owner) สราง Window โดยมี Window เปน Owner public Container getContentPane() คืนคา Container เพื่อใชสําหรับวาง

Components ตัวอ่ืนๆลงไป public void remove(Component comp) Remove Component ออกจาก Window public void setContentPane(Container กําหนด Container ใหกับ Window

Page 117: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 117

contentPane) public void setLayout(LayoutManager manager) กําหนด Layout Manager ใหกับ Window ตัวอยางที่ 1.33 แสดงการสราง Window /*-------------------------file CreateWindow.java------------------------*/ import java.awt.* ; import javax.swing.* ; public class CreateWindow { public static void main(String[] arge) { JWindow win = new JWindow() ; win.setSize(300,150) ; Container c = win.getContentPane(); c.setLayout(new FlowLayout()); c.add(new JLabel(“Select Button”)); c.add(new JButton(“OK”)); win.show(); } }

การทํางานของโปรแกรม จากตัวอยางสราง window ขึ้นมากําหนดขนาดเทากับ(300,150) พรอมกําหนด layout เปน Flow Layout หลังจากนั้นเพิ่ม Label และ Button ใหกับ Container แลวจงึคอยส่ังให window แสดงใหเห็นทางจอภาพดวย method show()

Page 118: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 118

จากตัวอยางจะเหน็วา Window ไมมีปุมที่ใชสําหรับผิดหนาตางเหมือนกับ Frame ดังนั้นหากตองการไมให window แสดงอีก อาจเรียกใช method dispose() เพื่อทําลาย Window นั้นเสีย หรือ method hide() เพื่อซอน Windows นั้นๆ ดังตัวอยางที่ 1.34 ตัวอยางที่ 1.34 แสดงการทําลาย Window /*-------------------------file DisposeWindow.java------------------------*/ import java.awt.* ; import javax.swing.* ; public class DisposeWindow { public static void main(String[] arge) { JWindow win = new JWindow() ; win.setSize(300,150) ; Container c = win.getContentPane(); c.setLayout(new FlowLayout()); c.add(new JLabel(“Select Button”)); c.add(new JButton(“OK”)); win.show(); try { Thread.sleep(4000); win.dispose(); //ทําลาย window และสงคืนหนวยความจํา Thread.sleep(400); c.add(new JLabel(“after Dispose”)); //เพิ่ม Component ใหกบั Container อีก win.show() ; } catch(Exception e) { System.out.println(e.getMessage()); } } }

Page 119: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 119

การทํางานของโปรแกรม ตัวอยางนี้มีลักษณะการทํางานคลายกับตวัอยางที่ 1.33 แตไดเพิ่ม method เพื่อทําลาย Window ที่สรางขึ้น โดยภายใน block คําสั่ง try มีการหนวงเวลาให window แสดงไดเพยีง 4 วินาที จากนัน้เรียกใช Method dispose() เพื่อทําลาย Window แลวหนวงเวลาอีก 4 วนิาทีจึงเพิ่ม Component ใหมใหกับ Container แลวส่ังให Window แสดงออกทางจอภาพอีกครั้ง จากผลลัพธจะเห็นวา Window แสดงขึ้นมาพักหนึ่ง(เทากับวินาที่ทีก่ําหนด) แลวหายไป หลังจากนั้นอีก 4 วินาทีก็แสดงผลลัพธขึ้นมาอีกครั้งพรอมกับมี Component ตัวใหมดวย 1.26 Container JDialog โดยปกติ Dialog จะใชสําหรับติดตอกับผูใชเพียงชัว่คราวเทานั้น เชน Dialog ยืนยนัการทํางานอยางใดอยางหนึ่ง การสราง Dialog สามารถสรางไดโดย Class JDialog ซ่ึงขยายมาจาก Class Dialog Dialog เปน top-level windows Component ตัวหนึ่งทีส่ามารถนํา Component ตัวอ่ืนๆใสลงไปไดและสามารถนํามาแสดงบนจอภาพไดเปนตวัแรกเชนเดยีวกับ top-level window Component ตัวอ่ืนๆ Dialog จะมีลักษณะคลายกับ Frame แต Dialog ไมมีปุม Minimize และ Maximize คุณลักษณะอยางหนึ่งของ Dialog คือ modal ซ่ึงหมายความวา ถา Dialog ใดมีคุณสมบัติเปน modal แลว เมื่อแสดง Dialogจะไมสามารถปดหรือทํางานใดๆกบั Frame แมทีเ่ปนผูสราง Dialog ขึ้นมาได จนกวา Dialog ดังกลาวจะถูกปดไปกอน แตถา Dialog ใดไมมีคณุสมบัติเปน modal แลว เมื่อแสดง Dialogจะสามารถปดหรือทํางานใดๆกับ Frame แมที่เปนผูสราง Dialog ขึ้นมาได ไมวา Dialog นั้นจะถูกปดไปแลวหรือยัง

Page 120: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 120

ตารางแสดงคาคงที่และ Method ของ Class JDialog ท่ีสําคัญ คาคงที่/Method ความหมาย

public static final int DISPOSE_ON_CLOSE ทําลายและปด Window โดยอัตโนมัติ(ยังคงอยูในโปรแกรม)

public static final int EXIT_ON_CLOSE ออกจากโปรแกรมและปด Window อัตโนมัติ public static final int DO_NOTHING_ON_CLOSE

ปองกันการกดปุม Close (เมื่อกดแลวไมปด window)

public static final int HIDE_ON_CLOSE ปดแลวซอน Window โดยอัตโนมัติ public JDialog() สราง Dialog แบบไมเปน modal public JDialog(Dialog owner) สราง Dialog แบบไมเปน modalโดยระบวุา

Dialog ใดเปน Dialog แม (owner) ที่สราง Dialog ดังกลาวขึ้นมา

public JDialog(Dialog owner ,boolean modal) สราง Dialog แบบสามารถระบุไดวาเปน modal หรือไม โดยหากตองการใหเปน modal กใ็หสงคา true ใหกบั modal พรอมกับระบุวา Dialog ใดเปน Dialog แมที่สราง Dialog ดังกลาวขึ้นมา

public JDialog(Dialog owner , String title) สราง Dialog แบบไมเปน modal โดยระบุวา Dialog ใดเปน Dialog แม(owner) ที่สราง Dialog ดังกลาวขึ้นมา พรอมกับระบุขอความ Title Bar ใหกบั Dialog ผาน title

public JDialog(Dialog owner , String title ,boolean modal)

สราง Dialog แบบสามารถระบุไดวาเปน modal หรือไม โดยหากตองการใหเปน modal ใหสงคา true ใหกับ modal พรอมกบัระบุวา Dialog ใดเปน Dialog แม(owner) ที่สราง Dialog ดังกลาวขึ้นมา และสามารถกําหนดขอความ Title Bar ใหกับ Dialog ผาน title

public JDialog(Frame owner) สราง Dialog แบบไมเปน modal โดยระบุวา Frame ใดเปน Frame แมที่สราง Dialog ดังกลาวขึ้นมา

public JDialog(Frame owner ,boolean modal) สราง Dialog แบบสามารถระบุไดวาเปน modal

Page 121: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 121

หรือไม โดยหากตองการใหเปน modal กใ็หสงคา true ใหกับ modal พรอมกับระบุวา Frame ใดเปน Frame แมที่สราง Dialog ดังกลาวขึ้นมา

public JDialog(Frame owner , String title) สราง Dialog แบบไมเปน modal โดยระบุวา Frame ใดเปน Frame แม(owner) ที่สราง Dialog ดังกลาวขึ้นมา พรอมกับระบุขอความ Title Bar ใหกับ Dialog ผาน title

public JDialog(Frame owner , String title ,boolean modal)

สราง Dialog แบบสามารถระบุไดวาเปน modal หรือไม โดยหากตองการใหเปน modal ใหสงคา true ใหกับ modal พรอมกบัระบุวา Frame ใดเปน Frame แม(owner) ที่สราง Dialog ดังกลาวขึ้นมา และสามารถกําหนดขอความ Title Bar ใหกับ Dialog ผาน title

public Container getContentPane() คืนคา Content Pane ซ่ึงเปนContainer ของ Dialog เพื่อใชสําหรับวาง Components ตัวอ่ืนๆลงไป

public int getDefaultCloseOperation() คืนคาคงที่ใชสําหรับจัดการกับ Dialog ที่กําหนดผาน Method setDefaultCloseOperation

Public void setContentPane(Container contentPane)

ใชกําหนด Content pane ใหกับ Dialog ซ่ึงมักใชคูกับ Panel

Public void setDefaultCloseOperation(int operation)

กําหนดการทํางานเมื่อกดปุม Close ของ Dialog โดยoperation จะหมายถึงคาคงที่ที่ไดกลาวถึงในตารางขางตน

Public void setJMenuBar(JMenuBar menu) กําหนด Menu Bar ใหกับ Dialog Public void setLayout(LayoutManager mng) กําหนด Layout ใหกับ Content pane ของ

Dialog ตัวอยางที่ 1.35 แสดงการสราง Dialog /*----------------------------file CreateDialog.java-----------------------------*/ import java.awt.* ; import javax.swing.* ; public class CreateDialog extends JFrame {

Page 122: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 122

Container c ; public CreateDialog(String title) { super(title); c = getContentPane(); c.setLayout(new FlowLayout()); c.add(new JLabel(“Frame แมใชทดสอบ Dialog”)); c.add(new JButton(“OK”)); } public static void main(String[] args) { JDialog j ; CreateDialog f= new CreateDialog(“Frame แม”); f.setSize(400,350); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.show(); j = new JDialog(f, “Test Dialog” ,true); j.setDefaultCloseOperation(j.DISPOSE_ON_CLOSE); j.getContentPane().setLayout(new FlowLayout()); j.getContentPane().add(new JLabel(“Dialog”)); j.setSize(200,150); j.show(); } }

Frame แม

Dialog

Page 123: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 123

การทํางานของโปรแกรม จากตัวอยางสราง Frame f ขึ้นมากอนโดยกําหนดใหม ี Layout เปน Flow Layout พรอมกับ add Label และ Button ใหกับ Container ของ Frame หลังจากนั้น สราง Dialog j โดยมี f เปน Frame แม พรอมกับระบุ Title Bar ใหกับ Dialog ดังกลาว พรอมกับกําหนดให Dialog ที่สางขึ้นมามีคุณสมบัติเปน modal โดยกําหนดให j มี Layout เปน FlowLayout พรอมกับ add Label ใหกับContainer ของ Dialog สังเกตวาเราสงคาคงที่ DISPOSE_ON_CLOSE ใหกับ Method setDefaultCloseOperation() ของ Dialog เพราะวาเมือ่เราทําลาย Dialog ดังกลาวแลวเราตองไปทํางานที่ Frame แมซ่ึงเราจะยังไมออกจากโปรแกรมจริงๆ การทํางานของโปรแกรมเราจะเห็นวาเราไมสามารถทํางานกับ Frame แมไดหากยังไมปด Dialog ดังกลาวไปกอน ซ่ึงคุณสมบตัิดังกลาวนี้มักนํามาใชกับระบบงานทั่วๆไป เชน Dialog ใหใสช่ือผ็ใชงานและรหัสผานเพื่อเขาใชงานโปรแกรม เปนตน 1.27 Cursor โดยปกตใินระบบ win32 เมื่อเรานําเมาสเคลื่อนที่ผานเขาไปยังพื้นทีแ่สดงผลของ Component ก็จะปรากฏ Cursor ที่ตําแหนงของเมาสเปนรูปลูกศร และเมื่อเมาสเคลื่อนที่ไปยังตําแหนงที่สามารถพิมพขอความไดก็จะเปลี่ยนเปน text cursor(I) เราสามารถเปลี่ยนรูปแบบ Cursor เมื่อเมาสเคลื่อนที่มายังตําแหนงการแสดงผลของ Component นั้นไดโดยการเรียกใช Method setCursor() ของ Class Cursor ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class Cursor

คาคงที่/Method ความหมาย public static final int CROSSHAIR_CURSOR Cursor แบบ Crosshair public static final int DEFAULT_CURSOR Cursor แบบ Default public static final int TEXT_CURSOR Cursor แบบ Text public static final int WAIT_CURSOR Cursor แบบ Wait public static final int SW_RESIZE_CURSOR Cursor แบบ south-west-resize public static final int SE_RESIZE_CURSOR Cursor แบบ south-east-resize public static final int NW_RESIZE_CURSOR Cursor แบบ north-west-resize public static final int NE_RESIZE_CURSOR Cursor แบบ north-east-resize public static final int N_RESIZE_CURSOR Cursor แบบ north-resize public static final int S_RESIZE_CURSOR Cursor แบบ south-resize

Page 124: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 124

public static final int W_RESIZE_CURSOR Cursor แบบ west-resize public static final int E_RESIZE_CURSOR Cursor แบบ east-resize public static final int HAND_CURSOR Cursor แบบ Hand public static final int MOVE_CURSOR Cursor แบบ Move public Cursor(int type) Constructor ใชสราง Cursor ตามในรปูแบบ

ตางๆโดย type หมายถึงคาคงที่ของ Cursor ตามชนิดที่ตองการสรางตางๆ

public static Cursor getDefaultCursor() คืนคา Default Cursor Object ของ Component นั้นๆ

ตัวอยางที่ 1.36 การกําหนด Cursor ใหกับ Component /*---------------file CreateCursor.java --------------*/ import java.awt.* ; import javax.swing.* ; public class CreateCursor extends JPanel { JButton b1; public CreateCursor() { setLayout(new FlowLayout()); b1=new JButton("OK"); b1.setCursor(new Cursor(Cursor.HAND_CURSOR)); add(new JLabel("Test Cursor")); add(b1); } public static void main(String[] args) { JFrame f=new JFrame(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(200,100); f.setContentPane(new CreateCursor()); f.show(); } }

Page 125: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 125

การทํางานของโปรแกรม จากตัวอยาง Class CreateCursor ขยายมาจาก Class JPanel โดยภายใน Class ดังกลาวมกีารจัด Layout แบบ Flow Layout โดยมี Component 2 ตัวคือ JLabel และ JButton b1 และกําหนดใหเมื่อลากเมาสผาน Button ใหเปลี่ยนรูป Cursor เปนรูปมือ หลังจากนัน้ภายใน Method main() สราง Frame f ขึ้นมาตามปกติ หลังจากนั้นกําหนด Object ของ Class CreateCursor ใหเปนพื้นที่ Content pane ของ f จากผลลัพธจะเห็นวาเมื่อเราลาเมาสผาน Button b1 Cursor จะเปลีย่นเปนรูปมือ และเมื่อลากเมาสออกจาก Button Cursor ก็จะเปลี่ยนมาเปน Default โดยอัตโนมัติ เพราะทุก Component จะมี Cursor เปน Default อยูแลว 1.28 Enable Components โดยปกตใินหนาจอการทํางานหนึ่งอาจประกอบดวยหลายๆ Component ซ่ึงอาจทําใหผูใชสับสนไดวาตองการใหทํางานที่ Component ไหนกอนเชนมีปุมหลายๆปุมบน Frame หนึ่ง ผูใชอาจสับสนไดวาจะกดปุมไหนกอนดี วิธีการแกไขปญหานี้วิธีหนึ่งก็คือ กําหนดให Component ที่สามารถใชงานไดในขณะนั้นมีคาเปน enable สวน Component ตัวอ่ืนทีไ่มตองการใหสามารถใชงานไดในเวลานัน้ใหกําหนดใหเปน disable Class JComponent มี Method ที่ใชกําหนดให Component นั้น Enable หรือไมและตรวจสอบวา Component ดังกลาว Enable อยูหรือไม Method ทั้งสองไดแก

public void setEnabled(boolean enabled) กําหนดให Component Enable ดวยการสงคา true เมื่อตองการให Component Enable และสงคา false เมื่อไมตองการให Component Enable

public boolean isEnabled() ตรวจสอบวา Component Enable อยูหรือไม โดยจะสงคา true เมื่อ Component Enable

Page 126: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 126

ตัวอยางที่ 1.37 แสดงการ Enable Component /*-----------------file EnableComponent.java-----------------------*/ import java.awt.* ; import javax.swing.* ; public class EnableComponent extends JPanel { JButton b1,b2; JTextField text; public EnableComponent() { setLayout(new FlowLayout()); b1 = new JButton("OK"); b2 = new JButton("Cancel"); b2.setEnabled(false); //กําหนดให b2 Disable text= new JTextField(10); add(text); add(b1); add(b2); } public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,100); Container c= f.getContentPane(); c.add(new EnableComponent()); f.show(); } }

Page 127: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 127

การทํางานของโปรแกรม Class EnableComponent ขยายมาจาก Class JPanel โดยมี TextField text และ Button b1,b2 เปน Component แตเรากําหนดให Button b2 disable ไวดวยการสงคา false ใหกับ Method setEnabled() ซ่ึงจะเปนผใหปุมดังกลาวไมสามารถใชงานได 1.27 Bounds ทุกๆ Component จะมี bound บอกขนาดและตําแหนงที่วางอยูใน Container ซ่ึงหากเราตองการทราบ Bound ของ Component ใดๆสามารถทําไดโดยการเรียกใช Method ดังนี ้

public java.awt.Rectangle.getBounds() จะเห็นวา Method ดังกลาวจะคืนคามาเปน Rectangle Object ซ่ึง Class นี้จัดเก็บอยูใน Package java.awt โดยมีตัวแปรและ Method ที่สําคัญดังนี ้ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class Rectangle

คาคงที่/Method ความหมาย public int height เก็บความสูงของ Component public int width เก็บความกวางของ Component public int x เก็บตําแหนง x coordinate public int y เก็บตําแหนง y coordinate public Rectangle() สราง Rectangle มีความกวางและความสูงตามที่

กําหนด สวน x,y มีคาเปน 0 public Rectangle(Diamension d) สราง Rectangle ตาม Dimension ที่กําหนด public Rectangle(int width , int height) สราง Rectangle มีความกวางและความสูงตามที่

กําหนด สวน x,y มีคาเปน 0 public Rectangle(int x, int y ,int width , int height)

สราง Rectangle มีตําแหนง x,y และความกวางและสูงตามที่กาํหนด

public Rectangle getBounds() คืนคา boundของ Component เปน Rectangle Object

public void setBounds(int x, int y, int width,int height)

กําหนดการวาง Component ที่ตําแหนง x,y มีขนาดเปน width,height ใชเมือ่กําหนด Layout เปนแบบ null Layout

public void setBounds(Rectangle r) กําหนดการวาง Component ที่ตําแหนงและขนาดตาม Rectangle r ที่กําหนด ใชเมื่อกาํหนด Layout เปน null Layout

Page 128: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 128

ตัวอยางที่ 1.38 แสดงการใชงาน bounds /*------------------file useBounds.java -----------------*/ import java.awt.* ; import javax.swing.* ; public class useBounds { public static void displayBound(Component comp) { if(comp != null) { Rectangle r = comp.getBounds();

//แสดงชื่อ Class ของ Component System.out.println(comp.getClass().getName());

System.out.println("x coordinate : "+r.x); System.out.println("y coordinate : "+r.y); System.out.println("height : "+r.height); System.out.println("widh : "+r.width); } else return; } public static void main(String[] arg) { JTextField text = new JTextField(10); JButton b1 = new JButton("OK"); JFrame f = new JFrame(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(300,100); Container c= f.getContentPane(); c.setLayout(new FlowLayout()); c.add(text); c.add(b1); f.show(); displayBound(b1); } }

Page 129: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 129

การทํางานของโปรแกรม Class useBounds มี Method displayBound() ใชสําหรับแสดงชื่อ Component ตําแหนง x, y และความสูง กวางของ Component ที่สงเขามา จากตัวอยางมี Frame f ซ่ึงมี layout เปน Flow layout หลังจาก add Text Field “text” และ Button b1 ใหกับ Component แลว หลังจากนั้นก็เรียกใช Method displayBound() พรอมกับสงคา b1 เปน parameter ใหกับ Method ซ่ึงคา Bound ของ Component ที่แสดงออกมาจะเปนดังผลลัพธ 1.28 Point Class Point ใชสําหรับเก็บคา coordinate x และ y ของจุดๆหนึ่ง ซ่ึงมตีัวแปรและ Method ที่สําคัญดังนี ้ตารางแสดงคาคงที่และ Method ท่ีสําคัญของ Class Point

คาคงที่ / Method ความหมาย public int x เก็บคา x Coordinate public int y เก็บคา y Coordinate public Point() สราง Point ที่มีจุด Origin เปน (0,0) public Point(int x, int y) สราง Point ที่มีจุด Origin เร่ิมตนที่ x,y ที่กาํหนด public double getX() คืนคา Coordinate x ของ Point เปน double public double getY() คืนคา Coordinate y ของ Point เปน double หากตองการจดัการอยางใดอยางหนึ่งเกี่ยวกับ Point เราสามารถเรียกใช Method ของ Class Component เหลานี้ขึ้นมาทาํงานได

Method ความหมาย public void setLocation(Point p) เล่ือนตําแหนงการแสดงของ Component ไปยัง

ตําแหนง Point ที่ตองการ public Point getLocation() คืนคาตําแหนงจุดที่ Component วางอยูบน top-

level window Component กลับมาเปน Point Object

Page 130: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 130

public Point getLocationOnScreen() คืนคาตําแหนงจุดที่ Component วางอยูบนจอภาพกลับมาเปน Point Object แตหาก Component ดังกลาวยังไมสามารถมองเห็นไดบนจอภาพก็จะเกดิ illegalComponentStateException

ตัวอยางที่ 1.39 แสดงการใชงาน Point /*--------------------file usePoint.java ----------------------*/ import java.awt.* ; import javax.swing.* ; public class usePoint extends JPanel { static JButton b1; public usePoint() { setLayout(new FlowLayout()); b1=new JButton("OK"); add(new JLabel("Test Point")); add(b1); } public static void disPlayPoint(Component comp) { if(comp != null) { Point pointOnContainer = comp.getLocation(); Point pointOnScreen = comp.getLocationOnScreen(); System.out.println("Point on top-level window component"); System.out.println("\t x coordinate :"+pointOnContainer.getX()); System.out.println("\t y coordinate :"+pointOnContainer.getY()); System.out.println("Point on Screen"); System.out.println("\t x coordinate :"+pointOnScreen.getX()); System.out.println("\t y coordinate :"+pointOnScreen.getY()); } else return ; } public static void main(String[] args) {

Page 131: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 131

JFrame f= new JFrame("Use Point"); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); c.add(new usePoint(),BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); Point FramePoint = new Point(350,200); f.setSize(250,100); f.setLocation(FramePoint); f.show(); disPlayPoint(b1); } }

การทํางานของโปรแกรม สราง Frame f ขึ้นมาแบบปกติ จากนัน้สราง Point ‘FramePoint’ สําหรับกําหนดจดุแสดงผลใหกับ Frame โดยกําหนดไวที่ Coordinate(350,200) จากนั้นสง FramePoint ใหกับ Method setLocation() เพื่อกําหนดให f แสดงผลยังจุด Coordinate ที่กําหนดผาย FramePoint หลังจากนั้นสั่งใหแสดง f

Page 132: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 132

ดวย Method show() ก็มีการเรียกใช Method disPlayPoint() พรอมกับสงคา b1 เปน parameter ใหกับ Method ซ่ึงภายใน Method นี้จะนํา Component ที่รับเขามาหาจุด Coordinate ที่ Component นั้นวางอยูบน top-level window component และจุดที ่ Coordianate ที่ Component ทวางอยูบน Screen แลวจึงแสดงจุดเหลานั้นออกทางจอภาพ จากผลลัพธ ของตัวอยางะเหน็วา Frame f จะแสดงผล ณ.จุดที่กําหนดไวคือ (350,200) และแสดงจุด Coordinate ปุม b1ที่วางอยูบน top-level window Component และ Screen ออกทางจอภาพใหเหน็ดวย 1.29 Preferred Size เมื่อ Component ถูก add ใหกับ Container หนึ่งแลว Layout Manager จะพยายามคํานวณขนาดของ Component ทั้งหมดทีว่างอยูบน Container นั้น เพื่อพยายามทําให Component ตางๆที่วางอยูบน Container สามารถมองเห็นไดทั้งหมดโดยคาที่นํามาคํานวณขนาดของ Component เปนอันดับแรกคือ คา Preferred size ซ่ึงกําหนดไดโดยเรียกใช Method setPreferredSize() ของ Class JComponent ซ่ึงมีรูปแบบดังนี้

public void setPreferredSize(Dimension preferredSize) โดยที่ preferredSize คือคา Preferred size ที่ Layout Manager จะนํามาคาํนวณขนาดของ Component เปนอันดับแรกเพื่อให Component ดังกลาวสามารถมองเห็นได แตหากไมไดกําหนดคา Preferred size ไว Layout Manager ก็จะคํานวณขนาดของ Component ใหจาก font และขอความบน Component นั้น โดยสวนใหญแลว Method setPreferredSize() จะถูกนํามากําหนดใหกับ Container เพื่อระบวุาตองการให Container ดังกลาวมีขนาดเปนเทาใด หลังจากนั้นก็เรียกใช Method pack() ของ top-level window Component เพื่อปรับขนาดใหเทากับขนาดที่กําหนดไวเปนคา Preferred Size พอดี(ตองใชคูกับpack() เสมอ มิฉะนั้น setPreferredSize() จะไมทํางานตามที่กําหนดไว) ตัวอยางที่ 1.40 แสดงการกาํหนดคา Preferred size /*--------------------file usePreferredSize.java----------------------*/ import java.awt.* ; import javax.swing.* ; public class usePreferredSize extends JPanel {

Page 133: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 133

JButton b1; public usePreferredSize() { setPreferredSize(new Dimension(250,100)); //กําหนดขนาด Preferred size setLayout(new FlowLayout()); b1 = new JButton("OK"); add(new JLabel("Test Preferred sie")); add(b1); } public static void main(String[] args) { JFrame f=new JFrame("Use Preferred size"); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); c.add(new usePreferredSize(),BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.pack(); f.show(); } }

การทํางานของโปรแกรม Class “usePreferredSize ขยายมาจาก Class JPanel จึงทําให Class นี้มีลักษณะเปน Layout Container (non top-level Container) ซ่ึงสามารถที่จะ add Component ใดลงไปก็ได ในโปรแกรมกําหนดคา Preferred size ใหกับ Container มีคาเทากบั (250,100) หลังจากนั้นสราง Frame f ตามปกติแลว add Object ของ Class ดังกลาวนี้ใหกับ Container ของ f หลังจากนัน้เรียกใช Method pack() ของ f เพื่อปรับขนาดตางๆของ Component ตาม Layout Manager ใหพอดีกบั Frame ซ่ึงจาก

Page 134: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 134

ผลลัพธจะเห็นวา ขนาดของ Frame ที่ไดมีขนาดเทากับคา Preferred size พอดี ดวยคุณสมบัตินี้ทําใหเราสามารถสราง Panel พรอมกับกําหนดขนาดที่ตองการแสดงผลไวลวงหนาได 1.30 Pack เมื่อเรา add Component หลายๆ Component ลงไปใน Container หาก Container ดังกลาวกาํหนดขนาดไวเล็กเกนไป ก็อาจทําให Component บางตัวไมสามารถมองเห็นได(ตวัที่ add เขาไปทีหลัง) ดวยปญหาเหลานี้ในทางปฏบิัติเราจึงมักกําหนดขนาดของ Window หรือ Frame ไวใหใหญกวาพื้นที่ที่จะใชงานจริงเสมอ แตหากเราตองการให window หรือ Frame มีพื้นที่การแสดงผลเทากับพื้นที่การใชงานจริงในการแสดง Component ก็สามารถทําไดโดยเรียกใช Method ดังนี้

public void pack() Method pack() เปน Method ของ Class Window โดยเมื่อ Window หรือ Frame มีการเรียกใช Method นี้ Window ก็จะนําคา Preferred size (หากมีการกําหนดไว) มาคํานวณขนาด เพื่อใหได Window ที่มีขนาดเทากับคา Preferred size ของ Component ทั้งหมด แตหากไมมีกําหนดคา Preferred size ไว Window ก็จะคํานวณขนาดของ Component นั้นจาก font และขอความบน Component นั้นๆ ตัวอยางที่ 1.41 แสดงใหเหน็วาไมสามารถแสดง Component ไดทั้งหมด /*-------------------file UsenonPack.java-----------------*/ import java.awt.* ; import javax.swing.* ; public class UsenonPack extends JPanel { public UsenonPack() { setLayout(new FlowLayout()); add(new JTextArea(5,10)); add(new JButton("OK")); add(new JButton("Cancel")); } public static void main(String[] args) { JFrame f = new JFrame("Use non Pack"); Container c = f.getContentPane(); c.setLayout(new BorderLayout());

Page 135: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 135

c.add(new UsenonPack() , BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(200,100); f.show(); } }

การทํางานของโปรแกรม Panel UsenonPack มี Layout แบบ Flow Layout ซ่ึงประกอบดวย Component 3 ตัวคือ Text Area และ Button อีก 2 ปุม เมื่อนาํ Panel ดังกลาวมากําหนดใหกับ Container ของ Frame f มีการกําหนดขนาดไวเปน (200,100) และเมื่อส่ังใหแสดง f จะเหน็วาไมสามารถมองเห็น Component หมดทุกตวัได สาเหตุที่เปนแบบนีก้็เพราะวา เรากําหนดขนาดของ Frame นอยกวาขนาดของ Component ที่ตองการใชงานจริง ตัวอยางที่ 1.41 แสดงการใช pack() /*-------------------file UsePack.java-----------------*/ import java.awt.* ; import javax.swing.* ; public class UsePack extends JPanel { public UsePack() { setLayout(new FlowLayout()); add(new JTextArea(5,10)); add(new JButton("OK")); add(new JButton("Cancel")); } public static void main(String[] args) { JFrame f = new JFrame("Use non Pack"); Container c = f.getContentPane();

Page 136: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 136

c.setLayout(new BorderLayout()); c.add(new UsePack() , BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.pack(); f.show(); } }

การทํางานของโปรแกรม ตัวอยางนี้มีลักษณะการทํางานเหมือนกับตวัอยางที่ผานมา เพียงแตไมมกีารเรียกใช setSize() แตไดเรียกใช Method pack() ของ Frame f ซ่ึงจะเหน็วาขนาดของ Frame วามีขนาดทากับขนาดของ Component ที่ตองการแสดงผลพอดี 1.31 Maximized Bound และ Resizable ในการทํางานกับ Frame บางครั้งเราอาจตองการกําหนดวา เมื่อกดปุม maximize บน Frame จะให Frame มีขนาดเทาใดเราสามารถทําไดโดยเรยีกใช Method setMaximizedBounds() ดังนี้

public void setMaximizedBounds(Rectangle bounds) และหากตองการกําหนดให Frame ไมสามารถ Resize ไดก็สามารถทําไดโดยเรียกใช Method setResizable() ดังนี ้

public void setResizable(boolean resizable) และเมื่อตองการตรวจสอบวา Frame ดังกลาวสามารถ resize ไดหรือไมสามารถทําไดดวยการเรียกใช Method isResizable() ดังนี ้

public boolean isResizable()

Page 137: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 137

ตัวอยางที่ 1.42 แสดงการใช MaximizedBound() /*-------------------file UseMaximizedBound.java-----------------*/ import java.awt.* ; import javax.swing.* ; public class UseMaximizedBound extends JPanel { public UseMaximizedBound() { setLayout(new FlowLayout()); add(new JTextArea(5,10)); add(new JButton("OK")); add(new JButton("Cancel")); } public static void main(String[] args) { JFrame f = new JFrame("Use Maximzed Bound"); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); c.add(new UseMaximizedBound() , BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setMaximizedBounds(new Rectangle(370,200)); f.pack(); f.show(); } }

Page 138: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 138

การทํางานของโปรแกรม ตัวอยางมีลักษณะการทํางานเหมือนกับตวัอยางที่ผานมา เพียงแตมีการเรียกใช Method setMaximizedBounds() เพื่อกําหนดคา Maximize ของ Frame เปน (370,200) จากผลลัพธเมื่อเรากดปุม Maximize ขนาดของ Frame ก็จะขยายขึ้นเทากับขนาดของ Maximize ที่กําหนดไวพอด ี ตัวอยางที่ 1.43 แสดงการใช Resizable() /*-------------------file UseResizable.java-----------------*/ import java.awt.* ; import javax.swing.* ; public class UseResizable extends JPanel { public UseResizable() { setLayout(new FlowLayout()); add(new JTextArea(5,10)); add(new JButton("OK")); add(new JButton("Cancel")); } public static void main(String[] args) { JFrame f = new JFrame("Use Resizable"); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); c.add(new UseResizable() , BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setResizable(false); f.pack();

Page 139: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 139

f.show(); } }

การทํางานของโปรแกรม จะคลายกับโปรแกรมที่ผานมาเพียงแตมีกรเรียกใช Method “setRsizeable()” เพื่อกําหนดวาไมใหสามารถทําการ Resizeable ขนาดของ Frame ได และไมมกีารกําหนดขนาด Maximize ใหกับ Frame เพราะถึงกําหนดไปก็ไมมีประโยชนเพราะปุม Maximize ไมสามารถใชงานได 1.32 Icon และ ImageIcon Swing component บางตัวเราสามารถกําหนด Icon ใหแสดงพรอมกับ Component นั้นๆได ดังนัน้ใน package javax.swing จะกําหนดใหม ี Interface “Icon” เพื่อใชเปน Reference ในการกําหนด icon ใหกับ swing component ตางๆซึ่งภายใน interface icon มีการกําหนด abstract method ดังนี ้

public abstract void paintIcon(Component c,Graphics g,int x,int y) public abstract int getIconWidth() public abstract int getIconHeight()

โดยที่ Method paintIcon() ใชสําหรับวาด Icon ในตําแหนง x,y getIconWidth() ใหคาความกวางของ Icon getIconHeight() ใหคาความสูงของ Icon เพื่อใหเกิดความสะดวกในการใชงาน Icon ภายใน package javax.swing มี class ImageIcon ที ่implement Interface Icon ไวเรียบรอยแลว ดงันัน้เราจึงสามารถใชคุณสมบัติ Icon นี้ไดทันที class ImageIcon มี constructor และ Method ที่นาสนใจดังนี ้

Constructor/Method ความหมาย public ImageIcon(String filename) สราง ImageIcon จากไฟลรูปภาพที่กําหนดโดย

filename จะตองระบุถึงที่อยูของรูปภาพที่ตองการใชงาน

Page 140: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 140

public Image getImage() แปลง ImageIcon ไปเปน Image Object ตัวอยางที่ 1.44 แสดงการสราง IconImage /*--------------------file UseIcon.java--------------------*/ import java.awt.*; import javax.swing.*; public class UseIcon extends JPanel { public UseIcon() { setLayout(new FlowLayout()); ImageIcon icon1=new ImageIcon("./open.gif"); ImageIcon icon2=new ImageIcon("./save.gif"); ImageIcon icon3=new ImageIcon("./print.gif"); add(new JLabel("Open",icon1,SwingConstants.LEFT)); add(new JLabel("Save",icon2,SwingConstants.LEFT)); add(new JLabel("Print",icon3,SwingConstants.LEFT)); } public static void main(String[] args) { JFrame f=new JFrame("Use Icon"); Container c=f.getContentPane(); c.setLayout(new BorderLayout()); c.add(new UseIcon(),BorderLayout.NORTH); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setResizable(false); f.pack(); f.show(); } }

Page 141: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 141

1.33 JOptionPane ถึงแมวาเราสามารถสราง Dialog จาก class JDialog ขึ้นมาทํางานได แตอยางไรก็ตามการสราง Dialog จาก class JDialog โดยตรงนัน้จะตองเสียเวลาในการสรางมากพอสมควร ดังนัน้ใน Package javax.swing จึงไดจัดเตรยีม class JOptionPane เพื่อใชสําหรับสราง dialog ที่สรางจาก class JOptionPane โดย dialog ที่สรางขึ้นจะมีลักษณะเปน Modal Dialog ที่สรางจาก JOptionPane สามารถสรางขึ้นได 4 ประเภทคือ

1.Confirm Dialog ใชสําหรับถามผูใชเพื่อยืนยนัการกระทําโดยมีปุมใหเลือกคือ YES/NO/CANCEL หรือ YES/NO หรือ OK/CANCEL

2.Input Dialog ใชสําหรับรับ input จากผูใชโดยมีปุมใหใชคือ OK/CALCEL 3.Message Dialog ใชสําหรับแจงขาวสารใหผูใชทราบกบัเหตุการณที่เกิดขึ้น โดยมีปุมให ใชคือ OK 4.Option Dialog เปน dialog ที่สามารถมีขอมูลและปุมใดๆที่เรากําหนด คาคงที่และ Method ท่ําคัญของ class JOptionPane มีดังนี ้

คาคงที่และ Method ความหมาย public static final int CANCEL_OPTION คาคงที่ของปุม Cancel public static final int CLOSE_OPTION คาคงที่ของปุม Close public static final int OK_OPTION คาคงที่ของปุม Ok protected transient Object[] options คาคงที่ของปุมที่กําหนดขึ้นอง public static final int YES_OPTION คาคงที่ของปุม Yes public static final int ERROR_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type

ประเภท Error Message public static final int INFORMATION_MESSAGE

คาคงที่ใชกําหนด Icon ของ Message type ประเภท Information Message

public static final int WARNING_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type ประเภท Warning Message

public static final int QUESTION_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type ประเภท Question Message

public static final int PLAIN_MESSAGE คาคงที่ใชกําหนด Icon ของ Message type ประเภท Plain Message

public static final int DEFAULT_OPTION คาคงที่ใชกําหนดปุม option button โดย Default

Page 142: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 142

สําหรับเลือกยนืยันการทํางานใหกับ dialog public static final int YES_NO_OPTION คาคงที่ใชกําหนดปุม option button โดยมีปุม

YES และ NO สําหรับใชเลือกยืนยนัการทํางานใหกับ Dialog

public static final int YES_NO_CANCEL_OPTION

คาคงที่ใชกําหนดปุม option button โดยมีปุม YES, NO และ CALCEL สําหรับใชเลือกยืนยนัการทํางานใหกับ Dialog

public static final int OK_CANCEL_OPTION คาคงที่ใชกําหนดปุม option button โดยมีปุม OK และ CALCEL สําหรับใชเลือกยืนยันการทํางานใหกับ Dialog

public JOptionPane() สราง Option Pane public JOptionPane(Object message) สราง Option pane โดย message คือขอความที่

ตองการนํามาแสดง public JOptionPane(Object message, int messageType)

สราง Option Pane โดย message คือขอความที่ตองการนํามาแสดง messageType คือ Message Type วาเปนประเภทใด

public JOtonpane(Object message,int messageType,int optionType)

สราง Option Pane โดย message คือขอความตองการนํามาแสดง messageType คือ Message type วาเปนประเภทใด และ optionType คือ ปุมที่ตองการนํามาแสดง

public JOptionPane(Object message, int messageType, int optionType, Icon icon)

สราง Option Pane โดย message คือขอความตองการนํามาแสดง messageType คือ Message type วาเปนประเภทใด และ optionType คือ ปุมที่ตองการนํามาแสดงและ icon คือรูป icon ที่ตองการนํามาแสดง

public JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options)

สราง Option Pane โดย message คือขอความตองการนํามาแสดง messageType คือ Message type วาเปนประเภทใด และ optionType คือ ปุมที่ตองการนํามาแสดง icon คือรูป icon ที่ตองการนํามาแสดงและ options คือขอความที่นํามาสรางเปนปุมเพิ่มเติม

public JDialog createDialog(Component สราง Dialog จาก Option pane โดยม ี parent

Page 143: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 143

parentComponent,String title) throws HeadlessException

เปน parentComponent และ title เปนขอความ title ใหกับ Dialog

public void setIcon(Icon newIcon) กําหนด Icon ใหกับ Option pane public void setMessage(Object newMessage) กําหนด Message ที่ตองการแสดงใหกับ Option

Pane public void setMessageType(int newType) กําหนด Message Type ใหกบั Option pane public void setOptions(Object[] newOptions) กําหนด Option เพิ่มเติมใหกบั Option pane public void setOptionType(int newType) กําหนด Option Type ใหกับ Option pane public static int showConfirmDialog(Component parentComponent, Object message)

สรางและแสดง Confirm Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และ message คือขอความที่ตองการแสดงบน Dialog และมีปุม Yes/No และ Cancel เพื่อใชเลือกการทํางานของ Dialog และคืนคากลบัมาเปน int ตามคาคงที่ของปุมตางๆ

public static int showConfirmDialog(Component parentComponent,Object message,String title,int optionType)

สรางและแสดง Confirm Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และ message คือขอความที่ตองการแสดงบน Dialog ขอความบน title bar และ option type ผาน message ,title และ option type ตามลําดับ และคืนคากลับมาเปน int ตามคาคงที่ของปุมตางๆ

public static int showConfirmDialog(Component parentComponent,Object message,String title,int optionType, int messageType)

สรางและแสดง Confirm Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และ message คือขอความที่ตองการแสดงบน Dialog ขอความบน title bar และ option type ผาน message ,title และ option type ตามลําดับ และคืนคากลับมาเปน int ตามคาคงที่ของปุมตางๆ

public static int showConfirmDialog(Component parentComponent,Object message,String title,int optionType,int messageType, Icon icon)

สรางและแสดง Confirm Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และ message คือขอความ

Page 144: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 144

ที่ตองการแสดงบน Dialog ขอความบน title bar และ option type ผาน message ,title, option type และ icon ตามลําดับ และคืนคากลับมาเปน int ตามคาคงที่ของปุมตางๆ

public static String showInputDialog(Component parentComponent, Object message)

สรางและแสดง input Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และกําหนดขอความที่ใชแสดงบน Dialog ผาน message และหากมีการกดปุม Ok บน dialog ก็จะสงคากลับคืนเปน string สรางและแสดง input Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และกําหนดขอความที่ใชแสดงบน Dialog ผาน message พรอมกับกําหนดขอความเริ่มตนในชองรับขอมูลผาน initialSelectionValue และหากมีการกดปุม Ok บน dialog ก็จะสงคากลับคืนเปน string

public static String showInputDialog(Component parentComponent, Object message, Object initialSelectionValue)

สรางและแสดง input Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และกําหนดขอความที่ใชแสดงบน Dialog ขอความ Title bar, message type ผาน message ,title และ messageType ตามลําดับ และหากมกีารกดปุม Ok บน dialog ก็จะสงคากลับคืนเปน string

public static String showInputDialog(Component parentComponent, Object message, Object message, String title, int messageType)

public static Object showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)

สรางและแสดง input Dialog โดยระบุวา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และกําหนดขอความที่ใชแสดงบน Dialog ขอความ Title bar, message type,icon ขอความที่ใชกําหนดผานปุมตางๆขอความเริ่มตนที่กําหนดเปน input ผานทาง message ,title,icon, selectionValues, initialSelectionValue ตามลําดับ และหากมีการกด

Page 145: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 145

ปุม Ok บน dialog ก็จะสงคากลับคืนเปน string public static String showInputDialog(Object message)

สรางและแสดง input dialog โดยระบุขอความบน Dialog ผาน message และหากมีการกดปุม Ok บน dialog ก็จะสงคากลบัคืนเปน String

public static String showInputDialog(Object message,Object initialSelectionValue)

สรางและแสดง input dialog โดยระบุขอความบน Dialog ผาน message และกําหนดขอความที่กําหนดเปนคาเริ่มตนในการ input ผาน initialSelectionValue และหากมีการกดปุม Ok บน dialog ก็จะสงคากลับคืนเปน String

public static void showMessageDialog(Component parentComponent, Object message)

สรางและแสดง Message Dialog โดยระบวุา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได และกําหนดขอความบน dialog ผาน message

public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)

สรางและแสดง Message Dialog โดยระบวุา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได โดยกาํหนดขอความบน Dialog ขอความ Title Bar และ Message Type ผาน message, title,messageType ตามลําดบั

public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)

สรางและแสดง Message Dialog โดยระบวุา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได โดยกาํหนดขอความบน Dialog ขอความ Title Bar, Message Type และ icon ผาน message, title,messageType และ icon ตามลําดับ

public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] options,Object initialValue)

สรางและแสดง Message Dialog โดยระบวุา Component ใดเปน Parent Component หรือกําหนดเปน null ก็ได โดยกาํหนดขอความบน Dialog ขอความ Title Bar, Message Type ,icon,option,initialValue และหากมกีารกดปุม close บน Dialog ก็จะคืนคากลับมาเปน -1 และหากกดปุมใดๆบน Dialog ก็จะคนืคาเปนลําดับของปุมนั้นกลบัมา

Page 146: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 146

การสราง dialog จาก JOtionPane สวนใหญจะนิยมสรางและแสดง Dialog จากการเรียกใช static method ตางๆที่ไดแสดงไวในตารางมากกวากาสรางเปน Object เพราะมีความสะดวกดี ตัวอยางที่ 1.45 การสราง Confirm Dialog /*----------------file OptionPane1.java ------------------*/ import javax.swing.*; public class OptionPane1 { public static void main(String[] args) { int i = JOptionPane.showConfirmDialog(null,"Do you want to Exit Program",

"Confirm Dialog",JOptionPane.YES_NO_OPTION); if(i==JOptionPane.YES_OPTION) System.exit(0); else if(i==JOptionPane.CLOSED_OPTION) System.out.println("Close Dialog"); } } ผลการทํางาน

ตัวอยางที่ 1.46 การสราง Input Dialog /*----------------file OptionPane2.java ------------------*/ import javax.swing.*; public class OptionPane2 { public static void main(String[] args) { String input = ""; input = JOptionPane.showInputDialog(null,"Enter name","Input Dialog",

JOptionPane.PLAIN_MESSAGE);

Page 147: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 147

if(input != "") System.out.println(input); System.exit(0); } } ผลการทํางาน

ตัวอยางที่ 1.47 การสราง Input Dialog แบบกําหนดขอมูลใหเลือก /*----------------file OptionPane3.java ------------------*/ import javax.swing.*; public class OptionPane3 { public static void main(String[] args) { ImageIcon icon = new ImageIcon("./print.gif"); String[] printname = {"HP Laser","Fine Print","Epson"}; Object ob = JOptionPane.showInputDialog(null,"Select value Choice",

"Input Dialog",JOptionPane.PLAIN_MESSAGE,icon,printname,"Epson"); System.out.println(ob); } } ผลการทํางาน

Page 148: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 148

ตัวอยางที่ 1.48 การสราง Message Dialog /*----------------file OptionPane4.java ------------------*/ import javax.swing.*; public class OptionPane4 { public static void main(String[] args) { JOptionPane.showMessageDialog(null,"Foud Virus","Message Dialog",

JOptionPane.WARNING_MESSAGE); System.exit(0); } } ผลการทํางาน

ตัวอยางที่ 1.50 การนํา Component มาแสดงแทนขอความ /*----------------file OptionPane5.java ------------------*/ import java.awt.*; import javax.swing.*; public class OptionPane5 { public static void main(String[] args) { String st="คําเตือนการนั่งหนาจอคอพิวเตอรนานเกินไป\n"+

"จะทําใหอายกุารใชงานายตาของคุณสั้นลง\n"+ "เพราะฉะนั้นควรรักสายตาของคุณบาง";

Page 149: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 149

JTextArea text1=new JTextArea(4,10); text1.setForeground(Color.red); text1.setText(st); text1.setFont(new Font("Cordia New",0,18)); JOptionPane.showMessageDialog(null,text1,"Message Dialog",

JOptionPane.WARNING_MESSAGE); System.exit(0); } } ผลการทํางาน

จุดประสงคของการใช Message Dialog ก็เพื่อแสดงขอความประเภทขอความใหผูใชทราบวาเปนอยางไรบาง เราสามารถกําหนด Message Type ใหกับ Message Dialog เพื่อใหไดรูป icon เปนรูปตางๆดังนี ้

-ERROR_MESSAGE

-INFORMATION_MESSAGE

Page 150: unit1-การสร้าง GUI ด้วย swing

3901-2105 เอกสารการสอนวิชาการโปรแกรมเชิงวัตถุ 3 (Advanced Java) 150

ตัวอยางที่ 1.51 การสรางและใชงาน Option Dialog /*----------------file OptionPane6.java ------------------*/ import java.awt.*; import javax.swing.*; public class OptionPane6 { public static void main(String[] args) { ImageIcon icon=new ImageIcon("./save.gif"); String[] choice = {"ตกลง","ยกเลิก"}; int i = JOptionPane.showOptionDialog(null,"คุณตองการบันทึกขอมูลหรือไม"

,"Option Dialog",JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE,icon,choice,choice[1]);

if(i==0) System.out.println("Ok Save"); } } ผลการทํางาน