ๆญฏ์ œ9์žฅ.PDF

Similar documents
9แ„Œแ…กแ†ผ.key

์ž๋ฐ”GUI์‹ค์ „ํ”„๋กœ๊ทธ๋ž˜๋ฐ2_์žฅ๋Œ€์›.PDF

11แ„Œแ…กแ†ผ.key

๊ฐ•์˜์ž๋ฃŒ

<4D F736F F F696E74202D20C1A63233C0E520B1D7B7A1C7C820C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

10แ„Œแ…กแ†ผ.key

<4D F736F F F696E74202D20C1A63230C0E520BDBAC0AE20C4C4C6F7B3CDC6AE203128B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - EEL2 Lecture10 -Swing and Event Handling.pptx

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - 04-UDP Programming.ppt

gnu-lee-oop-kor-lec10-1-chap10

Microsoft PowerPoint - ร€รšยนร™08ร€รฅ-1.ppt

Microsoft PowerPoint - ร€รšยนร™08ร€รฅ-2.ppt

Chap12

11-GUI.key

public class FlowLayoutPractice extends JFrame { public FlowLayoutPractice() { super("flowlayout Practice"); this. Container contentpane = getcontentp

iii. Design Tab ์„ Click ํ•˜์—ฌ WindowBuilder ๊ฐ€์ž๋™์œผ๋กœ์ƒ์„ฑํ•œ GUI ํ”„๋กœ๊ทธ๋ž˜๋ฐํ™˜๊ฒฝ์„ํ™•์ธํ•œ๋‹ค.

Java Programing Environment

05-class.key

์ œ8์žฅ ์ž๋ฐ” GUI ํ”„๋กœ๊ทธ๋ž˜๋ฐ II

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

Microsoft PowerPoint - 06-Chapter09-Event.ppt

01-OOPConcepts(2).PDF

Microsoft PowerPoint ์ž๋ฐ”-AWT์ปดํฌ๋„ŒํŠธ(Ch8).pptx

๋ชจ๋“ ์Šค์œ™์ปดํฌ๋„ŒํŠธ์—๋Š”ํ…์ŠคํŠธ์˜†์—์ด๋ฏธ์ง€๋ฅผ์ถ”๊ฐ€๋กœํ‘œ์‹œํ• ์ˆ˜์žˆ๋‹ค. ImageIcon image = new ImageIcon("image.gif"); JLabel label = new JLabel(" ์ด๋ฏธ์ง€๋ ˆ์ด๋ธ” "); label.seticon(image);

Microsoft PowerPoint - [JAVAํ”„๋กœ๊ทธ๋ž˜๋ฐ]9์žฅGUI

rmi_๋ฐ•์ค€์šฉ_final.PDF

PowerPoint Presentation

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63138C0E520C0CCBAA5C6AE20C3B3B8AE28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - java1-lecture11.ppt [ํ˜ธํ™˜ ๋ชจ๋“œ]

PowerPoint Presentation

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

Microsoft PowerPoint - 14์ฃผ์ฐจ ๊ฐ•์˜์ž๋ฃŒ

10 แ„‹แ…ตแ„‡แ…ฆแ†ซแ„แ…ณ แ„Žแ…ฅแ„…แ…ตแ„‹แ…ช แ„€แ…ณแ„…แ…ขแ„‘แ…ตแ†จ แ„‘แ…ณแ„…แ…ฉแ„€แ…ณแ„…แ…ขแ„†แ…ตแ†ผ.key

02 C h a p t e r Java

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

Microsoft PowerPoint - Java-03.pptx

Microsoft PowerPoint - java1-lecture11.ppt [ํ˜ธํ™˜ ๋ชจ๋“œ]

1

์ž๋ฐ”๋กœ

ch09

PowerPoint Presentation

JMF3_์‹ฌ๋นˆ๊ตฌ.PDF

5แ„Œแ…กแ†ผ.key

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

PowerPoint Presentation

Java Coding Standard

Orcad Capture 9.x

09-interface.key

Cluster management software

No Slide Title

์Šฌ๋ผ์ด๋“œ 1

๋น„๊ธด์ฟก-์ž๋ฐ” 00์•ž๋ถ€์†

Dialog Box ์‹คํ–‰ํŒŒ์ผ์„ Web์— ํฌํ•จ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

์Šฌ๋ผ์ด๋“œ 1

์ œ8์žฅ ์ž๋ฐ” GUI ํ”„๋กœ๊ทธ๋ž˜๋ฐ II

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

Microsoft PowerPoint - java2-lecture5.ppt [ํ˜ธํ™˜ ๋ชจ๋“œ]

07 แ„Œแ…กแ„‡แ…กแ„‹แ…ด แ„ƒแ…กแ„‹แ…ฃแ†ผแ„’แ…กแ†ซ แ„แ…ณแ†ฏแ„…แ…ขแ„‰แ…ณ.key

12-file.key

Microsoft PowerPoint - java1-lecture10.ppt [ํ˜ธํ™˜ ๋ชจ๋“œ]

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

LCD Display

1

(Microsoft PowerPoint - LZVNQBAJWGTC.ppt [\310\243\310\257 \270\360\265\345])

์ œ1์žฅ ์ž๋ฐ” ์–ธ์–ด ์†Œ๊ฐœ

์˜ค๋ฒ„๋ผ์ด๋”ฉ (Overriding)

์Šฌ๋ผ์ด๋“œ 1

Interstage5 SOAP์„œ๋น„์Šค ์„ค์ • ๊ฐ€์ด๋“œ

์ž๋ฐ” ํ”„๋กœ๊ทธ๋ž˜๋ฐ

<4D F736F F F696E74202D20C1A63236C0E520BED6C7C3B8B428B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

DocsPin_Korean.pages

JMF2_์‹ฌ๋นˆ๊ตฌ.PDF

8์žฅ.๊ทธ๋ž˜ํ”ฝ ํ”„๋กœ๊ทธ๋ž˜๋ฐ

MasoJava4_Dongbin.PDF

ilist.add(new Integer(1))๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ilist.add(1)๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•œ ๊ฒƒ์€ ์ž๋ฐ” 5.0์— ์ถ”๊ฐ€๋œ ๊ธฐ๋ณธ ์ž๋ฃŒํ˜•๊ณผ ํ•ด๋‹น ๊ฐ์ฒด ์ž๋ฃŒ ํ˜•๊ณผ์˜ ์˜คํ† ๋ฐ•์‹ฑ/์–ธ๋ฐ•์‹ฑ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•œ ๊ฒƒ์œผ๋กœ ์˜คํ† ๋ฐ•์‹ฑ์ด๋ž€ ์ž๋ฐ” ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ๊ฐ์ฒด๋ฅผ ์š”๊ตฌํ•˜๋Š” ๊ณณ์— ๊ธฐ๋ณธ ์ž๋ฃŒํ˜•

Cluster management software

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_fโ€ฆ

(Microsoft PowerPoint - java1-lecture7.ppt [\310\243\310\257 \270\360\265\345])

No Slide Title

untitled

10-Java Applet

Eclipse ์™€ Firefox ๋ฅผ์ด์šฉํ•œ Javascript ๊ฐœ๋ฐœ ๋ฐœํ‘œ์ž : ๋ฌธ๊ฒฝ๋Œ€ 11 ๋…„ 10 ์›” 26 ์ผ์ˆ˜์š”์ผ

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

์ค‘๊ฐ„๊ณ ์‚ฌ

DB ์—๋ฐ์ดํ„ฐ์ €์žฅ์„์œ„ํ•œ์ž…๋ ฅ์ฐฝ์„ค๊ณ„ - JLabel, JTextField, JButton ์„์ด์šฉํ•œ์ž…๋ ฅ์ฐฝ์„ค๊ณ„ - 2 -

MAX+plus II Getting Started - ๋ฌด์ž‘์ •๋”ฐ๋ผํ•˜๊ธฐ

03-JAVA Syntax(2).PDF

03์žฅ

2011๋…„ 10์›” ์ดˆํŒ c 2011 Sony Corporation. All rights reserved. ์„œ๋ฉด ํ—ˆ๊ฐ€ ์—†์ด ์ „์ฒด ๋˜๋Š” ์ผ๋ถ€๋ฅผ ๋ณต์ œํ•˜๋Š” ๊ฒƒ์„ ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ๋Šฅ ๋ฐ ๊ทœ๊ฒฉ์€ ํ†ต๋ณด ์—†์ด ๋ณ€๊ฒฝ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. Sony์™€ Sony ๋กœ๊ณ ๋Š” Sony์˜ ์ƒํ‘œ์ž…๋‹ˆ๋‹ค. G L

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

JTable๊ณผ MVC(Model-View-Controller) ๊ตฌ์กฐ - ๋ชจ๋ธ-๋ทฐ-์ปจํŠธ๋กค๋Ÿฌ๊ตฌ์กฐ๋Š”๋ฐ์ดํ„ฐ์˜์ €์žฅ๊ณผ์ ‘๊ทผ์—๋Œ€ํ•œ์ œ๊ณต์€๋ชจ๋ธ์ด๋‹ด๋‹นํ•˜๊ณ , ํ™”๋ฉดํ‘œ์‹œ๋Š”๋ทฐ, ์ด๋ฒคํŠธ์˜์ฒ˜๋ฆฌ๋Š”์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ํ•˜๋„๋ก๊ฐ์—ญํ• ์„๊ตฌ๋ถ„ํ•œ๊ตฌ์กฐ์ด๋‹ค. ์ฆ‰, ์—ญํ• ์˜๋ถ„๋‹ด์„ํ†ตํ•˜์—ฌ์ƒํ˜ธ๊ฐ„์˜์˜ํ–ฅ์„์ตœ์†Œํ™”ํ•˜๊ณ ๊ฐ์š”์†Œ์˜๋…๋ฆฝ์„ฑ์„๋ณด์žฅํ•˜์—ฌ๋…์ž

JavaPrintingModel2_JunoYoon.PDF

PowerPoint Presentation

PowerPoint ํ”„๋ ˆ์  ํ…Œ์ด์…˜

Microsoft Word - java18-1-final-answer.doc

13ร€รฅรƒรŸยฐยกยบร

Transcription:

9 (Swing) Model-View-Controller 1

8 GUI(Graphic User Interface) GUI (swing) (architecture),,, look and feel AWT 2 (frame work) Kim Topley Core Java Foundation Classes (Prentice Hall 1998) - - ( Model-View-Controller Design Pattern) (Swing Component Architecture) (Tree) ( ) (content) (visual appearance) (behavior) : look and feel Metal Window Motif, look and feel - - - - 5 look and feel (content) - - (Model-View- Controller: MVC) 3 (Model): (content) (View): (Controller): (Input) 3 (content), (active) (tag) 2

(view) 9-1: (abstract) ---------------------------------------------------------------------- : (simulate) - - - - HTML WYSIWYG(What you see is what you get) (tag) 9-2 9-3:,,, Christoper Alexander 3

Timeless way of Building(Oxford University Press) Alexander (catalog) 1 2 - - 9-4 - - look and feel, 3,, - - - - - Elements of Reusable Object-Oriented Software by Erich Gamma A system of Patterns by Frank Buschmann John Wiley & sons 1996 - - AWT listener - - listener - - (JButton JTextField ) (wrapper) ( ), (wrapper) ( (caret) ), 4

( look and feel ) - - (pluggable) look and feel look and feel look and feel (pluggable) look and feel (wrapper) - -,, - - model ButtonModel DefaultButtonModel ButtonModel Table 9-1 (accessor) 9-1 ButtonModel GetActionCommand (action) ( ) getmnemonic( ) isarmed( ) true isenabled( ) true ispressed( ) true isrollover( ) true isselecteed( ) (toggle) true - (radio button) (check box) ) JButton JButton button = new JButton( Blue ); ButtonMode modeel = buttongetmodel ( ); - JButton ( JButton ) 5

ButtonModel ( DefaultButtonModel),,, metal look and feel JButton ButtonUIListener BasicButtonUI UI JButton JButton DefaultButtonModel ( ), DefaultButtonUI JComponent (layout) JDK VB Delphi (form) (designer) Java-enabled look and feel 9-5: 3 1 JButton yellowbutton = new JButton( Yellow ) 2 add(yellowbutton); 3 yellowbuttonaddactionlistener(this);? 9-6 6 9-6: (flow) 6 ( 9-7) 9-7 (dynamic) : (default) 6

FlowLayout LEFT RIGHT setlayout ( new FlowLayout(FlowLayoutLEFT)) (flow) (reflow) : (version) javaawtcontainer setlayout(layoutmanager m) void add(component c) API) javaawtflowlayout FlowLayout(int align) FlowLayout : align : LEFT, CENTER, RIGHT FlowLayout(int align, int hgap, intvgap) FlowLayout : align : LEFT, CENTER, RIGHT hgap ( (overlap) ) vgap ( (overlap) ) (Border Layout) JFrame (pane) north, south, east, west center ( 9-8) 9-8 class MyPanel extends JPanel { setlayout( new BorderLayout( ) ); 7

add(yellowbutton, South ); center, (center) North, South, East, West Center ( ) Center ( ) BorderLayout JFrame (content pane) center Container contentpane = getcontentpane( ); contentpaneadd(yellowbutton, South ); api: javaawtcontainer void add(component c, Object constraints) : c constraints (identifier) api:javaawtborderlayout(int hgap, int vgap), BorderLayout : hgap ( (overlap) ) vgap ( (overlap) ) BorderLayout 9-9 (southern) (panel) (prototype) GridBagLayout 9-9 8

VB : (picture box) 9-10 (south) 9-10 9-10 JPanel (instance) FlowLayout add FlowLayout 3 Container contentpane = getcontentpane ( ); JPanel panel new JPanel ( ); paneladd(yellowbutton); paneladd(bluebutton); paneladd(redbutton); contentpaneadd(panel, South ); : (organizee) JPanel FlowLayout setlayout JPanel ( ) api) javaxswingjpanel JPanel (LayoutManager m) (edit) 2 text fields text areas text field text area JTextField JTextArea JTextComponent JTextComponent API JTextComponent API field area 9

JTextComponent api: javaxswingjtextcomponent void settext(string t) t String gettext( ) void seteditable (boolean b) JTextComponent (text field) JPanel panel = new JPanel(); JTextField textfield = new JTextField( Default input, 20); paneladd(textfield); Default input 20, (column) n n 1 2 AWT JTextField (run time) setcolumn ---------------- : setcolumns validate textfieldsetcolumns(10); validate( ); validate validate --------------------, JTextField 10

JTextField textfield = new JTextField(, 20); TextComponent settext, hourfieldsettext( 12 ); gettext gettext trim String hour = hourfieldgettext()trim();, javaawtcomponent setfont 9-11 2 (update) 9-11 ( ) : (the model) (view) (architecture) (formated), ( HTML) Document document listener document textfieldlgetdocument ( )adddocumentlistener (listener) ; void insertupdate(documentevent e) void removeupdate(documentevent e) void changedupdate(documentevent e) (callback) - (adapter) listener 3 class TextTestFrame extends JFrame implements DocumentListener { public void insertupdate(documentevent e) { setclock(); 11

public void removeupdate(documentevent e) { setclock(); public void changedupdate(documentevent e) { setclock gettext (integer) int hours = IntegerparseInt(hourFieldgetText()trim()); int minutes = IntegerparseInt(minuteFieldgetText()trim()); two javalangnumberformatexception DocumentEvent qusghkeehls 8 ActionEvent DocumentEvent DocumentEvent EventObejct getsource public void insertupdate(documentevent e) { Document d = egetdocument ( );? (editablee) HTML (structure) (reference) (reference) Document d = egetdocument( ); int length = dgetlength( ); String text = null; try { text = dgettext(0, length); catch(badlocationexception ex) { 9-1 (listener) ------------- 12

: (listener) ENTER ENTER (focus) ---------------------- 9-1:TextTestjava import javaawt*; import javaawtevent*; import javaxswing*; import javaxswingevent*; class TextTestFrame extends JFrame implements DocumentListener { public TextTestFrame() { settitle("texttest"); setsize(300, 200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); Container contentpane = getcontentpane(); JPanel p = new JPanel(); hourfield = new JTextField("12", 3); padd(hourfield); hourfieldgetdocument()adddocumentlistener(this); minutefield = new JTextField("00", 3); padd(minutefield); minutefieldgetdocument()adddocumentlistener(this); contentpaneadd(p, "South"); clock = new ClockPanel(); contentpaneadd(clock, "Center"); public void insertupdate(documentevent e) { setclock(); public void removeupdate(documentevent e) { setclock(); public void changedupdate(documentevent e) { public void setclock() { int hours = IntegerparseInt(hourFieldgetText()trim()); 13

int minutes = IntegerparseInt(minuteFieldgetText()trim()); clocksettime(hours, minutes); private JTextField hourfield; private JTextField minutefield; private ClockPanel clock; class ClockPanel extends JPanel { public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawoval(0, 0, 100, 100); double hourangle = 2 * MathPI * (minutes - 3 * 60) / (12 * 60); double minuteangle = 2 * MathPI * (minutes - 15) / 60; gdrawline(50, 50, 50 + (int)(30 * Mathcos(hourAngle)), 50 + (int)(30 * Mathsin(hourAngle))); gdrawline(50, 50, 50 + (int)(45 * Mathcos(minuteAngle)), 50 + (int)(45 * Mathsin(minuteAngle))); public void settime(int h, int m) { minutes = h * 60 + m; repaint(); private int minutes = 0; public class TextTest { public static void main(string[] args) { JFrame frame = new TextTestFrame(); frameshow(); API: javaawtcomponent void validate ( ) API:javaawtJTextField JTextField(cols) JTextfield : cols JTextField(String text, int cols) JTextfield 14

: text cols void setcolumns( int cols) : cols API) javaxswingtextdocument int getlength( ) String gettext(int offset, int length) : offset length void adddocumentlistener(documentlistener listener) API:javaxswingeventDocumentEvent Document getdocument( ) API) javaxswingeventdocumentlistener void changedupdate(documentevent e) (set) void insertupdate(documentevent e) void changedupdate(documentevent e) (validation), 0-9 JTextField IntTextField (validating) (key) (listener) 15

(consume) ( (consuming) 8 ) (valid) 3 3-3 look and feel (cut), (copy), (paste) metal look and feel CTRL+V - - (caret) DocumentinsertString ( ) TextField PlainDocument Document IntTextDocument PlainDocument insertstring insertstring ( ) IntTextDocument insertstring IntegerparseInt superinsertstring PlainDocumentinsertString IntegerparseInt IntTextDocument insertstring ( 11 ) class IntTextDocument extends PlainDocument { public void insertstring(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) return; String oldstring = gettext(0, getlength()); String newstring = oldstringsubstring(0, offs) + str + oldstringsubstring(offs); try { IntegerparseInt(newString + "0"); superinsertstring(offs, str, a); catch(numberformatexception e) { JTextField IntTextField 16

createdefaultmodel IntTextDocument PlainDocument class IntTextField extends JTextField { public IntTextField(int defval, int size) { super("" + defval, size); protected Document createdefaultmodel() { return new IntTextDocument(); (entry) 3 insertstring( ) 0 IntTextField isvalid insertstring isvalid IntTextField getvalue getvalue isvalid --------- VB : KeyAscii 0 VB java ---------- 9-2 IntTextField ------------- : Toolkit (beep) ToolkitgetdefaultToolkit( )beep( ); --------------- 9-2 ValidationTextjava import javaawt*; import javaawtevent*; import javaxswing*; import javaxswingevent*; import javaxswingtext*; class ValidationTestFrame extends JFrame implements DocumentListener { public ValidationTestFrame() 17

{ settitle("validationtest"); setsize(300, 200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); Container contentpane = getcontentpane(); JPanel p = new JPanel(); hourfield = new IntTextField(12, 3); padd(hourfield); hourfieldgetdocument()adddocumentlistener(this); minutefield = new IntTextField(0, 3); padd(minutefield); minutefieldgetdocument()adddocumentlistener(this); contentpaneadd(p, "South"); clock = new ClockPanel(); contentpaneadd(clock, "Center"); public void insertupdate(documentevent e) { setclock(); public void removeupdate(documentevent e) { setclock(); public void changedupdate(documentevent e) { public void setclock() { if (hourfieldisvalid() && minutefieldisvalid()) { int hours = hourfieldgetvalue(); int minutes = minutefieldgetvalue(); clocksettime(hours, minutes); private IntTextField hourfield; private IntTextField minutefield; private ClockPanel clock; class ClockPanel extends JPanel { public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawoval(0, 0, 100, 100); double hourangle = 2 * MathPI * (minutes - 3 * 60) / (12 * 60); double minuteangle 18

= 2 * MathPI * (minutes - 15) / 60; gdrawline(50, 50, 50 + (int)(30 * Mathcos(hourAngle)), 50 + (int)(30 * Mathsin(hourAngle))); gdrawline(50, 50, 50 + (int)(45 * Mathcos(minuteAngle)), 50 + (int)(45 * Mathsin(minuteAngle))); public void settime(int h, int m) { minutes = h * 60 + m; repaint(); public void tick() { minutes++; repaint(); private int minutes = 0; public class ValidationTest { public static void main(string[] args) { JFrame frame = new ValidationTestFrame(); frameshow(); class IntTextDocument extends PlainDocument { public void insertstring(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) return; String oldstring = gettext(0, getlength()); String newstring = oldstringsubstring(0, offs) + str + oldstringsubstring(offs); try { IntegerparseInt(newString + "0"); superinsertstring(offs, str, a); catch(numberformatexception e) { class IntTextField extends JTextField { public IntTextField(int defval, int size) { super("" + defval, size); protected Document createdefaultmodel() { return new IntTextDocument(); 19

public boolean isvalid() { try { IntegerparseInt(getText()); return true; catch(numberformatexception e) { return false; public int getvalue() { try { return IntegerparseInt(getText()); catch(numberformatexception e) { return 0; API) javaxswingtextjtextcomponent int getcaretposition ( ) ( ) void SetCaretPosition(int pos) ( ) API) javaxswingtextdocument void insertstring(int offset, String str) null : offset (offset) str void remove(int offset, String len) : offset (offset) len API) javaxswingjtextfield Document createdefaultmodel ( ) (PlainDocument ) (Password fields) 20

(*) JPasswordField - - API) javaswingjpasswordfield JPasswordField(String text, int columns) : text null columns void setechochar(char echo) look and feel 0 : echo char[] getpassword (overwrite) ( (garbage) ) (Text Area) JTextArea, ENTER \n 12 StringTokenizer 9-12 JTextArea textarea = new JTextArea(8, 40) // 8 40 getcontentpane( )add(textarea); 1 2 setcolumns setrows (line-wrapping) textareasetlinewrap(true); // 21

9-12: (wrapping) \n (scroll pane) textareea = new JTextArea(8, 40); JScrollPane scrollpane = new JScrollPane(textArea); getcontentpane( )add(scrollpane, Center ); - 9-3 Insert - (line-wrapping) wrap no wrap (section) (highlight) (cut), (copy), (paste) CTRL+X, CTRL+C CTRL+V ( look and feel Metal, Windows, Mac look and feel ) ------------------ : JTextArea (HTML RTF ) JEditorPane JTextPane 2 ------------------- 9-3:TextAreaTextjava import javaawt*; import javaawtevent*; import javaxswing*; class TextAreaFrame extends JFrame implements ActionListener { public TextAreaFrame() { JPanel p = new JPanel(); insertbutton = new JButton("Insert"); padd(insertbutton); insertbuttonaddactionlistener(this); wrapbutton = new JButton("Wrap"); padd(wrapbutton); wrapbuttonaddactionlistener(this); nowrapbutton = new JButton("No wrap"); padd(nowrapbutton); 22

nowrapbuttonaddactionlistener(this); getcontentpane()add(p, "South"); textarea = new JTextArea(8, 40); scrollpane = new JScrollPane(textArea); getcontentpane()add(scrollpane, "Center"); settitle("textareatest"); setsize(300, 300); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); public void actionperformed(actionevent evt) { Object source = evtgetsource(); if (source == insertbutton) textareaappend ("The quick brown fox jumps over the lazy dog "); else if (source == wrapbutton) { textareasetlinewrap(true); scrollpanevalidate(); else if (source == nowrapbutton) { textareasetlinewrap(false); scrollpanevalidate(); private JButton insertbutton; private JButton wrapbutton; private JButton nowrapbutton; private JTextArea textarea; private JScrollPane scrollpane; public class TextAreaTest { public static void main(string[] args) { JFrame f = new TextAreaFrame(); fshow(); API) javaswingjtextarea JTextArea(int rows, int cols) : rows cols 23

JTextArea(String text, int rows, int cols) : text rows cols void setcolumns(int cols) : cols void setrows(int rows) : cols void append(string newtext) : newtext void setlinewrap(boolean wrap) - (line-wrapping) wrap (wrap) true void setwrapstyleword(boolean word) word true word (boundary) (wrap) false word API) javaxswingjscrollpane JScrollPane(Component c) : c ( (boundary) ) (identify) (identifier) JLabel JLabel SwingConstants LEFT, 24

RIGHT, CENTER, NORTH, EAST JLabel JLabel label = new JLabel ( Text, SwingConstantsLEFT); JLabel label = new JLabel( Text, JLabelLEFT) settext seticon 9-13 with API) javaxswingjlabel JLabel(String text) : text JLabel(Icon icon) icon JLabel(String text, int align) : text align SwingConstantsLEFT, SwingConstantsRIGHT, SwingConstantsCENTER JLabel(String text, Icon icon, int align) : text icon align SwingConstantsLEFT, SwingConstantsRIGHT, SwingConstantsCENTER void settext(string text) : text void seticon(string text) : text ( ) 25

, selectall(),, select select substring 1, tselect(10, 15) 10 14 (End-of-line) getselectionstart getselectionend getselectedtext Windows SHIFT + arrow API) javaawttextjtextcomponent void selectall() void select(int selstart, int selend) : selstart selend + 1 int getselectionstart() int getselectionend() + 1 String getselectedtext() JTextArea, 9-4 find-and-replace 7-6 Replace, URL 9-4: TextEditTestjava 26

import javaawt*; import javaawtevent*; import javaxswing*; class TextEditFrame extends JFrame { public TextEditFrame() { settitle("textedittest"); setsize(300, 300); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); Container contentpane = getcontentpane(); JPanel panel = new JPanel(); JButton replacebutton = new JButton("Replace"); paneladd(replacebutton); replacebuttonaddactionlistener(new ActionListener() { public void actionperformed(actionevent evt) { String f = fromgettext(); int n = textareagettext()indexof(f); if (n >= 0 && flength() > 0) textareareplacerange(togettext(), n, n + flength()); ); from = new JTextField(8); paneladd(from); paneladd(new JLabel("with")); to = new JTextField(8); paneladd(to); textarea = new JTextArea(8, 40); scrollpane = new JScrollPane(textArea); contentpaneadd(panel, "South"); contentpaneadd(scrollpane, "Center"); private JScrollPane scrollpane; private JTextArea textarea; private JTextField from, to; public class TextEditTest { public static void main(string[] args) { JFrame f = new TextEditFrame(); fshow(); 27

API) javaawtjtextarea void inserttext(string str, int pos) : str pos (0=, \n ) void replacerange(string str, int start, int end) : str start end + 1,, (Check Box) yes no, 9-14 : italic (helper) public CheckBoxFrame() { JPanel p = new JPanel(); bold = addcheckbox(p, "Bold"); italic = addcheckbox(p, "Italic"); add(p, "South"); public JCheckBox addcheckbox(jpanel p, String name) { JCheckBox c = new JCheckBox(name); caddactionlistener(this); padd(c); return c; 28

9-14 setselected boldsetselected(true); actionperformed isselected false true public void actionperformed(actionevent evt) { int m = (boldisselected()? FontBOLD : 0) + (italicisselected()? FontITALIC : 0); panelsetfont(m); 9-5 ------------ : AWT JCheckBox Checkbox ---------------- Example 9-5 CheckBoxTestjava import javaawt*; import javaawtevent*; import javaxswing*; class CheckBoxFrame extends JFrame implements ActionListener { public CheckBoxFrame() { settitle("checkboxtest"); setsize(300, 200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); JPanel p = new JPanel(); bold = addcheckbox(p, "Bold"); italic = addcheckbox(p, "Italic"); getcontentpane()add(p, "South"); panel = new CheckBoxTestPanel(); getcontentpane()add(panel, "Center"); public JCheckBox addcheckbox(jpanel p, String name) { JCheckBox c = new JCheckBox(name); 29

caddactionlistener(this); padd(c); return c; public void actionperformed(actionevent evt) { int m = (boldisselected()? FontBOLD : 0) + (italicisselected()? FontITALIC : 0); panelsetfont(m); private CheckBoxTestPanel panel; private JCheckBox bold; private JCheckBox italic; class CheckBoxTestPanel extends JPanel { public CheckBoxTestPanel() { setfont(fontplain); public void setfont(int m) { setfont(new Font("SansSerif", m, 12)); repaint(); public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawstring ("The quick brown fox jumps over the lazy dog", 0, 50); public class CheckBoxTest { public static void main(string[] args) { JFrame frame = new CheckBoxFrame(); frameshow(); API) javaawtjcheckbox JCheckbox(String label) : label JCheckbox(String label, boolean state) : label state JCheckbox(String label, boolean state) 30

: label icon boolean isselected() void setselected(boolean state),, (radio button group) 9-15 Small, Medium, Large, Extra-large ButtonGroup JRadioButton small = new JRadioButton( Small, false) medium = new JRadioButton( Medium, true) ButtonGroup group = new ButtonGroup ( ); groupadd(small); groupadd(medium); 9-15 true false JPanel 9-14 9-15 public void actionperformed(actionevent evt) { Object source = evtgetsource(); if(source == smallbutton) panelsetsize(8); else if (source == mediumbutton) panelsetsize(12); 31

isselected ButtonGroup ButtonGroup getselection ButtonModel (view) ButtonModel ButtonModel getselectedobjects ItemSelectable null ButtonModel getactioncommand setactioncommand buttongroupgetselectiongetactioncommand( ) 9-7 BorderText 9-6 9-6:RadioButtonTestjava import javaawt*; import javaawtevent*; import javaxswing*; class RadioButtonFrame extends JFrame implements ActionListener { public RadioButtonFrame() { settitle("radiobuttontest"); setsize(400, 200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); JPanel buttonpanel = new JPanel(); ButtonGroup group = new ButtonGroup(); smallbutton = addradiobutton(buttonpanel, group, "Small", false); mediumbutton = addradiobutton(buttonpanel, group, "Medium", true); largebutton = addradiobutton(buttonpanel, group, "Large", false); xlargebutton = addradiobutton(buttonpanel, group, "Extra large", false); 32

getcontentpane()add(buttonpanel, "South"); panel = new RadioButtonTestPanel(); getcontentpane()add(panel, "Center"); public JRadioButton addradiobutton(jpanel buttonpanel, ButtonGroup g, String buttonname, boolean v) { JRadioButton button = new JRadioButton(buttonName, v); buttonaddactionlistener(this); gadd(button); buttonpaneladd(button); return button; public void actionperformed(actionevent evt) { Object source = evtgetsource(); if(source == smallbutton) panelsetsize(8); else if (source == mediumbutton) panelsetsize(12); else if (source == largebutton) panelsetsize(14); else if (source == xlargebutton) panelsetsize(18); private RadioButtonTestPanel panel; private JRadioButton smallbutton; private JRadioButton mediumbutton; private JRadioButton largebutton; private JRadioButton xlargebutton; class RadioButtonTestPanel extends JPanel { public RadioButtonTestPanel() { setsize(12); public void setsize(int p) { setfont(new Font("SansSerif", FontPLAIN, p)); repaint(); public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawstring ("The quick brown fox jumps over the lazy dog", 0, 50); public class RadioButtonTest { public static void main(string[] args) { JFrame frame = new RadioButtonFrame(); 33

frameshow(); API) javaxswingjradiobutton JRadioButton(String label, boolean state) : label state JRadioButton(String label, Icon icon) : label state API) javaxswingbuttongroup void add(abstractbutton b) ButtonModel getselection( ) API) javaxswingbuttonmodel String getactioncommand API) javaxswingabstractbutton void setactioncommand(string s) (Border) JComponent 1 BorderFactory Lowered bevel Raised bevel Etched Line Matte Empty ( ) 2 34

BorderFactorycreateTiledBorder 3 BorderFactorycreateCompoundBorder 4JComponent setborder etched Border etched = BorderFactorycreateEchedBorder ( ); Border titled = BorderFactorycreateTitledBorder (etched, A Title ); panelsetborder(titled); 9-7 (option) API n beveled border SoftBevelBorder BorderFactory 9-16 9-7:BorderTextjava import javaawt*; import javaawtevent*; import javaxswing*; import javaxswingborder*; class BorderFrame extends JFrame implements ActionListener { public BorderFrame() { JPanel buttonpanel = new JPanel(); group = new ButtonGroup(); addradiobutton(buttonpanel, group, "Lowered bevel", true); addradiobutton(buttonpanel, group, "Raised bevel", false); addradiobutton(buttonpanel, group, "Etched", false); addradiobutton(buttonpanel, group, "Line", false); addradiobutton(buttonpanel, group, "Matte", false); addradiobutton(buttonpanel, group, "Empty", false); Border etched = BorderFactorycreateEtchedBorder(); Border titled = BorderFactorycreateTitledBorder (etched, "Border types"); buttonpanelsetborder(titled); getcontentpane()add(buttonpanel, "South"); setdemopanel(); settitle("bordertest"); setsize(600, 200); 35

addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); public void addradiobutton(jpanel buttonpanel, ButtonGroup g, String buttonname, boolean v) { JRadioButton button = new JRadioButton(buttonName, v); buttonaddactionlistener(this); gadd(button); buttonpaneladd(button); buttonsetactioncommand(buttonname); public void actionperformed(actionevent evt) { setdemopanel(); public void setdemopanel() { JPanel panel = new JPanel(); Border border = null; String command = groupgetselection() getactioncommand(); if (commandequals("lowered bevel")) border = BorderFactorycreateLoweredBevelBorder(); else if (commandequals("raised bevel")) border = BorderFactorycreateRaisedBevelBorder(); else if (commandequals("etched")) border = BorderFactorycreateEtchedBorder(); else if (commandequals("line")) border = BorderFactorycreateLineBorder(Colorblue); else if (commandequals("matte")) border = BorderFactorycreateMatteBorder(10, 10, 10, 10, Colorblue); else if (commandequals("empty")) border = BorderFactorycreateEmptyBorder(); panelsetborder(border); getcontentpane()add(panel, "Center"); validate(); private JPanel panel; private ButtonGroup group; public class BorderTest { public static void main(string[] args) { JFrame frame = new BorderFrame(); frameshow(); 36

API) javaswingborderfactory static Border createlineborder(color color) static Border createlineborder(color color, int thickness) static MatteBorder creatematteborder(int top, int left, int bottom, int right, Color color) static MatteBorder creatematteborder(int top, int left, int bottom, int right, Icon tileicon) border static Border createemptyborder ( ) static Border createemptyborder (int top, int left, int bottom, int right) static Border createetchedborder ( ) static Border createetchedborder (Color highlight, Color shadow) 3 highlight, shadow 3 static Border createbevelborder ( ) static Border createbevelborder (int type, Color highlight, Color shadow) static Border createlowerdbevelborder ( ) static Border createraisedbevelborder ( ) : type BevelBorderLOWERED, BevelBorderRAISED highlight, shadow 3 static TiltedBorder CreateTitledBordeer (String title) static TiltedBorder CreateTitledBordeer (Border border) static TiltedBorder CreateTitledBordeer (Border border, String title) static TiltedBorder CreateTitledBordeer (Border border, String title, int justification, int position) static TiltedBorder CreateTitledBordeer (Border border, String title, int justification, int position, Font font) static TiltedBorder CreateTitledBordeer (Border border, int justification, int position, Font font, Color) : title border justification TitleBorderLEFT, TitleBorderRIGHT, TitleBorderCENTER position ABOVE_TOP, TOP, BELOW_TOP, ABOVE_BOTTOM, BOTTOM, BELOW_BOTTOM font color 37

static CompoundBorder createcompoundborder(border outsideborder, Border insideborder) API) javaxswingbordersoftbevelborder SoftBevelBorder(int type) SoftBevelBorder(int type, Color highlight, Color shadow) bevel : type BevelBorderLOWERED, BevelBorderRAISED color, shadow 3D API) javaxswingjcomponent void setborder(border border), (machinery) JList JList 9-17, quick, quickly, brown, hungry, wild, static, final, private JList String[] words = { quickly, brown, hungry, wild, ; JList wordlist = new JList(words); 9-17 (anonymous) JList wordlist = new JList (new String[ ]{ quickly, brown, hungry, wild, ); 38

JScrollPane scrollpane = new JScrollPane(wordList); 8 setvisiblerowcount wordlistsetvisiblerowcount(10); // 10 CTRL SHIFT setselectionmode wordlistsetselectionmode (ListSelectionModelSINGLE_SELECTION); // wordlistsetselectionmode (ListSelectionModelSINGLE_INTERVAL_SELECTION); // public void valuechanged(listselectionevent evt) (listener) class ListFrame extends JFrame implements ListSelectionListener { public ListFrame() { JList wordlist = new JList(words); wordlistaddlistselectionlistener(this); public void valuechanged(listselectionevent evt) { 2 (transitional) 39

evtisadjusting( ) isadjusting final true isadjusting false (transitional) isadjusting false (feedback) ------------- ; (CTRL+ ) isadjusting true isadjusting ------------------ getselectedvalues -------------- VB : getselectedvalues VB List property --------------- (cast) JList source = (JList)evtgetSource(); Object[] values = sourcegetselectedvalues(); for (int i = 0; i < valueslength; i++); (String)values[I] --------------- : Object [] getselectedvalues String[ ] int length = valueslength; String[ ] words = new String(length); SystemarrayCopy(values, 0, words, 0, length); ----------------- getselectedvalue ( ) String selection = (String)sourcegetSelectedValue ( ); -------------------- : 40

public void mouseclicked(mouseevent evt) { if (evtgetclickcount ( ) == 2) { JList source = (JList)evtgetSource(); Object[ ] selection = sourcegetselectedvalues( ); doaction(selection); 9-8 valuechanged 9-8:ListTestjava import javaawt*; import javaawtevent*; import javaxswing*; import javaxswingevent*; class ListFrame extends JFrame implements ListSelectionListener { public ListFrame() { settitle("listtest"); setsize(400,300); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); String[] words = { "quick","brown","hungry","wild","silent", "huge","private","abstract","static","final" ; JList wordlist = new JList(words); JScrollPane scrollpane = new JScrollPane(wordList); JPanel p = new JPanel(); padd(scrollpane); wordlistaddlistselectionlistener(this); getcontentpane()add(p, "South"); panel = new ListTestPanel(); getcontentpane()add(panel, "Center"); public void valuechanged(listselectionevent evt) { JList source = (JList)evtgetSource(); Object[] values = sourcegetselectedvalues(); String text = ""; for (int i = 0; i < valueslength; i++) { String word = (String)values[i]; 41

text += word + " "; panelsetattribute(text); private ListTestPanel panel; class ListTestPanel extends JPanel { public ListTestPanel() { setattribute(""); public void setattribute(string w) { text = "The " + w + "fox jumps over the lazy dog"; repaint(); public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawstring(text, 0, 50); private String text; public class ListTest { public static void main(string[] args) { JFrame frame = new ListFrame(); frameshow(); API) javaxswingjlist JList(Object[] items) void setvisiblerowcount(int c) void setvisiblerowcount (int c) : mode SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, MULTIPLE_INTERVAL_SELECTION void addlistselectionlistener(listselectionlistener listener) Object [] getselectedvalue( ) Object getselectedvalue( ) null 42

API) javaxswingeventlistselectionlistener void valuechanged(listselectionevent e) (list model) (collection) JList? JList - - ( ) ( ) JList ListModel public interface ListModel { public int getsize(); public Object getelementat(int n); pubic void addlistdatalistener(listdatalistener 1); pubic void removelistdatalistener(listdatalistener 1); JList JList list data listener? JList (vector)? getelementat 3 9-18: 43

26*26*26=17576 3 AbstractListModel getsize getelementat class WordListModel extends AbstractListModel { public WordListModel(int n) { length = n; public int getsize() { return (int)mathpow(26, length); public Object getelementat(int n) { n (technical) 9-8 JList wordlist = new JList(new WordListModel(3)); wordlistsetselectionmode(listselectionmodelsingle_selection); JScrollPane scrollpane = new JScrollPane(wordList); wordlistsetfixedcellwidth(50); wordlistsetfixedcellheight(15); 9-9 (entity) 9-9: LonglistTestjava import javaawt*; import javaawtevent*; import javaxswing*; import javaxswingevent*; class WordListModel extends AbstractListModel { public WordListModel(int n) { length = n; public int getsize() 44

{ return (int)mathpow(last - FIRST + 1, length); public Object getelementat(int n) { String r = ""; for (int i = 0; i < length; i++) { char c = (char)(first + n % (LAST - FIRST + 1)); r = c + r; n = n / (LAST - FIRST + 1); return r; private int length; public static final char FIRST = 'a'; public static final char LAST = 'z'; class LongListFrame extends JFrame implements ListSelectionListener { public LongListFrame() { settitle("longlisttest"); setsize(400, 300); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); JList wordlist = new JList(new WordListModel(3)); wordlistsetselectionmode (ListSelectionModelSINGLE_SELECTION); wordlistsetfixedcellwidth(50); wordlistsetfixedcellheight(15); JScrollPane scrollpane = new JScrollPane(wordList); JPanel p = new JPanel(); padd(scrollpane); wordlistaddlistselectionlistener(this); getcontentpane()add(p, "South"); panel = new LongListPanel(); getcontentpane()add(panel, "Center"); public void valuechanged(listselectionevent evt) { JList source = (JList)evtgetSource(); String word = (String)sourcegetSelectedValue(); panelsetjumper(word); private LongListPanel panel; 45

class LongListPanel extends JPanel { public LongListPanel() { setjumper("fox"); public void setjumper(string w) { text = "The quick brown " + w + " jumps over the lazy dog"; repaint(); public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawstring(text, 0, 50); private String text; public class LongListTest { public static void main(string[] args) { JFrame frame = new LongListFrame(); frameshow(); API) javaxswingjlist JList(ListModdel, datamodel) void setfixedcellwidth(int width) 0 1 void setfixedcellheight(int height) 0 1 API) int getsize( ) Object getelementat(int index) model ListModel model = listgetmodel ( ); ListModel 46

JList Vector values = new Vector ( ); valuesaddelement( quick ); valuesaddelement( brown ); JList list = new JList(values); (vector) DefaultListModel DefalutListModel model = new DefaultListModel ( ); modeladdelement( quick ); modeladdelement( brown ); JList list = new JList(values); model modelremoveelement( quick ); modeladdelement( slow ); DefaultModel Vector ( add remove DefaultListModel ) AbstractListModel ------------- : JList DefaultListModel Vector JLIst public JList(final Vector listdata) { this (new AbstractListModel() { public int getsize( ) { return listdatasize(); public Object getelementat(int i) { return listdataelementat(i); ); ( final (vector) listdata listdata ) 47

API) javaxswingjlist listmodel getmodel ( ) API) javaxswingdefaultlistmodel void addelement(object obj) boolean removeelement (Object obj) (occurence) true false -Icon - (drawing) JList (list cell renderer) JList interface ListCellRenderer { Component getlistcellrenderercomponent(jlist list, Object value, int index, boolean isselected, boolean cellhasfocus); Component getpreferredsize 2 class MyCellRenderer implements ListCellRenderer { public Component getlistcellrenderercomponent (final JList list, final Object value,final int index, final boolean isselected, final boolean cellhasfocus) { return new JPanel() { public void paintcomponent(graphics g) {// public Dimension getpreferredsize() {// ; 48

9-10 paintcomponent JList look and feel JList getforeground /getbackground getselectionforeground/getselectionbackground 7 getpreferredsize 9-19 class FontCellRenderer implements ListCellRenderer { public Component getlistcellrenderercomponent (final JList list, final Object value, final int index, final boolean isselected, final boolean cellhasfocus) { return new JPanel() { public void paintcomponent(graphics g) { Font font = (Font)value; String text = fontgetfamily(); FontMetrics fm = ggetfontmetrics(font); gsetcolor(isselected? listgetselectionbackground() : listgetbackground()); gfillrect(0, 0, getwidth(), getheight()); gsetcolor(isselected? listgetselectionforeground() : listgetforeground()); gsetfont(font); gdrawstring(text, 0, fmgetascent()); public Dimension getpreferredsize() { Font font = (Font)value; String text = fontgetfamily(); Graphics g = getgraphics(); FontMetrics fm = ggetfontmetrics(font); return new Dimension(fmstringWidth(text), fmgetheight()); ; setcellrenderer fontlistsetcellrenderer(new FontCellRenderer()); (custom render) JLabel 49

class FontCellRenderer implements ListCellRenderer { public Component getlistcellrenderercomponent (JList list, Object value, int index, boolean isselected, boolean cellhasfocus) { JLabel label new JLabel( ); Font font = (Font)value; labelsettext = (fontgetfamily()); labelsetfont(font); labelsetopaque(true); labelsetbackground(isselected? listgetselectionbackground() : listgetbackground()); labelsetforeground(isselected? listgetselectionforeground() : listgetforeground()); return label; paintcomponent getpreferredsize JLabel,, FontCellRendere JLabel getlistcellrendercomponent this class FontCellRenderer implements ListCellRenderer { public Component getlistcellrenderercomponent (JList list, Object value, int index, boolean isselected, boolean cellhasfocus); { JLabel label new JLabel( ); Font font = (Font)value; settext = (fontgetfamily()); setfont(font); setopaque(true); setbackground(isselected? listgetselectionbackground() : listgetbackground()); setforeground(isselected? listgetselectionforeground() : listgetforeground()); return this; - JLabel- 9-10:ListRenderingTestjava 50

import javautil*; import javaawt*; import javaawtevent*; import javaxswing*; import javaxswingevent*; class FontCellRenderer implements ListCellRenderer { public Component getlistcellrenderercomponent (final JList list, final Object value, final int index, final boolean isselected, final boolean cellhasfocus) { return new JPanel() { public void paintcomponent(graphics g) { Font font = (Font)value; String text = fontgetfamily(); FontMetrics fm = ggetfontmetrics(font); gsetcolor(isselected? listgetselectionbackground() : listgetbackground()); gfillrect(0, 0, getwidth(), getheight()); gsetcolor(isselected? listgetselectionforeground() : listgetforeground()); gsetfont(font); gdrawstring(text, 0, fmgetascent()); public Dimension getpreferredsize() { Font font = (Font)value; String text = fontgetfamily(); Graphics g = getgraphics(); FontMetrics fm = ggetfontmetrics(font); return new Dimension(fmstringWidth(text), fmgetheight()); ; class ListRenderingFrame extends JFrame implements ListSelectionListener { public ListRenderingFrame() { settitle("listrenderingtest"); setsize(400, 300); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); Vector fonts = new Vector(); fontsadd(new Font("Serif", FontPLAIN, 12)); fontsadd(new Font("SansSerif", FontPLAIN, 12)); 51

fontsadd(new Font("Monospaced", FontPLAIN, 12)); fontsadd(new Font("Dialog", FontPLAIN, 12)); fontsadd(new Font("DialogInput", FontPLAIN, 12)); JList fontlist = new JList(fonts); fontlistsetselectionmode (ListSelectionModelSINGLE_SELECTION); fontlistsetcellrenderer(new FontCellRenderer()); JScrollPane scrollpane = new JScrollPane(fontList); JPanel p = new JPanel(); padd(scrollpane); fontlistaddlistselectionlistener(this); getcontentpane()add(p, "South"); panel = new ListRenderingPanel(); getcontentpane()add(panel, "Center"); public void valuechanged(listselectionevent evt) { JList source = (JList)evtgetSource(); Font font = (Font)sourcegetSelectedValue(); panelsetfont(font); private ListRenderingPanel panel; class ListRenderingPanel extends JPanel { public ListRenderingPanel() { setfont(new Font("Serif", FontPLAIN, 12)); public void setfont(font f) { currentfont = f; repaint(); public void paintcomponent(graphics g) { superpaintcomponent(g); gsetfont(currentfont); gdrawstring ("The quick brown fox jumps over the lazy dog", 0, 50); private Font currentfont; public class ListRenderingTest { public static void main(string[] args) { JFrame frame = new ListRenderingFrame(); frameshow(); 52

API) javaxswingjlist Color getbackground ( ) Color getselectionbackground ( ) void setcellrender(listcellrender cellrenderer) API) javaxswinglistcellrenderer Component getlist (JList list, Object item, int index, boolean isselected, boolean HasFocus) paint cell getpreferedsize : list item isselected true hasfocus true 9-20 (editable) (combo box) seteditable JComboBox getselecteditem (Serif, SansSerif, Monospaced, etc ) additem additem style = new JComboBox(); styleseteditable(true); styleadditem("serif"); styleadditem("sansserif"); insertitemat 53

styleinsetitemat( Monospaced, 0) removeitem removeitemat styleremoveitem( Monospaced ) styleremoveitemat(0) RemoveAllItem getactioncommand getselecteditem getsource public void actionperformed(actionevent evt) { JComboBox source = (JComboBox)evtgetSource(); String item = (String)sourcegetSelectedItem(); panelsetstyle(item); 9-11 import javaawt*; import javaawtevent*; import javaxswing*; class ComboBoxFrame extends JFrame implements ActionListener { public ComboBoxFrame() { settitle("comboboxtest"); setsize(300,200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); style = new JComboBox(); styleseteditable(true); styleadditem("serif"); styleadditem("sansserif"); styleadditem("monospaced"); styleadditem("dialog"); styleadditem("dialoginput"); styleaddactionlistener(this); JPanel p = new JPanel(); padd(style); getcontentpane()add(p, "South"); panel = new ComboBoxTestPanel(); getcontentpane()add(panel, "Center"); public void actionperformed(actionevent evt) 54

{ JComboBox source = (JComboBox)evtgetSource(); String item = (String)sourcegetSelectedItem(); panelsetstyle(item); private ComboBoxTestPanel panel; private JComboBox style; class ComboBoxTestPanel extends JPanel { public ComboBoxTestPanel() { setstyle("serif"); public void setstyle(string s) { setfont(new Font(s, FontPLAIN, 12)); repaint(); public void paintcomponent(graphics g) { superpaintcomponent(g); gdrawstring ("The quick brown fox jumps over the lazy dog", 0, 50); public class ComboBoxTest { public static void main(string[] args) { JFrame frame = new ComboBoxFrame(); frameshow(); API) javaxswingjcombobox void seteditable(boolean b) : b true, false void additem(object item) void insertitemat(object item, int index) void removeitem(object item) void removeitemat(int index) void removeallitems( ) 55

Object getselecteditem( ) : (AdjustableHORIZONTAL AdjustableVERTICAL) setorientation : getvalue setvalue : 0 100 setminimum setmaximum (visible area): ( 9-21) 0 setvisibleamount :, 1 setlineincrement (block increment):, (block increment) 10 setlineincrement setpageincrement (AdjustableHORIZON, AdjustableVERTICAL), (visible amount) SetValues SetValues red, green, blue ( 9-22) 2 red = new JScrollBar(Adjustable, HORIZONTAL) redsetvalues(0, 0, 0, 255) red = new JScrollBar(AdjustbleHORIZONTAL, 0, 0, 0, 255) (Adjustment) 5 56

9-2 9-22 9-2 UNIT_INCREMENT UNIT_DECREMENT BLOCK_INCREMENT BLOCK_DECREMENT TRACK evt evtgetadjustmenttype( ) getvalue( ) public void adjustmentvaluechanged(adjustmentevent evt) { redlabelsettext("red " + redgetvalue()); greenlabelsettext("green " + greengetvalue()); bluelabelsettext("blue " + bluegetvalue()); csetbackground(new Color(redgetValue(), greengetvalue(), bluegetvalue())); crepaint(); 9-12 ( grid layout 9-12:ColorSelectjava import javaawt*; import javaawtevent*; import javaxswing*; public class ColorSelect extends JFrame implements AdjustmentListener { public ColorSelect() { settitle("colorselect"); setsize(300, 200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); Container contentpane = getcontentpane(); JPanel p = new JPanel(); psetlayout(new GridLayout(3, 2)); padd(redlabel = new JLabel("Red 0")); padd(red = new JScrollBar(AdjustableHORIZONTAL, 57

0, 0, 0, 255)); redsetblockincrement(16); redaddadjustmentlistener(this); padd(greenlabel = new JLabel("Green 0")); padd(green = new JScrollBar(AdjustableHORIZONTAL, 0, 0, 0, 255)); greensetblockincrement(16); greenaddadjustmentlistener(this); padd(bluelabel = new JLabel("Blue 0")); padd(blue = new JScrollBar(AdjustableHORIZONTAL, 0, 0, 0, 255)); bluesetblockincrement(16); blueaddadjustmentlistener(this); contentpaneadd(p, "South"); colorpanel = new JPanel(); colorpanelsetbackground(new Color(0, 0, 0)); contentpaneadd(colorpanel, "Center"); public void adjustmentvaluechanged(adjustmentevent evt) { redlabelsettext("red " + redgetvalue()); greenlabelsettext("green " + greengetvalue()); bluelabelsettext("blue " + bluegetvalue()); colorpanelsetbackground(new Color(redgetValue(), greengetvalue(), bluegetvalue())); colorpanelrepaint(); public static void main(string[] args) { Frame f = new ColorSelect(); fshow(); private JLabel redlabel; private JLabel greenlabel; private JLabel bluelabel; private JScrollBar red; private JScrollBar green; private JScrollBar blue; private JPanel colorpanel; API) javaxswingscrollbar JScrollbar(int orientation) : orientation HORIZONTAL VERTICAL 58

JScrollbar(int orientation, int value, int visible, int minimum, int maximum) : orientation HORIZONTAL VERTICAL value visible 0 minimum maximum void setvalue(int Value) value, void setvalues(int value, int visible, int minimum, int maximum) value visible 0 minimum maximum void setminimum(int value) : value void setmaximum(int value) : value void setvisibleamount(int value) : value (visible setting) void setblockincrement(int i) void setunitincrement(int i) int getvalue( ) API) javaawteventadjustmentlistener void adjustmentvaluechanged(adjustmentevent e) (Scroll Panes) 59

(offset) (offset) JScrollPane JScrollPane JScrollPane sp = new JScrollPane(viewdComponent); // JScrollPane sp = new JScrollPane(viewedComponent, ScrollPaneConstantsVERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstantsHORIZON_SCROLLBAR_NEVER, ); ScrollPaneConstantsHORIZON_SCROLLBAR_AS_NEEDED ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED contenpaneadd(sp, Center ) public MyComponent( ) { setpreferredsize(new Dimension(MAX_XWIDTH, MAX_YHEIGHT)); vewport JViewport vp = spgetviewport( ); vpsetviewsize(new Dimension(MAX_XWIDTH, MAX_YHEIGHT)); viewport viewport ( 60

9-23) 9-12 600*400 300*200 MousePanel MousePanel setpreferredsize MousePanel JScrollPane 9-23 (header) 4 9-23 ruler RulerPanel paintcomponent 9-24 setrowheaderview setcolumnheaderview ( ) RulerPanel horizrulerpanel = new RulerPanel (SwingConstantsHORIZONTAL, viewedcomponentgetpreferredsize()width, 25, 100, 100, 10); spsetcolumnheaderview(horizrulerpanel); setcorner ( SwingConstantsNORTH_WEST Swing JScrollPaneUPPER_RIGHT_CORNER ) 4 spsetcorner(jscrollpaneupper_right_corner, new label(new ImageIcon( blue-ballgif ))); PGUP/PGDN, CTRL+PGUP/CTRL+PGDN 8 JComponent registerkeyboardaction Action ScrollAction,, ( ), (-1, 61

+1, ) actionperformed JScrollBar setvaule class ScrollAction extends AbstractAction { public void actionperformed(actionevent evt) { JScrollBar scrollbar; if (orientation == JScrollBarHORIZONTAL) scrollbar = scrollpanegethorizontalscrollbar(); else scrollbar = scrollpanegetverticalscrollbar(); if (scrollbar == null!scrollbarisvisible()) return; int increment; if (type == UNIT) increment = scrollbargetunitincrement(); else increment = scrollbargetblockincrement(); scrollbarsetvalue(scrollbargetvalue() + increment * direction); ScrollAction spregisterkeyboardaction( new ScrollAction(p, orient, t, dir), KeyStrokegetKeyStroke(key, modifier, false), JComponentWHEN_IN_FOCUSED_WINDOW); register ScrollAction 9-13 9-13: ScrollPaneTestjava import javaawt*; import javaawtevent*; import javaxswing*; class MousePanel extends JPanel // unchanged except for setpreferredsize implements MouseMotionListener { public MousePanel() { addmouselistener(new MouseAdapter() { public void mousepressed(mouseevent evt) { int x = evtgetx(); int y = evtgety(); current = find(x, y); if (current < 0) // not inside a square add(x, y); public void mouseclicked(mouseevent evt) { int x = evtgetx(); 62

int y = evtgety(); if (evtgetclickcount() >= 2) { remove(current); ); addmousemotionlistener(this); setpreferredsize(new Dimension(MAX_XWIDTH, MAX_YHEIGHT)); public void paintcomponent(graphics g) { superpaintcomponent(g); for (int i = 0; i < nsquares; i++) draw(g, i); public int find(int x, int y) { for (int i = 0; i < nsquares; i++) if (squares[i]x - SQUARELENGTH / 2 <= x && x <= squares[i]x + SQUARELENGTH / 2 && squares[i]y - SQUARELENGTH / 2 <= y && y <= squares[i]y + SQUARELENGTH / 2) return i; return -1; public void draw(graphics g, int i) { gdrawrect(squares[i]x - SQUARELENGTH / 2, squares[i]y - SQUARELENGTH / 2, SQUARELENGTH, SQUARELENGTH); public void add(int x, int y) { if (nsquares < MAXNSQUARES) { squares[nsquares] = new Point(x, y); current = nsquares; nsquares++; repaint(); public void remove(int n) { if (n < 0 n >= nsquares) return; nsquares--; squares[n] = squares[nsquares]; if (current == n) current = -1; repaint(); public void mousemoved(mouseevent evt) { int x = evtgetx(); 63

int y = evtgety(); if (find(x, y) >= 0) setcursor(cursorgetpredefinedcursor (CursorCROSSHAIR_CURSOR)); else setcursor(cursorgetdefaultcursor()); public void mousedragged(mouseevent evt) { int x = evtgetx(); int y = evtgety(); if (current >= 0) { Graphics g = getgraphics(); gsetxormode(getbackground()); draw(g, current); squares[current]x = x; squares[current]y = y; draw(g, current); gdispose(); private static final int MAX_XWIDTH = 600; private static final int MAX_YHEIGHT = 400; private static final int SQUARELENGTH = 10; private static final int MAXNSQUARES = 100; private Point[] squares = new Point[MAXNSQUARES]; private int nsquares = 0; private int current = -1; class ScrollPaneFrame extends JFrame { public ScrollPaneFrame() { settitle("scrollpanetest"); setsize(300, 200); addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { Systemexit(0); ); Container contentpane = getcontentpane(); Component viewedcomponent = new MousePanel(); JScrollPane sp = new JScrollPane(viewedComponent); RulerPanel horizrulerpanel = new RulerPanel (SwingConstantsHORIZONTAL, viewedcomponentgetpreferredsize()width, 25, 100, 100, 10); spsetcolumnheaderview(horizrulerpanel); RulerPanel vertrulerpanel = new RulerPanel 64

(SwingConstantsVERTICAL, 25, viewedcomponentgetpreferredsize()height, 100, 100, 10); spsetrowheaderview(vertrulerpanel); contentpaneadd(sp, "Center"); ScrollActionregister(sp, JScrollBarHORIZONTAL, ScrollActionUNIT, -1, KeyEventVK_LEFT, 0); ScrollActionregister(sp, JScrollBarHORIZONTAL, ScrollActionUNIT, 1, KeyEventVK_RIGHT, 0); ScrollActionregister(sp, JScrollBarVERTICAL, ScrollActionUNIT, -1, KeyEventVK_UP, 0); ScrollActionregister(sp, JScrollBarVERTICAL, ScrollActionUNIT, 1, KeyEventVK_DOWN, 0); ScrollActionregister(sp, JScrollBarHORIZONTAL, ScrollActionBLOCK, -1, KeyEventVK_PAGE_UP, InputEventCTRL_MASK); ScrollActionregister(sp, JScrollBarHORIZONTAL, ScrollActionBLOCK, 1, KeyEventVK_PAGE_DOWN, InputEventCTRL_MASK); ScrollActionregister(sp, JScrollBarVERTICAL, ScrollActionBLOCK, -1, KeyEventVK_PAGE_UP, 0); ScrollActionregister(sp, JScrollBarVERTICAL, ScrollActionBLOCK, 1, KeyEventVK_PAGE_DOWN, 0); public class ScrollPaneTest { public static void main(string[] args) { JFrame frame = new ScrollPaneFrame(); frameshow(); class ScrollAction extends AbstractAction { public ScrollAction(JScrollPane p, int orient, int t, int dir) { scrollpane = p; orientation = orient; type = t; direction = dir; public static void register(jscrollpane p, int orient, int t, int dir, int key, int modifier) { pregisterkeyboardaction( new ScrollAction(p, orient, t, dir), KeyStrokegetKeyStroke(key, modifier, false), JComponentWHEN_IN_FOCUSED_WINDOW); public void actionperformed(actionevent evt) { JScrollBar scrollbar; if (orientation == JScrollBarHORIZONTAL) 65