Java 2: Programs with a graphical user interface

3 downloads 181 Views 7MB Size Report
Components are placed in a window using a layout manager, which is an object that determines the component's size and po


POUL KLAUSEN

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE SOFTWARE DEVELOPMENT

Download free eBooks at bookboon.com 2

Java 2: Programs with a graphical user interface: Software Development 1st edition © 2017 Poul Klausen & bookboon.com ISBN 978-87-403-1643-8 Peer review by Ove Thomsen, EA Dania

Download free eBooks at bookboon.com 3

Deloitte & Touche LLP and affiliated entities.

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Contents

CONTENTS Foreword

6

1 Introduction

8

2

Hello Swing

10



Exercise 1

17



Exercise 2

22

3

Fonts and colors

29



Exercise 3

33

4

Dialog boxes

34



Exercise 4

5

More components



Exercise 5

360° thinking

360° thinking

44

.

.

48 62

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download

Click on the ad to read more

4

Dis

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Contents

6 Layout and the component’s size

65

6.1

65

The component’s size

6.2 Borderlayout

68

6.3 Flowlayout

70

6.4 Gridlayout

72



Exercise 6

74

6.5 Gridbaglayout

76



88

Exercise 7

6.6 Boxlayout

89



Exercise 8

97

6.7

Null layout

98



Problem 1

100

6.8 MVC

101

7 Paedit

103

7.1

The model

103

7.2

The view

106

8

Final example

120

8.1

the program’s classes

121

8.2 Programming

123

9

A last example

128

9.1

Creating the library

128

9.2

The test program

134

Download free eBooks at bookboon.com 5

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Contents

FOREWORD This book is the second in a series of books on software development. The programming language is Java, and the language and its syntax and semantics fills obviously much, but the books have also largely focus on the process and how to develop good and robust applications. The subject of the current book is an introduction to development of programs with a graphical user interface and thus also an introduction to Swing. Programs with a graphical user interface is also called GUI programs and Swing is the Java’s API for the development of GUI programs. Swing is extensive and is first treated in detail in the book Java 9, and the goal of the current book is to present as much of Swing, that the reader will be able to write small applications that have practical interest. The book assumes a basic knowledge of Java corresponding to the book Java 1 of this series, but since the objective is that the reader soon should be introduced to the development of programs with a graphical user interface the book bypasses many object-oriented concepts, which naturally are part of a book about GUI programming. These concepts are discussed in detail in the next book in the series. As the title says this series of books deals with software development, and the goal is to teach the reader how to develop applications in Java. It can be learned by reading about the subject and by studying complete sample programs, but most importantly by yourself to do it and write your own programs from scratch. Therefore, an important part of the books is exercises and problems, where the reader has to write programs that correspond to the substance being treated in the books. All books in the series is built around the same skeleton and will consist of text and examples and exercises and problems that are placed in the text where they naturally belongs. The difference between exercises and problems is that the exercises largely deals with repetitions of the substance that is presented in the text, and furthermore it is relatively accurately described what to do. Problems are in turn more loosely described, and are typically a little bigger and there is rarely any clear best solution. These are books to be read from start to finish, but the many code examples, including exercises and problems plays a central role, and it is important that the reader predict in detail studying the code to the many examples and also solves the exercises and problems or possibly just studying the recommended solutions. All books ends with one or two larger sample programs, which focus primarily is on process and an explanation of how the program is written. On the other hand appears the code only to a limited extent – if at all – and the reader should instead study the finished program code perhaps while testing the program. In addition to show the development of programs that are larger than the examples, which otherwise is presented, the aim of the concluding examples also is to show program examples from varying fields of application.

Download free eBooks at bookboon.com 6

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Contents

Most books also ends with an appendix dealing with a subject that would not be treated in the books. It may be issues on the installation of software or other topics in computer technology, which are not about software development, but where it is necessary to have an introductory knowledge. If the reader already is familiar with the subject, the current appendix can be skipped. The programming language is, as mentioned Java, and besides the books use the following products: -- NetBeans as IDE for application development -- MySQL to the extent there is a need for a database server (from the book Java 6 onwards) -- GlassFish as a web server and application server (from the book Java 11 onwards) It is products that are free of charge and free to install, and there is even talk about products, where the installation is progressing all by itself and without major efforts and challenges. In addition, there are on the web detailed installation instructions for all the three products. The products are available on Windows and Linux, and it therefore plays no special role if you use Linux or Windows. All sample programs are developed and tested on machines running Linux. In fact, it plays no major role, as both Java and other products work in exactly the same way whether the platform is one or the other. Some places will be in the books where you could see that the platform is Linux, and this applies primarily commands that concerning the file system. Otherwise it has no meaning to the reader that the programs are developed on a Linux machine, and they can immediately also run under Windows unless a program refers to the file system where it may be necessary to change the name of a file. Finally a little about what the books are not. It is not “how to write” or for that matter reference manuals in Java, but it is as the title says books on software development. It is my hope that the reader when reading the books and through the many examples can find inspiration for how to write good programs, but also can be used as a source collection with a number of examples of solutions to concrete everyday programming problems that you regularly face as a software developer.

Download free eBooks at bookboon.com 7

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Introduction

1 INTRODUCTION This book is an introduction to writing GUI applications in Java using the Swing API. Far from everything is treated, but conversely sufficient that you after reading the book can write small applications with a graphical user interface. A program with a graphical user interface is a program that runs in a window. Since it is largely based on the principles of object-oriented programming, the topic should be examined only after the next book in the series of this books, and the following will also use a lot about classes and interfaces that are first mentioned there. When I still have chosen to address the subject now, it is because I want to be able to write applications that are more interesting and better match the programs that you meet in everyday life, than what is possible purely as commands or console applications. To write a program with a graphical user interface you must work on basis of a wide range of finished classes, for example classes that creates and opens a window, classes representing a button, classes for an input field, etc. These are very many classes, and they are assembled in an API called Swing. In fact, Swing classes are based on an older API called AWT, so there are two APIs that you have to learn about, and each of these has several packages of classes. In the following I will call programs with a graphical user interface for GUI programs where GUI stands for Graphical User Interface, and I will start to make it clear that you can not learn to write GUI applications by learning all the many classes and their methods. Instead, you must learn some basic principles for the development of these kinds of programs, and once you have learned it, it’s all not so difficult. You quickly get an idea of what it takes, and the question is what it’s all are called and what you actually have to write. Here, however, there is only one way and that is to turn up the help, which fortunately is online available and there is also a variety of other sources on the Internet that provides advice on how to solve specific problems. It is very different to writing GUI applications than console applications, and immediately it seems as if you have to write a lot and you also has to (at least as I will introduce Swing), but you will also quickly find that there is a lot of repetition and it is the same you have to write every time. Therefore, to reducing the task after you’ve written the first programs, and to reduce the work, you can create your own class library with frequently used methods. You will find an example of that in the book’s appendix.

Download free eBooks at bookboon.com 8

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Introduction

A GUI application will typically consist of several or many classes, but starting you can think of each window as a class. In addition, the data that a program must treat, are usually also be defined using classes, and possibly there will also be classes that implement the logic that must process the application’s data. It is primarily in this context, that I am missing something of the theory of classes and interfaces, as first is explained in the third book on object-oriented programming. The following will therefore to some extent deal with objectoriented concepts, but so that I postpone all details for later. The focus is on how to write a GUI application using Swing, and I will mainly use the most basic components, while more complex components is delayed. The goal is that after reading this book and in detail studied the related examples and solved the related exercises and problems you should be able to write less GUI programs for practical use.

Download free eBooks at bookboon.com 9

JAVA PROGRAMS WITH JAVA 2: 2: PROGRAMS WITH AA GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello swIng Hello Swing

2 HELLO HELLOSWING SWING 2 starta alittle, little,like likeI Idid didininthe thefirst firstbook booktotowrite writea asimple simpleprogram, program,but butthis thistime timea a I’llI’llstart programwhich whichopens opensa awindow windowwhere whereyou youcan canenter entera aname. name.When Whenyou youthen thenclick clickthe the program Addbutton, button,the theentered enteredname nameis isadded addedtotoa alistlistbox, box,and andyou youcan canenter entera anew newname. name.AtAt Add thebottom bottomofofthe thewindow, window,there thereis isalso alsoa abutton, button,allowing allowingyou youtotodelete deletethe thecontents contentsofof the thelistlistbox. box. the

additionyou youcan, can,what whatyou youelse elsecan canwith witha awindow. window.You Youcan canmove movethe thewindow, window,and and InInaddition youcan canchange changethe thewindow windowsize. size.Right-clicking Right-clickingononthe thetitle titlebar, bar,you youget getthe theusual usualmenu menu you anddouble-click double-clickatatthe thetitle titlebar, bar,the thewindow windowmaximizes. maximizes.If Ifforfora amoment momentyou youthink thinkabout about and actuallya alotlotthat thatthe theprogram programcan cando. do. it,it,it’sit’sactually Forwriting writingthe theprogram programI Ihave haveininNetBeans NetBeanscreated createda acommon commonproject projectininthe thesame sameway way For thefirst firstbook, book,and andI Ihave havecalled calledthe theproject projectHelloSwing. HelloSwing.Next, Next,I Iadded addeda aclass classtotothe the asasininthe project,called calledMainWindow, MainWindow,and andit itis isthe thefile fileforforthis thisclass, class,which whichcontains containsallallthe thecode: code: project, package helloswing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainWindow extends JFrame { private JTextField txtName = new JTextField(); private JButton cmdAdd = new JButton("Add"); private JButton cmdClr = new JButton("Clear"); private JList lstNames; private DefaultListModel model = new DefaultListModel();

Download free eBooks at bookboon.com 10 10

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello swIng

public MainWindow() { setTitle("Hello Swing"); setSize(500, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); addListeners(); createWindow(); setVisible(true); } private void createWindow() { add(createLabel(), BorderLayout.NORTH); add(createLabel(), BorderLayout.WEST); add(createLabel(), BorderLayout.EAST); add(createLabel(), BorderLayout.SOUTH); JPanel panel = new JPanel(new BorderLayout()); panel.add(createTop(), BorderLayout.NORTH); panel.add(createBottom(), BorderLayout.SOUTH); panel.add(createCenter()); add(panel); } private JLabel createLabel() { JLabel label = new JLabel(""); label.setPreferredSize(new Dimension(10, 10)); return label; } private JPanel createTop() { JPanel panel = new JPanel(new BorderLayout(10, 10)); JLabel label = new JLabel("Enter a name"); panel.add(label, BorderLayout.WEST); panel.add(cmdAdd, BorderLayout.EAST); panel.add(txtName); return panel; } private JPanel createCenter() { lstNames = new JList(model); JPanel panel = new JPanel(new BorderLayout()); panel.add(createLabel(), BorderLayout.NORTH); panel.add(createLabel(), BorderLayout.SOUTH); panel.add(new JScrollPane(lstNames)); return panel; }

Download free eBooks at bookboon.com 11 11

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

{

}

Hello Swing Hello swIng

private JPanel createBottom() JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); panel.add(cmdClr); return panel;

private void addListeners() { cmdAdd.addActionListener(new AddAction()); cmdClr.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.clear(); } NY026057B TMP PRODUCTION }); 6x4 }

gl/rv/rv/baf

4

12/13/2013

ACCCTR00

PSTANKIE Bookboon Ad Creative

class AddAction implements ActionListener { public void actionPerformed(ActionEvent e) {

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

Download free eBooks at bookboon.com 12 12

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

}

}

Hello Swing Hello swIng

String name = txtName.getText().trim(); if (name.length() > 0) { model.addElement(name); txtName.setText(""); txtName.requestFocus(); }

ItItlooks looksundeniably undeniablylike likemuch much(there (thereare are97 97lines), lines),and andI Iwill willexplain explainbelow belowwhat whatititall all means. Of course one can not know that the code should be written as shown above, but means. Of course one can not know that the code should be written as shown above, but ififyou youlook lookthrough throughthe thecode, code,you youcan canactually actuallyeasily easilyunderstand understandthe themeaning meaningofofmost. most. There Thereare arethree threeimport importstatements, statements,which whichimports importsthree threepackages packageswith withclasses, classes,two twopackages packages from the AWT API and one package from the Swing API. These import statements from the AWT API and one package from the Swing API. These import statementswill willbe be part of any GUI program and in all the classes that define windows. part of any GUI program and in all the classes that define windows. The Theclass classisisnamed namedMainWindow, MainWindow,and andititinherits inheritsthe theclass classJFrame. JFrame.ItItisisaaSwing Swingclass, class,and and this is the class that defines all that is necessary to create a window and offers all the services this is the class that defines all that is necessary to create a window and offers all the services that thatare areneeded neededtotodefine definehow howthe thewindow windowshould shouldbehave. behave. AAwindow windowisisininprinciple principlejust justaasimply simplyrectangular rectangulararea areawithout withoutany anycontent, content,but butititmay may contain components. Each component is defined by a class, and in this case the window contain components. Each component is defined by a class, and in this case the window must mustcontain containan aninput inputfield, field,two twobuttons buttonsand andaalist listbox. box.They Theyare aredefined definedasasinstance instancevariables variables atatthe start of the class. An input field has the type JTextField, a button the type JButton, the start of the class. An input field has the type JTextField, a button the type JButton, and andaalist listbox boxthe thetype typeJList. JList.They Theyare areall allSwing Swingclasses. classes.You Youshould shouldnote notethat thatthe thelist listbox boxisis not notcreated, created,when whenthe thevariables variablesare aredefined, defined,but butthe theother otherthree threecomponents componentsare. are.Finally, Finally,aa last lastinstance instancevariable variableofofthe thetype typeDefaultListModel DefaultListModelisisdefined definedand andisisexplained explainedbelow. below. The Theclass classhas hasaaconstructor constructorthat thatdoes doesthe thefollowing: following: -------------

defines definesthe thetext textininthe thetitle titlebar bar defines the window size, which defines the window size, whichisisthe thesize sizeofofthe thewindow windowhas haswhen whenititopens opens defines that the program should close when the user clicks the cross in the defines that the program should close when the user clicks the cross in thetitle titlebar bar calls a method addListeners() that assigns functionality to the window’s buttons calls a method addListeners() that assigns functionality to the window’s buttons calls callsaamethod methodcreateWindow() createWindow()placing placingthe thecomponents componentsininthe thewindow window define that the window must be displayed on the screen define that the window must be displayed on the screen

Download free eBooks at bookboon.com 13 13

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Hello Swing

The class has a method called createLabel(), which creates an empty label. A label is a component, and has the type JLabel, and it is a component that shows a text. In this case it is a blank text, but the important thing is that it has a size which is defined with setPreferredSize(). Components are placed in a window using a layout manager, which is an object that determines the component’s size and position. A window (that is a JFrame) has by default a BorderLayout. It is a layout manager that divides the window into 5 areas, and each area may contain a component. The five areas are 1. NORTH, and it has always the same width as the window while the height is determined by the height of the component 2. SOUTH, and it has always the same width as the window while the height is determined by the height of the component 3. WEST, the height is the height of the window, except for what is used for NORTH and SOUTH, while the width is determined by the width of the component 4. EAST, the height is the height of the window, except for what is used for NORTH and SOUTH, while the width is determined by the width of the component 5. CENTER, that is the rest of the window If an area is empty – there is not a component in the area – it fills nothing and is collapsed. It is important to note that a BorderLayout can contain only 5 components. If you now considers the method createWindow(), it starts using the method createLabel() to place a component in each of the four areas NORTH, SOUTH, WEST and EAST. The goal is to define a margin of 10 corresponding to the size of the components that are created with the method createLabel(). Next, the method creates a new component of the type JPanel. It is a component which in itself is not visible, but it has a layout manager (in this case a BorderLayout) and can contain other components. The component is called panel, and the last statement in the method createWindow() places the component CENTER in the window. Before it is filled with content using three methods, called respectively createTop(), createCenter() and createBottom().

Download free eBooks at bookboon.com 14

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello swIng

If If II start start with with the the last last one, one, that that creates creates aa JPanel JPanel with with aa FlowLayout FlowLayout manager. manager. It It isis aa layout layout manager, where components are flowing horizontally. In this case, I have indicated that manager, where components are flowing horizontally. In this case, I have indicated that the the components must be aligned to the right edge. After the panel is created, I adds one of the components must be aligned to the right edge. After the panel is created, I adds one of the two two buttons buttons (the (the one one to to delete delete the the list list box). box). The The result result isis that that you you gets gets aa button button located located in in the lower right corner of the window, but because of the two layout managers properties, the lower right corner of the window, but because of the two layout managers properties, the the component component will will follow follow the the window’s window’s bottom bottom and and right right edge, edge, when when the the window window size size isis changed. changed. The The method method createTop() createTop() creates creates aa component component to to the the top, top, aa JPanel JPanel with with aa label label on on the the left, left, aa button on the right and an input box in the center. The three components are placed button on the right and an input box in the center. The three components are placed by by aa BorderLayout, BorderLayout, where where the the input input field field txtName txtName isis placed placed CENTER. CENTER. As As aa CENTER CENTER area area always fills it all, is the result of the layout, that the input field will always fill the part always fills it all, is the result of the layout, that the input field will always fill the part of of the the panel, panel, which which isis not not used used by by the the other other two two components components and and thereby thereby adjust adjust to to the the window width. You should note that the panel is created as follows: window width. You should note that the panel is created as follows: JPanel panel = new JPanel(new BorderLayout(10, 10));

Here Here you you specify specify by by the the parameters parameters for for the the BorderLayout BorderLayout class’s class’s constructor, constructor, how how much much free free space should be between the components. space should be between the components.

The Wake the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

Download free eBooks at bookboon.com 15 15

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

Hello HelloSwing swIng

The Themethod methodcreateCenter() createCenter()creates createsthe thelist listbox. box.When Whenyou youdo dothat thatyou youassign assignthe thelist listbox boxtoto a adata datamodel model––ananobject objectofofthe thetype typeDefaultListModel DefaultListModel––which whichmust mustcontain containthe thedata datathat that the thelist listbox boxshould shoulddisplay. display.The Themethod methodcreates createsa aJPanel JPanelwith witha aBorderLayout, BorderLayout,and andassigns assigns ananempty label NORTH and SOUTH to get some space, respectively at top and bottom. empty label NORTH and SOUTH to get some space, respectively at top and bottom. When Whenthe thelist listbox boxisisplaced placedininthe thepanel, panel,ititisisencapsulated encapsulatedinina aJScrollPane, JScrollPane,which whichallows allows that thatyou youcan canscroll scrollthe thecontent. content. All Allthe theforegoing foregoingconcerning concerningonly onlyhow howtotocreate createand anddesign designthe thewindow. window.You Youshould shouldnote note that thatititisisa astable stabledesign designininthe thesense sensethat thatthe thecomponents componentsfollows followsthe thewindow windowsize. size.What What remains remainsisistotoattach attachfunctionality functionalitytotothe thetwo twobuttons. buttons.When Whenthe theuser userclicks clicksa abutton, button,ititraises raises ananevent. event.Specifically, Specifically,this thismeans meansthat thatother otherobjects objectscan canregister registerasaslisteners listenersfor forthis thisevent eventby by specifying a method with a specific signature. This method is called an event handler. When specifying a method with a specific signature. This method is called an event handler. When the thebutton buttonisisclicked, clicked,ititwill willcheck checkwhether whetherthere thereare arelisteners, listeners,and andififso, so,will willititcall callthese these listeners. listeners.This Thissends sendsmessages messagestotothe thelistener listenerobjects objectsthat thattells tellsthat thatthe thebutton buttonisisclicked, clicked, and andthe thelisteners listenerscan cando dosomething. something. Above, Above,there thereisisananinner innerdefined definedclass, class,which whichisissimply simplya aclass classwithin withinanother anotherclass. class.It’s It’s called calledAddAction AddActionand andimplements implementsananinterface interfacecalled calledActionListener. ActionListener.This Thisinterface interfacedefines defines only onlya asingle singlemethod methodcalled calledactionPerformed() actionPerformed()and andisisananexample exampleofofananevent eventhandler. handler.ItIt should shouldbebelinked linkedtotothe theAdd Addbutton, button,asashappens happenswidth widththe themethod methodaddActionListener(). addActionListener(). The Theevent eventhandler handlerretrieves retrievesthe thetext textfrom fromthe theinput inputfield, field,and andififthe thetext textisisnot notempty, empty,the the handler handlerupdates updatesthe themodel modelofofthe thelist listbox boxwith withthe thetext, text,and andthe theresult resultisisthat thatthe theentered entered name nameappears appearsininthe thelist listbox. box.Next, Next,the thecontent contentofofthe theinput inputfield fieldisisdeleted, deleted,and andfinally finally the field is given focus, and the input field is ready to enter the next name. That the the field is given focus, and the input field is ready to enter the next name. That theclass class AddAction AddActionimplements implementsthe theinterface interfaceActionListener ActionListenermeans meansthat thatananobject objectofoftype typeAddAction AddAction can canbebeused usedasasa alistener listenerobject objectofofa abutton. button.ItIthappens happensininthe themethod methodaddListeners() addListeners()with with the thefollowing followingstatement: statement: cmdAdd.addActionListener(new AddAction());

cmdAdd cmdAddisisthe thename nameofofthe thebutton, button,and andthe theclass classJButton JButton(which (whichare areofofthe thebutton’s button’stype) type) have havea amethod methodaddActionListener(), addActionListener(),which whichcan canregister registera alistener listenerobject. object.The Theresult resultisisthat that when whenyou youclick clickthe theAdd Addbutton, button,then thenlistener listenerobject’s object’sactionPerformed() actionPerformed()method methodexecutes. executes.You You should shouldnote notethat thatthis thismethod methodcan canrefer refertotothe theinstance instancevariables variablesininthe theclass classMainWindow. MainWindow. This is possible because AddAction is an inner class. This is possible because AddAction is an inner class. There Theremust mustnow nowbebedone donethe thesame samefor forthe thesecond secondbutton, button,but butthis thistime timethe theevent eventhandler handler isisvery verysimple, simple,since sinceititalone alonemust mustdelete deletethe thecontents contentsofofthe themodel modelfor forthe thelist listbox. box.I Ihave have therefore instead of writing a new listener class added a listener object created on the basis therefore instead of writing a new listener class added a listener object created on the basis ofofanananonymous anonymousclass: class:

Download free eBooks at bookboon.com 1616

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Hello Swing Hello swIng Hello swIng

cmdClr.addActionListener(new ActionListener() { cmdClr.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { model.clear(); } model.clear(); }); } });

At this point you just need to accept the syntax, but cmdClear is the name of a button, and At this point you just need to accept the syntax, but cmdClear is the name of a button, and IAtuse addActionListener() associate a listener That is, as explained above,and an thisitspoint you just need totoaccept the syntax, butobject. cmdClear is the name of a button, I use its addActionListener() to associate a listener object. That is, as explained above, an object that implements the interface ActionListener, and such an is, object can be instantiated I use its addActionListener() to associate a listener object. That as explained above, an object that implements the interface ActionListener, and such an object can be instantiated on the that basisimplements of an anonymous class ActionListener, with a syntax, and as shown above. discuss the object the interface such an objectOne can can be instantiated on the basis of an anonymous class with a syntax, as shown above. One can discuss the pros andbasis consofwith respect to anonymous since they can be difficult to understand on the an anonymous class with classes, a syntax, as shown above. One can discuss the pros and cons with respect to anonymous classes, since they can be difficult to understand and but are very to simple classes –classes, as in this it can quite to excellent. pros read, and cons withthey respect anonymous sincecase they– can be be difficult understand and read, but are they very simple classes – as in this case – it can be quite excellent. and read, but are they very simple classes – as in this case – it can be quite excellent. Now the window is finished, but this is not in itself a program. There must be instantiated Now the window is finished, but this is not in itself a program. There must be instantiated an object whose type is MainWindow, in the main Now the window is finished, but this isand not itinshould itself abe program. Thereprogram: must be instantiated an object whose type is MainWindow, and it should be in the main program: an object whose type is MainWindow, and it should be in the main program: package helloswing;

package helloswing; public class HelloSwing { public class HelloSwing { public static void main(String[] args) { public static void main(String[] args) { new MainWindow(); } new MainWindow(); }} }

Then the program is finished and can be run. As already mentioned, much is being written, Then isisfinished and run. already mentioned, being although it is a very simple but theAs example partlyisis because it is the Thenthe theprogram program finishedprogram, andcan canbebe run. As alreadyexaggerating, mentioned,much much beingwritten, written, although simple but example ititisisthe same to ithappen every time,program, and secondly, parts of theexaggerating, code can bepartly written simpler. although itisisa avery very simple program, butthe the example exaggerating, partlybecause because the same sametotohappen happenevery everytime, time,and andsecondly, secondly,parts partsofofthe thecode codecan canbebewritten writtensimpler. simpler.

EXERCISE 1 EXERCISE 1 EXERCISE In this exercise1you have to make some changes and improvements to the program HelloSwing.

InStart you totomake and totothe HelloSwing. by creating ahave copy and open itchanges in NetBeans. In MainWindow is a method called Inthis thisexercise exercise youhave makesome somechanges andimprovements improvements theprogram program HelloSwing. Start a acopy and MainWindow isisa amethod createLabel(), which is used add itaitin margin outsideInIn the window’s content and tocalled create Startby bycreating creating copy andtoopen open inNetBeans. NetBeans. MainWindow method called createLabel(), which isisused a amargin outside content totocreate space between the components. This can be done in the other way. Remove thisand method. You createLabel(), which usedtotoadd add margin outside thewindow’s window’s content and create space the components. can bebedone ininother way. this You get 6between statements refers This to this method), NetBeans reports anmethod. error. Delete space between the(which components. This can donewhere other way.Remove Remove this method. You get 6 statements (which refers to this method), where NetBeans reports an error. Delete these statements. If yourefers then to runthis themethod), program,where the result is the reports following: get 6 6statements (which NetBeans an error. Delete these these66statements. statements.IfIfyou youthen thenrun runthe theprogram, program,the theresult resultisisthe thefollowing: following:

Download free eBooks at bookboon.com 17 17

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Hello Hello Swing swIng

To To define define margins margins you you need need to to add add an an import import statement: statement: import javax.swing.border.*;

30 FR da EE ys tria

SMS from your computer ...Sync'd with your Android phone & number

l!

Go to

BrowserTexting.com

and start texting from your computer!

...

Download free eBooks at bookboon.com 18 18

BrowserTexting

Click on the ad to read more

JAVA 2: PROGRAMS WITH AA JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello Hello swIng swIng

The The method createWindow() must then be changed the following: Themethod methodcreateWindow() createWindow()must mustthen thenbe bechanged changedtoto tothe thefollowing: following: private private void void createWindow() createWindow() { { JPanel JPanel panel panel = = new new JPanel(new JPanel(new BorderLayout(0, BorderLayout(0, 10)); 10)); panel.setBorder(new EmptyBorder(10, EmptyBorder(10, 10, 10, 10, 10, 10)); 10)); panel.setBorder(new panel.add(createTop(), panel.add(createTop(), BorderLayout.NORTH); BorderLayout.NORTH); panel.add(createBottom(), BorderLayout.SOUTH); BorderLayout.SOUTH); panel.add(createBottom(), panel.add(createCenter()); panel.add(createCenter()); add(panel); add(panel); } }

So Sowould woulditit itall alllook lookright rightagain. again. So would all look right again. You You must then add new button the bottom the window: Youmust mustthen thenadd addaaanew newbutton buttontoto tothe thebottom bottomofof ofthe thewindow: window:

You Youdo dothis thisasas asfollows: follows: You do this follows: 1. 1. create new instance variable button that you can call cmdCount 1.create createaaanew newinstance instancevariable variabletoto toaaabutton buttonthat thatyou youcan cancall callcmdCount cmdCount 2. add the button (a component) to the window in the method 2. add the button (a component) to the window in the method createBottom() 2. add the button (a component) to the window in the methodcreateBottom() createBottom() Now Now the window should have another button. The two buttons the bottom probably Nowthe thewindow windowshould shouldhave haveanother anotherbutton. button.The Thetwo twobuttons buttonsatat atthe thebottom bottomisis isprobably probably not equal in size, but because they are laid out with a FlowLayout, you can define their not equal in size, but because they are laid out with a FlowLayout, you can define their size not equal in size, but because they are laid out with a FlowLayout, you can define theirsize size (in createBottom()) as follows: (in createBottom()) as follows: (in createBottom()) as follows: cmdAnt.setPreferredSize(new cmdAnt.setPreferredSize(new Dimension(80, Dimension(80, 27)); 27));

Assign Assignthe theClear Clearbutton buttonthe thesame samesize. size. Assign the Clear button the same size.

Download free eBooks at bookboon.com 1919 19

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello swIng

What remains is to attach an action for the new button. When the button is clicked, the What remains is to attach an action for the new button. When the button is clicked, the program must open the following message box that shows how many names are entered: program must open the following message box that shows how many names are entered:

Start by adding another inner class that defines a listener object: Start by adding another inner class that defines a listener object: class CountAction implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(MainWindow.this, "You have entered " + model.getSize() + " names", "Message", JOptionPane.INFORMATION_MESSAGE); } }

Here Here isis showMessageDialog() showMessageDialog() aa static static method method in in the the class class JOptionPane, JOptionPane, which which opens opens aa message message box. It has four parameters, wherein only the first two are required. The first tells who box. It has four parameters, wherein only the first two are required. The first tells who owns owns the message box, and the next is the text to be displayed. The third is the text in the the message box, and the next is the text to be displayed. The third is the text in the title title bar, while the remaining is telling the icon the message box will display. bar, while the remaining is telling the icon the message box will display. After After you you have have defined defined this this class, class, you you only only need need in in the the method method addListeners() addListeners() to to make make your your application to listener for events from the button. application to listener for events from the button. You You must must add add one one last last change change to to the the program. program. The The Clear Clear button button deletes deletes the the content content of of the the list box, but without a warning, which in practice can be unlucky. It would be better with list box, but without a warning, which in practice can be unlucky. It would be better with aa warning: warning:

Download free eBooks at bookboon.com 20 20

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello swIng

To add that, you must change the event handler for the Clear button so that its code is To add that, you must change the event handler for the Clear button so that its code is as follows: as follows: if (JOptionPane.showConfirmDialog(MainWindow.this, "Are you sure you want to delete the list?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) model.clear();

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com 21 21

Click on the ad to read more

JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL

HelloSwing swIng Hello

EXERCISE22 EXERCISE Createaanew newNetBeans NetBeansproject, project,that thatyou youcan cancall callCalculator. Calculator.You Youshould shouldwrite writeaaprogram program Create thatopens opensaawindow, window,asasshown shownbelow: below: that

Thewindow windowhas hastwo twoinput inputfields fieldswhere whereyou youmust mustenter enternumbers. numbers.Furthermore, Furthermore,there thereare are The fourbuttons buttons––one onefor foreach eachofofthe thefour fourarithmetical arithmeticaloperations. operations.When Whenyou youclick clickaabutton, button, four theprogram programshould shouldinsert insertaaline lineininthe thelist listbox, box,which whichshows showsthe theresults resultsofofthat thatcalculation. calculation. the thereisisan anerror, error,the theprogram programsimply simplyinserts insertsan anerror errormessage. message.The TheClear Clearbutton buttonshould should IfIfthere workininthe thesame sameway wayasasininthe thefirst firstprogram. program. work Whenthe thewindow windowsize sizeisischanged, changed,all allbuttons buttonsmust mustfollow followthe thewindow’s window’sright rightedge, edge,while while When thetwo twoinput inputboxes boxeswill willuse usethe theremaining remainingspace spaceequally. equally. the clearthat thatthe theprogram programisissimilar similartotothe theHelloSwing, HelloSwing,but butI Iwould wouldsuggest suggestthat thatyou youstart start ItItisisclear fromscratch scratchand andfollow followthe theguidelines guidelinesbelow. below.You Youcan canofofcourse courseuse useHelloSwing HelloSwingtotosee seehow how from theindividual individualstatements statementsshould shouldbe bewritten. written. the Addaanew newclass classnamed namedMainWindow MainWindowtotothe theproject. project.Start Startby bytyping typingthe thefollowing followingcode: code: 1)1)Add package calculator; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainWindow extends JFrame { public MainWindow() {

Download free eBooks at bookboon.com 2222

JAVA 2:2: PROGRAMS WITH AA JAVA 2: PROGRAMS WITH A JAVA PROGRAMS WITH GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello swIng Hello swIng

setTitle("Calculator"); setTitle("Calculator"); setSize(500, 300); 300); setSize(500, setDefaultCloseOperation(EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); setVisible(true); } } }}

You must must then then edit edit the the main main class class to to open open the the window: window: You package calculator; calculator; package public class class RegneMaskine RegneMaskine public {{ public static static void void main(String[] main(String[] args) args) public {{ new MainWindow(); MainWindow(); new }} } }

Test Testthe theprogram. program.This Thisshould shouldopen openaaawindow, window,and anditititisisisinin inaaaway wayaaaminimal minimalGUI GUIprogram, program, Test the program. This should open window, and way minimal GUI program, but butnevertheless neverthelessaaaprogram programwith withaaawindow windowwith withaaatitle titlebar barthat thatcan canbe bemoved movedaround aroundon on but nevertheless program with window with title bar that can be moved around on the thescreen screenand andresized. resized. the screen and resized. 2)2) 2)Add Addinstance instancevariables variablestoto tothe theprogram. program.There Thereisisisaaaneed needfor for999variables: variables: Add instance variables the program. There need for variables: ---- two twoinput inputfields fieldsthat thatyou youshould shouldcall calltxtNum1 txtNum1and andtxtNum2 txtNum2 two input fields that you should call txtNum1 and txtNum2 ---- five fivebuttons buttonswith withthe thenames namescmdAdd, cmdAdd,cmdSub, cmdSub,cmdMul, cmdMul,cmdDiv cmdDivand andcmdClr cmdClr five buttons with the names cmdAdd, cmdSub, cmdMul, cmdDiv and cmdClr ---- aaalist listbox boxwith withthe thename namelstRes lstRes(you (youmust mustnot notcreate createan anobject, object,but butjust justdefine define list box with the name lstRes (you must not create an object, but just define aaavariable) variable) variable) ---- aaamodel modelfor forthe thelist listbox, box,and andthe thename namemust mustbe bemodel model model for the list box, and the name must be model Compile Compilethe theprogram programand andrun runit.it. it.There Thereare areno novisible visibledifferences, differences,and andthis thisisisisjust justtoto toensure ensure Compile the program and run There are no visible differences, and this just ensure that thatyou youdo donot nothave haveany anysyntax syntaxerrors. errors. that you do not have any syntax errors. 3)3) 3)You Youmust mustnext nextadd addaaamethod methodnamed namedcreateCenter(). createCenter().It’s It’sbasically basicallythe thesame samemethod methodasas asinin in You must next add method named createCenter(). It’s basically the same method exercise exercise1,1, 1,and andthe thetask taskisisistoto tocreate createthe thelist listbox boxand andplace placeitititinin inaaaJScollPane. JScollPane.The Theonly onlydifference difference exercise and the task create the list box and place JScollPane. The only difference isisisthat thatthe thelist listbox boxisisisnow nowcalled calledsomething somethingelse. else.Next, Next,add addthe themethod methodcreateWindow(), createWindow(), that the list box now called something else. Next, add the method createWindow(), which whichcreates createsthe thewindow’s window’scomponents: components: which creates the window’s components: private void void createWindow() createWindow() private { { JPanel panel panel == new new JPanel(new JPanel(new BorderLayout(0, BorderLayout(0, 10)); 10)); JPanel panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.add(createCenter()); panel.add(createCenter()); add(panel); add(panel); }}

Download free eBooks at bookboon.com 2323 23

JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA 2: PROGRAMS WITH A JAVA GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL

Hello Swing swIng Hello swIng Hello

Keep in in mind mind that that ititit isisis necessary necessary to to add add an an import import statement statement Keep in mind that necessary to add an import statement Keep import javax.swing.border.*; javax.swing.border.*; import

You should should also also call call the the method method createWindow() createWindow() from from the the constructor. constructor. Run Run the the program, program, You should also call the method createWindow() from the constructor. Run the program, You the result result should should now now be be that that you you get get aaa window window with with aaa list list box. box. the result should now be that you get window with list box. the 4) Add Add aaa method method createBottom(). createBottom(). It It must must be be the the same same method method as as in in the the program program HelloSwing HelloSwing 4) Add method createBottom(). It must be the same method as in the program HelloSwing 4) whichadds addsthe theClear Clearbutton buttonto tothe thewindow. window.You Youmust mustthen thenadd addaaastatement statementto tocreateWindow(), createWindow(), which adds the Clear button to the window. You must then add statement to createWindow(), which so the the panel panel that that createBottom() createBottom() creates creates are are added added to to the the bottom bottom of of the the window: window: so the panel that createBottom() creates are added to the bottom of the window: so private void void createWindow() createWindow() private {{ JPanel panel panel == new new JPanel(new JPanel(new BorderLayout(0, BorderLayout(0, 10)); 10)); JPanel panel.setBorder(new EmptyBorder(10, EmptyBorder(10, 10, 10, 10, 10, 10)); 10)); panel.setBorder(new panel.add(createBottom(), BorderLayout.SOUTH); panel.add(createBottom(), BorderLayout.SOUTH); panel.add(createCenter()); panel.add(createCenter()); add(panel); add(panel); }}

> Apply now redefine your future

- © Photononstop

AxA globAl grAduAte progrAm 2015

axa_ad_grad_prog_170x115.indd 1

19/12/13 16:36

Download free eBooks at bookboon.com 24 24 24

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Hello Swing Hello swIng

If you then run the program, the result should be the following: If you then run the program, the result should be the following:

5) You now need to write the code to the top panel, which is a little more difficult. Start 5) You now need to write the code to the top panel, which is a little more difficult. Start by adding the following method: by adding the following method: private void initButton(JButton cmd) { cmd.setPreferredSize(new Dimension(29, 29)); cmd.setFont(new Font("Liberation Sherif", Font.PLAIN, 16)); cmd.setMargin(new Insets(0, 0, 0, 0)); }

ItIthas hasaabutton buttonasasaaparameter, parameter,and andassign assignthe thebutton buttonaasize sizeofof29 29××29, 29,defines definesthe thefont, font, the button should apply and remove an internal margin, as a button has by default. the button should apply and remove an internal margin, as a button has by default. You Youcan canthen thenadd addthe thefollowing followingmethod: method: private JPanel createRight() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0)); initButton(cmdAdd); initButton(cmdSub); initButton(cmdMul); initButton(cmdDiv); panel.add(cmdAdd); panel.add(cmdSub); panel.add(cmdMul); panel.add(cmdDiv); return panel; }

Download free eBooks at bookboon.com 25 25

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Hello Swing Hello swIng Hello swIng

The Themethod methodcalls callsinitButton() initButton()for foreach eachofofthe thefour fourcalculation calculationbuttons, buttons,and andthen thenplaces placesthe the four buttons in a JPanel with FlowLayout. The method calls initButton() for each of the four calculation buttons, and then places the four buttons in a JPanel with FlowLayout. four buttons in a JPanel with FlowLayout. As Asthe thenext nextstep stepyou youneed needtotocreate createaapanel paneltotothe thetwo twoinput inputfields: fields: As the next step you need to create a panel to the two input fields:

private JPanel createLeft() private JPanel createLeft() { { JPanel panel = new JPanel(new GridLayout(1, 2, 10, 0)); JPanel panel = new JPanel(new GridLayout(1, 2, 10, 0)); panel.add(txtNum1); panel.add(txtNum1); panel.add(txtNum2); panel.add(txtNum2); return panel; return panel; } }

HereI Iuse useaaGridLayout. GridLayout.ItItisisaalayout layoutmanager managerthat thatdivides dividesaapanel panelininaanumber numberofofrows rows Here Here I use a GridLayout. It is a layout manager that divides a panel in a number of rows andcolumns. columns.This Thisdivides dividesaapanel panelininaanumber numberofofcells cellsthat thatall allhave havethe thesame samesize. size.InInthis this and and columns. Thisrow divides a panel in a and number of cells that the all have the same of size. this case,there thereisisone one two columns, theresult result that panelconsists consists twoIn cells, case, row ofoftwo columns, and the isisthat the panel of two cells, case, isalways one row two columns, result is that consists two cells, whichthere willalways beofof ofthe thesame samesize. size.and Thethe two input fieldsthe arepanel added theof panel, and which will be The two input fields are added totothe panel, and which will always be of the same size. The two input fields are added to the panel, and eachfield fieldwill willautomatically automaticallyfill fillthe thecell cellthat thatititisislocated locatedin. in.The Theconstructor constructorfor forGridLayout GridLayout each each field will automatically fill the cell that it is located in. The constructor for GridLayout objecthas hastwo twoadditional additionalparameters parametersthat thatindicates indicateshow howmuch muchspace spacethere thereshould shouldbe bebetween between object object hashorizontally two additional parameters thecells cells andvertically. vertically. that indicates how much space there should be between the horizontally and the cells horizontally and vertically. Finally,add addthe thefollowing followingmethod: method: Finally, Finally, add the following method: private JPanel createTop() private JPanel createTop() { { JPanel panel = new JPanel(new BorderLayout(10, 10)); JPanel panel = new JPanel(new BorderLayout(10, 10)); panel.add(createRight(), BorderLayout.EAST); panel.add(createRight(), panel.add(createLeft()); BorderLayout.EAST); panel.add(createLeft()); return panel; } return panel; }

It returns a panel with a BorderLayout. For this panel is added the panel with the 4 calculation returnsso panel with BorderLayout. Forpanel thispanel panel isadded added the panel with the calculation ItIt returns aapanel aaBorderLayout. For this panel with 44calculation buttons it sitswith to the right, and the withisthe twothe input fields sothe that it uses the buttons so it sits to the right, and the panel with the two input fields so that it uses the buttons so it sits to the right, and the panel with the two input fields so that it remaining space. If you then apply the method createTop() in createWindow(), youuses can the add remaining space. youdesign thenapply apply the method createTop() createWindow(),you youcan canadd add remaining space. IfIfyou then the method inincreateWindow(), the top panel and the of the window iscreateTop() now finished. thetop toppanel paneland andthe thedesign designofofthe thewindow windowisisnow nowfinished. finished. the

Download free eBooks at bookboon.com 26 26

JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

6) What What 6) following following

Hello Swing Hello swIng

remains is is to to attach attach event event handlers handlers to to the the 5 5 buttons. buttons. Start Start by by adding adding the the remains method: method:

private void calculate(char ch) { try { double tal1 = Double.parseDouble(txtTal1.getText()); double tal2 = Double.parseDouble(txtTal2.getText()); double res = 0; switch (ch) { case '+': res = tal1 + tal2; break; case '-': res = tal1 – tal2; break; case '*': res = tal1 * tal2; break; case '/': res = tal1 / tal2; break; } model.addElement(String.format("%f %s %f = %f", tal1, "" + ch, tal2, res)); } catch (Exception ex) { model.addElement(ex.toString()); }

LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!

Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.

Download free eBooks at bookboon.com 27 27

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

}

Hello HelloSwing swIng

txtTal1.setText(""); txtTal2.setText(""); txtTal1.requestFocus();

ItIthas hasaaparameter parameterthat thattells tellswhich whichcalculation calculationtotobe becarried carriedout. out.The Themethod methodperforms performsthe the calculation and inserts a line in the model for the list box. calculation and inserts a line in the model for the list box. This Thismethod methodmust mustbe becalled calledfrom fromthe thebuttons buttonsevent eventhandlers. handlers.This Thisshould shouldbe bedone doneby bythe the same way as in the program HelloSwing to add a method addListeners(), which adds event same way as in the program HelloSwing to add a method addListeners(), which adds event handlers handlersfor forthe thebuttons, buttons,but butthis thistime timefor forall all55buttons, buttons,with withthe thehelp helpofofanonymous anonymousclasses. classes. Remember to call the methods addListeners() from the constructor in MainWndow. Remember to call the methods addListeners() from the constructor in MainWndow. Then Thenthe theprogram programshould shouldbe befinished finishedand andcould couldbe betested. tested.

Download free eBooks at bookboon.com 28 28

JAVA 2: 2: PROGRAMS WITH AA JAVA PROGRAMS WITH GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Fonts and colors Fonts and Colors

3 3 FONTS FONTSAND ANDCOLORS COLORS Most Mostofofthe thecomponents componentsthat thatcan canbebeinserted insertedinto intoa awindow/panel window/paneldisplays displaystext textand andyou you can candefine definethe thefont, font,which whichthey theymust mustuse. use.Similarly, Similarly,you youcan candefine definethe thecolor colorofofthe thetext text uses, uses,and andfinally finallyyou youcan candefine definethe thebackground backgroundcolor. color.The Theprogram programTextColor TextColoropens opensthe the following followingwindow: window:

It Itis isa avery verysimple simpleprogram programthat thatininfact factdodonothing. nothing.It Ithas hasthe thesame samearchitecture architectureasasthe the previous previousprograms, programs,ininwhich whichthe themain mainclass classopens opensa awindow, window,which whichininthis thiscase caseis isdefined defined asasfollows: follows: package textcolor; import java.awt.*; import javax.swing.*; public class MainWindow extends JFrame { public MainWindow() { setTitle("Font og farver"); setSize(500, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); createWindow(); setVisible(true); } private void createWindow() { add(createLabel("North", Color.blue, Color.white, new Font("Liberation Serif", Font.PLAIN, 24), 0, 30), BorderLayout.NORTH);

Download free eBooks at bookboon.com 29 29

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

Fonts and colors Fonts and Colors

add(createLabel("South", Color.green, Color.black, new Font("Liberation Serif", Font.BOLD, 36), 0, 50), BorderLayout.SOUTH); add(createLabel("West", Color.magenta, Color.black, new Font("Liberation Serif", Font.ITALIC, 18), 60, 0), BorderLayout.WEST); add(createLabel("East", Color.red, Color.white, new Font("Liberation Serif", Font.BOLD | Font.ITALIC, 24), 60, 0), BorderLayout.EAST); add(createLabel("Center", new Color(240, 240, 240), Color.pink, new Font("Liberation Serif", Font.BOLD, 96), 0, 0));

private JLabel createLabel(String text, Color bg, Color fg, Font font, int width, int height) { JLabel label = new JLabel(text); label.setOpaque(true); label.setBackground(bg); label.setForeground(fg); label.setFont(font); label.setHorizontalAlignment(JLabel.CENTER); label.setPreferredSize(new Dimension(width, height));

Download free eBooks at bookboon.com 30 30

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

}

}

Fonts Fontsand andcolors Colors

return label;

I’ll start with the method createLabel(), which creates and returns a component of the type I’ll start with the method createLabel(), which creates and returns a component of the type JLabel. It is a component that shows a text. The method has 6 parameters: JLabel. It is a component that shows a text. The method has 6 parameters: ------

The first is the text. The first is the text. The next is the background color, which is an object of the type Color. The next is the background color, which is an object of the type Color. The third is the foreground color and thus the text color. It is likewise an object The third is the foreground color and thus the text color. It is likewise an object of type Color. of type Color. The fourth parameter is the font, which is an object of type Font. The fourth parameter is the font, which is an object of type Font. The last two parameters are respectively the width and height og the component. The last two parameters are respectively the width and height og the component.

The method’s statements are easy enough to figure out, but you must again note how to The method’s statements are easy enough to figure out, but you must again note how to define the size of a component with setPreferredSize(). A JLabel is shown with transparent define the size of a component with setPreferredSize(). A JLabel is shown with transparent background by default, and therefore can not have a background color unless you say that background by default, and therefore can not have a background color unless you say that the background should not be transparent. This is done with setOpaQue(). the background should not be transparent. This is done with setOpaQue(). A frame window is by default born with a BorderLayout, and you can immediately add 5 A frame window is by default born with a BorderLayout, and you can immediately add 5 components, as happens in the method createWindow(). components, as happens in the method createWindow(). A BorderLayout divides as mentioned a window/ panel in 5 areas, called respectively NORTH, A BorderLayout divides as mentioned a window/ panel in 5 areas, called respectively NORTH, EAST, SOUTH, WEST and CENTER, with the latter as default. Each region may contain EAST, SOUTH, WEST and CENTER, with the latter as default. Each region may contain a single component, but may also be empty. If so, the area fills nothing on the screen. If a single component, but may also be empty. If so, the area fills nothing on the screen. If an area contains a component, the following applies concerning the size: an area contains a component, the following applies concerning the size: -- NORTH: The width is the width of the panel, and the height is determined by - NORTH: The width is the width of the panel, and the height is determined by the component’s height defined by its preferred size. The width of the component the component’s height defined by its preferred size. The width of the component in terms of its preferred size is ignored. in terms of its preferred size is ignored. -- SOUTH: The width is the width of the panel, and the height is determined by the - SOUTH: The width is the width of the panel, and the height is determined by the component’s height defined by its preferred size. The width of the component in component’s height defined by its preferred size. The width of the component in terms of its preferred size is ignored. terms of its preferred size is ignored. -- WEST: The height is the height of the panel minus the height that is used to NORTH - WEST: The height is the height of the panel minus the height that is used to NORTH and SOUTH, and the width is determined by the component’s width defined by and SOUTH, and the width is determined by the component’s width defined by its preferred size. The component’s height in terms of its preferred size is ignored. its preferred size. The component’s height in terms of its preferred size is ignored. -- EAST: The height is the height of the panel minus the height that is used to NORTH - EAST: The height is the height of the panel minus the height that is used to NORTH and SOUTH, and the width is determined by the component’s width defined by and SOUTH, and the width is determined by the component’s width defined by its preferred size. The component’s height in terms of its preferred size is ignored. its preferred size. The component’s height in terms of its preferred size is ignored. -- CENTER: The width is the width of the panel minus the width used by the WEST - CENTER: The width is the width of the panel minus the width used by the WEST and EAST, and the height is the height of the panel minus the height that is used and EAST, and the height is the height of the panel minus the height that is used to NORTH and SOUTH. The component’s preferred size is ignored. to NORTH and SOUTH. The component’s preferred size is ignored.

Download free eBooks at bookboon.com 3131

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

Fonts Fontsand andcolors Colors

InInthis thiscase, case,there thereisisplaced placed55JLabel JLabelcomponents componentsininthe thepanel, panel,where wherea acomponent componentisiscreated created bybythe themethod methodcreateLabel(). createLabel().Here Hereyou youshould shouldnote, note,how howthe thesize sizeisisdefined, defined,and andthat thatthe the values valuesfor forwidth widthand andheight heightwhere wherethey theyare areignored ignoredare areset settoto0.0.ItItisisnot notnecessary necessaryand andisis only onlydone donetotoclarify clarifythat thatthe thevalues valuesisisnot notused. used. Otherwise Otherwisenote notehow howyou youdefine definecolors colorsand andfonts. fonts.The TheColor Colorclass classhas hasa anumber numberofofconstants constants for forfrequently frequentlyused usedcolors, colors,and andmost mostofofthe thecolors colorsininthis thisexample exampleare areindicated indicatedbybymeans means ofofthese thesecolors. colors.Colors Colorsare aredefined definedusing usingthree threeintensities intensitiesofofred, red,green greenand andblue, blue,and andwee wee talk about this color coding as RGB colors. Each intensity has a value between 0 and 255, talk about this color coding as RGB colors. Each intensity has a value between 0 and 255, and andthe thenumber numberofofpossible possiblecolors colorsisis

The Thefollowing followingtable tableshows showssome someexamples examplesofofcolor colorencodings encodings RR

GG

BB

Farve Farve

00

00

00

Black Black

255 255

255 255

255 255

White White

255 255

00

00

Red Red

00

255 255

00

Green Green

00

00

255 255

Blue Blue

255 255

255 255

00

Yellow Yellow

128 128

128 128

128 128

Gray Gray

Here Hereyou youneed needtotospecifically specificallynote notethe thelast lastencoding, encoding,where wherethe thesame samevalue valuefor forallallintensities intensities provides providesa agrayscale. grayscale.InInJava Javayou youcan candefine definea acolor colorasasananobject objecttotothe thetype typeColor Colorwith withcolor color intensities to the constructor. It is used in the label that sits center in the window where intensities to the constructor. It is used in the label that sits center in the window where there thereisisdefined definedthe thefollowing followingcolor: color: new Color(240, 240, 240)

This Thismeans meansthat thatthe thecomponent componentwill willhave havea afaint faintgray graybackground. background. You Youdefine definea afont fontfrom fromthe thefont fontname, name,whether whetherititshould shouldbebenormal, normal,italic, italic,bold boldororpossibly possibly a acombination of the last two. Finally, you specify the font size. combination of the last two. Finally, you specify the font size.

Download free eBooks at bookboon.com 3232

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

You You should should note note that that course because it course because it is is aa an an event event handling. handling.

Fonts and Colors Fonts and colors

this this time time the the program program simple demo program, simple demo program,

do do not not define define any any event event handling. handling. It It and in practice GUI programs always and in practice GUI programs always

is is of of have have

Finally, in the the constructor constructor you you should should note note the the statement: statement: Finally, in setLocationRelativeTo(null);

It It is is aa statement statement that that ensures ensures that that the the window window opens opens in in the the middle middle of of the the screen. screen.

EXERCISE EXERCISE 3 3 Make JLabel components components so so Make aa copy copy of of the the program program TextColor. TextColor. You You should should modify modify the the 5 5 JLabel 1. North North must must use use aa Liberation 1. Liberation Sans Sans font font that that is is bold bold and and 16 16 point. point. 2. South must have a dark green text color. 2. South must have a dark green text color. 3. West West must must have have aa width 3. width on on 100 100 and and aa font font on on 48 48 point. point. 4. East must have a standard yellow text color. 4. East must have a standard yellow text color. 5. Center Center must must have have at at light light gray gray background background and and aa gray gray text text color. color. 5.

Download free eBooks at bookboon.com 33 33

Click on the ad to read more

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Dialog boxes

4 DIALOG BOXES In the above examples are each time been a single window, but in practice, a GUI program have several or many windows, and in this chapter I will show how you from a window can open another window. The main window is called a frame window, and is derived from the class JFrame. Another window, is usually a dialog box, which is a class derived from JDialog. I will show a program that has three windows:

Here is MainView a usual frame window, which in this case must have two buttons, which are used to open each of the other two windows:

The window to the right is an example of a dialog box where you should enter a name (first name and last name):

It must be a modal dialog, and it means that when the dialog box is open, the other windows of the application does not have focus, and you can not interact with the other windows before this dialog box is closed.

Download free eBooks at bookboon.com 34

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

Dialog dIalogboxes boxes

The Thethird thirdwindow windowmust mustalso alsobebea adialog dialogand andhas hastotoshow showa alist listbox boxwith withthe thenames namesthat that have havebeen beenentered entered(see (seebelow), below),but butititmust mustbebea amodless modlessdialog dialogbox, box,which whichmeans meansthat thatother other windows can get focus while the dialog box is open. windows can get focus while the dialog box is open. Dialog Dialogboxes boxesare aredefined defined(almost) (almost)the thesame sameway wayasasframe framewindows, windows,and andasassuch suchthere thereisis nothing nothingnew newininthe theprogram, program,but butthe thethree threewindows windowshas hastotocommunicate, communicate,sosothat thatififyou you enter a name in the dialog box above, then dialog box with the list box must be updated enter a name in the dialog box above, then dialog box with the list box must be updated with withthe theentered enteredname. name.

The Theprogram programshould shouldrepresent representa aname nameasasananobject, object,and andfor forthat thatI Ihave haveused usedthe theclass class Name Namefrom fromthe theprogram programComparison Comparisonininthe thebook bookJava Java1.1.The Theclass classisissimple simpleand andcompletely completely unchanged unchangedand andisistherefore thereforenot notdiscussed discussedfurther furtherhere. here. I’ll I’llstart startwith withthe thedialog dialogbox boxfor forentering enteringa aname: name: package dialogs; import import import import

java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*;

Download free eBooks at bookboon.com 3535

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Dialog boxes dIalog boxes

public class EnterView extends JDialog { private DefaultListModel model; private JTextField txtFirstname = new JTextField(); private JTextField txtLastname = new JTextField(); public EnterView(DefaultListModel model) { super(null, "Enter a name", Dialog.ModalityType.APPLICATION_MODAL); this.model = model; setSize(400, 200); setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createView(); setVisible(true); } private void createView() { setLayout(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout(0, 20)); panel.setBorder(new EmptyBorder(20, 20, 20, 20)); panel.add(createTop(), BorderLayout.NORTH);

Download free eBooks at bookboon.com 36 36

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

Dialog boxes dIalog boxes

panel.add(createBottom()); add(panel);

private JPanel createTop() { JPanel panel = new JPanel(new GridLayout(2, 1, 0 ,10)); panel.add(createLine("First name", txtFirstname)); panel.add(createLine("Last name", txtLastname)); return panel; } private JPanel createBottom() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); panel.add(createButton("OK", 90, 25, this::ok)); panel.add(createSpace()); panel.add(createButton("Close", 90, 25, this::close)); return panel; } private JPanel createLine(String text, JTextField field) { JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel(text); label.setPreferredSize(new Dimension(90, 22)); panel.add(label, BorderLayout.WEST); panel.add(field); return panel; } private JButton createButton(String text, int width, int height, ActionListener listener) { JButton cmd = new JButton(text); cmd.addActionListener(listener); cmd.setPreferredSize(new Dimension(width, height)); return cmd; } private JLabel createSpace() { JLabel label = new JLabel(); label.setPreferredSize(new Dimension(10, 20)); return label; }

Download free eBooks at bookboon.com 37 37

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Dialog dIalog boxes boxes

private void clear() { txtFirstname.setText(""); txtLastname.setText(""); txtFirstname.requestFocus(); } private void ok(ActionEvent e) { String firstname = txtFirstname.getText().trim(); String lastname = txtLastname.getText().trim(); if (firstname.length() > 0 && lastname.length() > 0) { model.addElement(new Name(firstname, lastname)); clear(); } else JOptionPane.showMessageDialog(this, "You must enter both first name and last name", "Error", JOptionPane.WARNING_MESSAGE); }

}

private void close(ActionEvent e) { dispose(); }

The class is called EnterView, and the first thing to note is that the class inherits JDialog The class is called EnterView, and the first thing to note is that the class inherits JDialog instead of JFrame. It is telling that it is a dialog box. There are three instance variables, to instead of JFrame. It is telling that it is a dialog box. There are three instance variables, to the two input fields and a model for a list box. It may seems strange, since the dialog box the two input fields and a model for a list box. It may seems strange, since the dialog box does not contain a list box, but it must be used to keep the Name objects to be displayed does not contain a list box, but it must be used to keep the Name objects to be displayed in the second dialog. The model is sent as a parameter in the constructor. Aside from that, in the second dialog. The model is sent as a parameter in the constructor. Aside from that, there is not much new in the constructor, but you must notice the first line, which is the there is not much new in the constructor, but you must notice the first line, which is the place where one says that it is a modal dialog box by sending a parameter to the constructor place where one says that it is a modal dialog box by sending a parameter to the constructor of JDialog. Finally, note the statement setDefaultCloseOperation(), which uses a different of JDialog. Finally, note the statement setDefaultCloseOperation(), which uses a different parameter, indicating that if you click the cross in the title bar, then the dialog box must parameter, indicating that if you click the cross in the title bar, then the dialog box must be closed, and the program should not terminate. be closed, and the program should not terminate. Then there is the method createView(), which initializes the window components. As in the Then there is the method createView(), which initializes the window components. As in the other examples, it is spread out in several methods and is certainly complex enough, but other examples, it is spread out in several methods and is certainly complex enough, but conversely, there is not much new compared to what was previously mentioned. However, conversely, there is not much new compared to what was previously mentioned. However, you should datailed study how the user interface is defined and, in particular, observe what you should datailed study how the user interface is defined and, in particular, observe what happens to the window when you run the program and changes the window size. happens to the window when you run the program and changes the window size.

Download free eBooks at bookboon.com 38 38

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH AA GRAPHICAL USER JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE INTERFACE GRAPHICAL USER INTERFACE

Dialog dIalog boxes boxes dIalog boxes

However, However, there there isis one one place place where where there there are are added added something something new. new. The The dialog dialog box box has has two two However, there is one place where there are added something new. The dialog box has two buttons, buttons, and and they they must must have have attached attached event event handlers. handlers. In In the the preceding preceding examples, examples, II have have buttons, and handlers they must have attached event handlers. In the preceding examples, I have attached attachedevent event handlersfor forbuttons buttonsat ateither eitherdefining defininginner innerclasses classesor orby bydefining defininganonymous anonymous attached event handlers for buttons at either defining inner classes or byclasses defining anonymous classes. Inner classes requires to be written much code and anonymous results classes. Inner classes requires to be written much code and anonymous classes results in in code code classes. Inner classes requires to be written much code and anonymous classes results in code that that can can be be hard hard to to read. read. However, However, there there are are alternatives alternatives and and in in this this example, example, II have have used used can be hard to read. However, thereexample, are alternatives and in this for example, I have used aathat simple simple and and readable readable notation. notation. If, If, as as an an example, the the event event handler handler for the the Close Close button, button, a simple and readable notation. If,that as an example, the event handler for box. the Close button, there shall be no more statements a statement that close the dialog You do there shall be no more statements that a statement that close the dialog box. You do this this therethe shall be no more statements that a the statement thatmethod: close the dialog box. You do this with statement dispose(), and I added following with the statement dispose(), and I added the following method: with the statement dispose(), and I added the following method: private void close(ActionEvent e) {private void close(ActionEvent e) {dispose(); } dispose(); }

Here you must notice the parameter, which is the one that says that this method can be Here Here you you must must notice notice the the parameter, parameter, which which isis the the one one that that says says that that this this method method can can be be used as an event handler. It must be attached to the button, which is done in the following used usedasasan anevent eventhandler. handler.ItItmust mustbe beattached attachedtotothe thebutton, button,which whichisisdone doneininthe thefollowing following way in the method createBottom(): way wayininthe themethod methodcreateBottom(): createBottom(): this::close this::close

93%

OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION

MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE

5 Specializations

Personalize your program

www.ie.edu/master-management

#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES

[email protected]

Download free eBooks at bookboon.com 39 39 39

Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

Dialog dIalogboxes boxes

Simpler Simplerititcan canhardly hardlybe. be.What Whatexactly exactlyhappens, happens,I Iwill willnot notexplain explainhere, here,but butininprinciple principle what whathappens happensisisthat thatthe thecompiler compilerautomatically automaticallygenerates generatesthe thecode codethat thatI Iusually usuallywrite. write.AA more moredetailed detailedexplanation explanationfollows followsininthe thebook bookJava Java4,4,but butthe thenotation notationenhances enhancesreadability readability sosomuch that I would recommend that you start taking it as is and use it already. much that I would recommend that you start taking it as is and use it already. There Thereisisaasimilar similarevent eventhandler handlerfor forthe thesecond secondbutton. button.ItItisisobviously obviouslymore moreextensive, extensive,but but shortly shortlythe thefollowing followinghappens. happens.The Theentered enteredvalues valuesare arecopied copiedtotovariables variablesfrom fromthe thetwo twoinput input fields. If there is typed something for both first and last name a Name object is created, fields. If there is typed something for both first and last name a Name object is created, and andthe themodel modelisisupdated. updated.IfIfnot notaamessage messagebox boxdisplays displaysan anerror errormessage. message. Then Thenthere thereisisthe theother otherdialog dialogbox, box,showing showingthe theentered enterednames: names: package dialogs; import import import import

java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*;

public class ShowView extends JDialog { private DefaultListModel model; private CloseListener listener; public ShowView(DefaultListModel model, CloseListener listener) { super(null, "Names", Dialog.ModalityType.MODELESS); this.model = model; this.listener = listener; setSize(400, 500); setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(new ClosingHandler()); createView(); setVisible(true); } private void createView() { setLayout(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout(0, 20)); panel.setBorder(new EmptyBorder(20, 20, 20, 20)); panel.add(new JScrollPane(new JList(model))); panel.add(createBottom(), BorderLayout.SOUTH); add(panel); }

Download free eBooks at bookboon.com 40 40

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

Dialog dIalogboxes boxes

private JPanel createBottom() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); panel.add(createButton("Close", 90, 25, this::close)); return panel; } private JButton createButton(String text, int width, int height, ActionListener listener) { JButton cmd = new JButton(text); cmd.addActionListener(listener); cmd.setPreferredSize(new Dimension(width, height)); return cmd; } private void close(ActionEvent e) { listener.dialogClosed(); dispose(); }

}

class ClosingHandler extends WindowAdapter { public void windowClosing(WindowEvent e) { listener.dialogClosed(); } }

ItItisissimilar similaraaclass classthat thatinherits inheritsJDialog. JDialog.There Thereare aretwo twoinstance instancevariables, variables,the thefirst firstbeing beingthe the model modeland andthus thusthe theobjects objectsthat thatmust mustbe bedisplayed displayedininthe thelist listbox, box,while whilethe theother otherhas hasthe the type typeCloseListener. CloseListener.I Iexplains explainsthe thetype typeininaamoment, moment,but butvalues valuesfor forboth bothvariables variablesare aresent sent totothe theconstructor. constructor.Otherwise, Otherwise,there thereisisonly onlyone onething thingtotonote, note,that thatthe thefirst firstline linedefines defines that it is a modeless dialog box. that it is a modeless dialog box. The Thedesign designofofthe thewindow windowisisthis thistime timesimple simplesince sinceititisismerely merelytotoplace placeaalist listbox boxand andaa button. button.The Thebutton buttonisisassigned assignedan anevent eventhandler handlerwith withthe thesame samesyntax syntaxasasmentioned mentionedabove, above, but there is one complication back. The dialog is opened by clicking a button in the but there is one complication back. The dialog is opened by clicking a button in themain main window, window,and andbecause becauseititisisaamodeless modelessdialog dialogbox, box,you youcan canclick clickthe thebutton buttonagain againand andopen open the thedialog dialogseveral severaltimes. times.I Iare arenot notinterested interestedininthat, that,but butconversely, conversely,ititmust mustbe bepossible possibletoto opened openedthe thedialog dialogagain againififititisisclosed. closed.ItItisistherefore thereforenecessary necessarytotosend sendaamessage messageback backtoto the themain mainwindow windowwhen whenthe thedialog dialogcloses. closes.As Asmentioned, mentioned,the theconstructor constructorhas hasaaparameter parameter named namedlistener listenerthat thathas hasthe thetype typeCloseListener. CloseListener.It’s It’saasimple simpleinterface interfacedefined definedininthe thesame same file fileasasthe theclass classMainView: MainView:

Download free eBooks at bookboon.com 4141

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL USER JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE INTERFACE

Dialog dIalog boxes boxes dIalog boxes

GRAPHICAL USER INTERFACE

interface CloseListener interface CloseListener { { public void dialogClosed(); } public void dialogClosed(); }

The interface interface does does nothing nothing more more than than define define aa single single method, method, but but when when the the dialog dialog box box The The interface does nothing more than define a single method, but when the dialog box through the the constructor constructor get get an an object object of of this this type type the the dialog dialog box box know know that that object object has has through through the constructor get an object of this type the dialog box know that object has such aa method, method, and and can can thus thus sent sent aa notfikation notfikation when when the the dialog dialog box box isis closed closed by by clicking clicking such such a method, and can thus sent a notfikation when the dialog box is closed by clicking the Close Close button: button: the the Close button: private void close(ActionEvent e) private void close(ActionEvent e) { { listener.dialogClosed(); listener.dialogClosed(); dispose(); } dispose(); }

Now the the dialog dialog box, box, in in principle, principle, also also could could be be closed closed by by clicking clicking on on the the cross cross in in the the Now Now the dialog box, in principle, also could be closed by clicking on the cross in the titleline, and and in in this this case, case, sending sending aa similar similar notification. notification. It It isis therefore therefore necessary necessary to to capture capture titleline, titleline, and in this case, sending a similar notification. It is therefore necessary to capture the event event that that occurs occurs when when clicking clicking on on the the cross. cross. It It isis aa WindowEvent, WindowEvent, and and itit occurs occurs in in the the event that occurs when clicking on the cross. It is a WindowEvent, and it occurs in several contexts, contexts, but but above above II have have shown shown how how to to catch catch itit with with the the class class CloseHandler. CloseHandler. Note Note several several contexts, but above I have shown how to catch it with the class CloseHandler. Note that the the handler handler must must be be associated associated with with the the dialog dialog box, box, which which happens happens in in the the constructor: constructor: that that the handler must be associated with the dialog box, which happens in the constructor:

DO YOU WANT TO KNOW:

What your staff really want?

The top issues troubling them?

How to make staff assessments work for you & them, painlessly?

How to retain your top staff

Get your free trial

FIND OUT NOW FOR FREE

Because happy staff get more done

Download free eBooks at bookboon.com 42 42 42

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH AA JAVA GRAPHICAL USER INTERFACE GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

Dialog boxes dIalog boxes boxes dIalog

addWindowListener(new ClosingHandler()); ClosingHandler()); addWindowListener(new

Back Back isisis the the main main window window where where there there isisis not not much much to to explain explain as as ititit isisis just just an an ordinary ordinary Back the main window where there not much to explain as just an ordinary window windowwith withtwo twobuttons: buttons: window with two buttons: package dialogs; dialogs; package import import import import import import import import

java.awt.*; java.awt.*; java.awt.event.*; java.awt.event.*; javax.swing.*; javax.swing.*; javax.swing.border.*; javax.swing.border.*;

public class class MainView MainView extends extends JFrame JFrame implements implements CloseListener CloseListener public { { private DefaultListModel DefaultListModel model model == new new DefaultListModel(); DefaultListModel(); private private JButton cmdShow; private JButton cmdShow; public MainView() MainView() public {{ setTitle("Dialogs"); setTitle("Dialogs"); setSize(200, 160); 160); setSize(200, setResizable(false); setResizable(false); setLocationRelativeTo(null); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE); createWindow(); createWindow(); setVisible(true); setVisible(true); }} private void void createWindow() createWindow() private { { JPanel panel panel == new new JPanel(new JPanel(new GridLayout(2, GridLayout(2, 1, 1, 0, 0, 20)); 20)); JPanel panel.setBorder(new EmptyBorder(20, 20, 20, 20)); panel.setBorder(new EmptyBorder(20, 20, 20, 20)); panel.add(createButton("Enter aa name", name", this::openEnter)); this::openEnter)); panel.add(createButton("Enter panel.add(cmdShow = createButton("Open list", this::openShow)); this::openShow)); panel.add(cmdShow = createButton("Open list", add(panel); add(panel); } } private JButton JButton createButton(String createButton(String text, text, ActionListener ActionListener listener) listener) private { { JButton cmd cmd == new new JButton(text); JButton(text); JButton cmd.addActionListener(listener); cmd.addActionListener(listener); return cmd; cmd; return } } private void void openEnter(ActionEvent openEnter(ActionEvent e) e) private {{

Download free eBooks at bookboon.com 43 43 43

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

}

Dialog dIalog boxes boxes

new EnterView(model);

private void openShow(ActionEvent e) { cmdShow.setEnabled(false); new ShowView(model, this); }

}

public void dialogClosed() { cmdShow.setEnabled(true); }

There are are two two instance instance variables, variables, respectively respectively the the model model for for the the list list box box and and aa button. button. There The model model isis sent sent to to both both dialog dialog boxes boxes and and the the button button isis aa reference reference to to the the button button that that The opens the the dialog dialog box box with with the the list. list. You You should should note note that that the the class class implements implements the the interface interface opens CloseListener and and must must therefore therefore define define the the method method dialogClosed(). dialogClosed(). When When the the dialog dialog box box for for CloseListener the list list box box isis opened, opened, two two things things happen. happen. First First disables disables the the button button so so the the dialog dialog box box can can the not be be opened opened again, again, and and then then the the dialog dialog box box opens opens by by sending sending parameters parameters as as the the model model for for not the list list box box and and aa reference reference to to the the window window itself, itself, but but the the window window isis special special aa CloseListener, CloseListener, the and therefore therefore can can be be used used as as aa current current parameter. parameter. The The result result isis that that when when the the dialog dialog box box and closes, itit calls calls the the method method dialogClosed(), dialogClosed(), which which enables enables the the button, button, and and the the dialog dialog box box can can closes, be opened opened again. again. When When you you test test the the program, program, especially especially noting noting that that ifif you you create create aa name name be then the the list list box box isis updated updated automatically automatically without without you you must must do do anything. anything. The The technique technique then for that that isis hided hided in in the the class class DefaultListModel. DefaultListModel. for

EXERCISE 44 EXERCISE In this this exercise exercise you you have have to to make make some some improvements improvements to to the the program program above. above. Start Start by by In creating aa copy copy and and open open the the copy copy in in NetBeans. NetBeans. creating You should should start start to to add add another another button button to to the the dialog dialog ShowView ShowView where where the the button button should should You delete the the contents contents of of the the list list box. box. This This change change should should not not lead lead to to major major challenges. challenges. delete Next, itit must must be be such such that that ifif you you double-click double-click on on aa name name in in the the list list box, box, then then the the dialog dialog Next, box EnterView EnterView should should opens opens initialized initialized with with the the name name that that isis clicked clicked on, on, and and you you should should box then be be able able to to edit edit the the name. name. It It isis immediately immediately aa little little more more complicated, complicated, but but you you can can go go then as follows. follows. as Modify the the class class Name, Name, so so itit has has set set methods methods for for both both variables. variables. Modify

Download free eBooks at bookboon.com 44 44

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA 2: PROGRAMS WITH A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL USER INTERFACE

Dialog dIalog boxes boxes dIalog boxes

Add parameter index to the constructor in the class EnterView: Add aaa parameter parameter index index to to the the constructor constructor in in the the class class EnterView: EnterView: Add public EnterView(DefaultListModel EnterView(DefaultListModel model, model, int int index) index) public

and store the value negative, shal and store store the the value value in in an an instance instance variable. variable. If If the the value value is negative, it shal indicate indicate that that the the and in an instance variable. If the value isis negative, itit shal indicate that the dialog box isis used to create Name, and otherwise the index isis interpreted as the index of dialog box box is used to to create create aaa Name, Name, and and otherwise otherwise the the index index is interpreted as as the the index index of of dialog used interpreted the object in the model to be edited. Note that the change means that itit isis necessary to the object object in in the the model model to to be be edited. edited. Note Note that that the the change change means means that that it necessary to to the is necessary change the class MainView where you must add a parameter (value -1) when the dialog change the the class class MainView MainView where where you you must must add add aa parameter parameter (value (value -1) -1) when when the the dialog dialog change box EnterView opens. box EnterView EnterView opens. opens. box In the class ShowView add the following inner class: In the the class class ShowView ShowView add add the the following following inner inner class: class: In class MouseHandler MouseHandler extends extends MouseAdapter MouseAdapter class {{ public void void mouseClicked(MouseEvent mouseClicked(MouseEvent e) e) public {{ JList list list == (JList)e.getSource(); (JList)e.getSource(); JList if (e.getClickCount() (e.getClickCount() == == 2) 2) if { { int nn == list.locationToIndex(e.getPoint()); list.locationToIndex(e.getPoint()); int

Challenge the way we run

EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…

READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM

1349906_A6_4+0.indd 1

22-08-2014 12:56:57

Download free eBooks at bookboon.com 45 45 45

Click on the ad to read more

JAVA JAVA PROGRAMS WITH JAVA2:2: 2:PROGRAMS PROGRAMSWITH WITHAA A JAVA 2: PROGRAMS WITH A GRAPHICAL GRAPHICAL USER INTERFACE GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL USER INTERFACE

Dialog dIalog boxes dIalogboxes boxes dIalog boxes

JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null, model.getElementAt(n)); model.getElementAt(n)); JOptionPane.showMessageDialog(null, model.getElementAt(n)); } } } } } } } } }

ItIt defines defines an event handler concerning mouse clicks, and must be linked tothe the list box, definesan anevent eventhandler handlerconcerning concerningmouse mouseclicks, clicks,and andmust mustbe belinked linkedto thelist listbox, box, ItIt defines an event handler concerning mouse clicks, and must be linked toto the list box, which you can do by changing the method createView(): which you can do by changing the method createView(): whichyou youcan cando doby bychanging changingthe themethod methodcreateView(): createView(): which JList JList list list = = new new JList(model); JList(model); JList list = new JList(model); list.addMouseListener(new list.addMouseListener(new MouseHandler()); MouseHandler()); list.addMouseListener(new MouseHandler()); panel.add(new JScrollPane(list)); panel.add(new JScrollPane(list)); panel.add(new JScrollPane(list));

Before continuing, you should test the program. Create few names and open the dialog Before Beforecontinuing, continuing,you youshould shouldtest testthe theprogram. program.Create Createaaaafew fewnames namesand andopen openthe thedialog dialog Before continuing, you should test the program. Create few names and open the dialog with the list box. Try double-clicking on name and see you get message box that with withthe thelist listbox. box.Try Trydouble-clicking double-clickingon onaaaaname nameand andsee seeififif ifyou youget getaaaamessage messagebox boxthat that with the list box. Try double-clicking on name and see you get message box that displays the name. Doing so is everything regarding double-click into place. displays everything displaysthe thename. name.Doing Doingso sois everythingregarding regardingdouble-click double-clickinto intoplace. place. displays the name. Doing so isiseverything regarding double-click into place. The above event handler for the mouse should now be changed, so itdoes does not open The Theabove aboveevent eventhandler handlerfor forthe themouse mouseshould shouldnow nowbe bechanged, changed,so soit doesnot notopen openaaaa The above event handler for the mouse should now be changed, so itit does not open message box, but instead opens EnterView, where the last parameter now isthe the index ofthe the message messagebox, box,but butinstead insteadopens opensEnterView, EnterView,where wherethe thelast lastparameter parameternow nowis theindex indexof the message box, but instead opens EnterView, where the last parameter now isisthe index ofofthe name that is double clicked. EnterView should show the name, and to do this, change in name double do namethat thatis doubleclicked. clicked.EnterView EnterViewshould shouldshow showthe thename, name,and andto dothis, this,change changein name that isis double clicked. EnterView should show the name, and toto do this, change inin the method createTop() so that itinitializes initializes the input fields with the name that isdoubledoublethe themethod methodcreateTop() createTop()so sothat thatit initializesthe theinput inputfields fieldswith withthe thename namethat thatis doublethe method createTop() so that itit initializes the input fields with the name that isis doubleclicked. Remember that the variable index isthe the index ofthe the Name object relative tothe the clicked. clicked.Remember Rememberthat thatthe thevariable variableindex indexis theindex indexof theName Nameobject objectrelative relativeto the clicked. Remember that the variable index isis the index ofof the Name object relative toto the model. When you then click OK, do not create new Name object, but the object that is model. model.When Whenyou youthen thenclick clickOK, OK,do donot notcreate createaaaanew newName Nameobject, object,but butthe theobject objectthat thatis model. When you then click OK, do not create new Name object, but the object that isis clicked must instead be updated. Itisistherefore therefore necessary tomodify modify the event handler ok() clicked clickedmust mustinstead insteadbe beupdated. updated.It thereforenecessary necessaryto modifythe theevent eventhandler handlerok() ok() clicked must instead be updated. ItItisistherefore necessary totomodify the event handler ok() so that it (using the variable index) distinguishes between the two cases, where to create sosothat (using create thatit (usingthe thevariable variableindex) index)distinguishes distinguishesbetween betweenthe thetwo twocases, cases,where whereto createaaaa so that itit(using the variable index) distinguishes between the two cases, where totocreate new object, and where an existing object isedited. edited. new newobject, object,and andwhere wherean anexisting existingobject objectis edited. new object, and where an existing object isisedited. Once you’ve made these changes, you will find that the list box does not seem tobe be updated, Once Onceyou’ve you’vemade madethese thesechanges, changes,you youwill willfind findthat thatthe thelist listbox boxdoes doesnot notseem seemto beupdated, updated, Once you’ve made these changes, you will find that the list box does not seem totobe updated, but close the dialog box ShowView and open it again, and you will now see that the changes but again, butclose closethe thedialog dialogbox boxShowView ShowViewand andopen openit again,and andyou youwill willnow nowsee seethat thatthe thechanges changes but close the dialog box ShowView and open ititagain, and you will now see that the changes are visible, so the model has therefore been updated. To solve this problem, you must add are arevisible, visible,so sothe themodel modelhas hastherefore thereforebeen beenupdated. updated.To Tosolve solvethis thisproblem, problem,you youmust mustadd add are visible, so the model has therefore been updated. To solve this problem, you must add the following class tofile file with the main window: the thefollowing followingclass classto filewith withthe themain mainwindow: window: the following class totofile with the main window: class class EnhancedListModel EnhancedListModel extends extends DefaultListModel DefaultListModel class EnhancedListModel extends DefaultListModel { { { public public void void update(int update(int index) index) public void update(int index) { { { fireContentsChanged(this, fireContentsChanged(this, index, index, index); index); fireContentsChanged(this, index, index); } } } } } }

Download free eBooks at bookboon.com 4646 46 46

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

dIalog Dialog boxes

It is a class that extends DefaultListModel with a new method. You must also change the definition of the model in the MainView: private DefaultListModel model = new EnhancedListModel();

The new method on the model must be called in the event handler ok() in the class EnterView after the object has been updated: ((EnhancedListModel)model).update(index);

Note the typecast. After that the list box will be updated correctly. You must add one last improvement. The dialog box EnterView must have an additional button to be used to delete the object being edited, but the button must only be enabled if the dialog box is used to edit a Name.

This e-book is made with

SETASIGN

SetaPDF

PDF components for PHP developers

www.setasign.com Download free eBooks at bookboon.com 47 47

Click on the ad to read more

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

More components

5 MORE COMPONENTS In this section I will show an example that, in principle is similar to the first examples, where the program simply consists of a single window, but it is a somewhat more complex example: 1. there are several components both in terms of the number of componentes and the type of components 2. it is an example of a complex layout 3. there is a comprehensive event management If you run the program it opens the following window:

The window should illustrate a sign with a text. You can then using the window’s other components to adjust how the sign should be displayed: -----

the font used to draw the text how the text is aligned (left, right or center) the color used to draw the text the background color to the sign

Download free eBooks at bookboon.com 48

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

More components

Compared to the first examples, this example use more kinds of components: -- JLabel, which is a component showing a text and was used in the previous examples -- JTextField, which is an input field, and is also used in the previous examples -- JComboBox, which is component with a list of objects, and you can then select one of these objects -- JCheckBox, which is a simple component, where you can select a property -- JRadioButton, where several components are organized in a group, so you can choose one of them -- JSlider, which is a component, where you by means of the “shoots” can select a value within a range If on top of that you adds the components JButton and JList that is used in the previous examples, but are not used in this example, you have actually met most of the basic Swing components, and in practice you will get far with these components. Then there is the program code, which is extensive with nearly 350 lines. Rather than show alle the code together, I will show parts in connection with the description of the individual concepts. It is recommended that you open the full code while you read the following. I’ll start with the layout, which this time is quite complex. You should start to run the application and notice how some of the components change their sizes as the window size changes. The components size and location are determined by the layout manager being used, and it is the subject of the next chapter, but for now I have mentioned three layout managers -- BorderLayout -- FlowLayout -- GridLayout and they are all used in this example. By using nested layout managers, that is having panels inside each other with their own layout managers, you can actually by using the above three layout managers design a rather complicated layout.

Download free eBooks at bookboon.com 49

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A JAVA 2: 2: PROGRAMS PROGRAMS WITH A A GRAPHICAL USER INTERFACE JAVA WITH GRAPHICAL USER INTERFACE GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

More components More CoMponents More CoMponents CoMponents More

The Thestarting startingpoint pointisis issimilar similartoto tothe theprevious previousexamples examplesand andstarts startswith withthe thefollowing followingmethod: method: The starting point similar the previous examples and starts with the following method: The starting point is similar to the previous examples and starts with the following method: private void void createWindow() createWindow() private private void createWindow() { {{ JPanel panel panel = new new JPanel(new JPanel(new BorderLayout()); BorderLayout()); JPanel JPanel panel == new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(10, 10, 10, 10, 10)); 10)); panel.setBorder(new EmptyBorder(10, EmptyBorder(10, 10, 10, panel.setBorder(new 10, 10)); panel.add(createTop(), BorderLayout.NORTH); BorderLayout.NORTH); panel.add(createTop(), panel.add(createTop(), BorderLayout.NORTH); panel.add(createCenter()); panel.add(createCenter()); panel.add(createCenter()); add(panel); add(panel); add(panel); } }}

thatby bymeans meansofof of a BorderLayout BorderLayout with with a margin margin around around dividing dividing the the window window into into two two parts, parts, that that by means that by means of aaaBorderLayout BorderLayout with with aaamargin margin around around dividing dividing the the window window into into two two parts, parts, wherethe thetop tophas hasaaapanel panelwith withall allofof of the the adjustment adjustment components, components, while while at at the the bottom bottom where where the top has panel with all where the top has a panel with all of the the adjustment adjustment components, components, while while at at the the bottom bottom hasthe thesign, sign,and anditit it will will use use the the part part of of the the window, window, which which is not not used used for for the the top top panel. panel. has has the sign, and has the sign, and it will will use use the the part part of of the the window, window, which which isisisnot not used used for for the the top top panel. panel. I’llstart startwith withthe thebottom bottompanel, panel,which whichisis is the the simplest. simplest. The The sign sign is represented represented by by a JLabel JLabel I’ll I’ll start with the bottom panel, which I’ll start with the bottom panel, which is the the simplest. simplest. The The sign sign isisisrepresented represented by by aaaJLabel JLabel definedasas as an an instance instance variable: variable: defined defined defined as an an instance instance variable: variable: private JLabel JLabel lblText lblText = = new new JLabel("Det JLabel("Det er er teksten"); teksten"); private private JLabel lblText = new JLabel("Det er teksten");

Thebottom bottompanel panelisis is created created by by the the following following method: method: The The bottom panel The bottom panel is created created by by the the following following method: method: private JPanel JPanel createCenter() createCenter() private private JPanel createCenter() { {{ lblText.setOpaque(true); lblText.setOpaque(true); lblText.setOpaque(true); lblText.setBackground(Color.white); lblText.setBackground(Color.white); lblText.setBackground(Color.white); JPanel panel panel = new new JPanel(new JPanel(new BorderLayout()); BorderLayout()); JPanel JPanel panel == new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(20, 0, 20, 20, 0)); 0)); panel.setBorder(new EmptyBorder(20, EmptyBorder(20, 0, 0, panel.setBorder(new 20, 0)); JPanel sign sign = new new JPanel(new JPanel(new BorderLayout()); BorderLayout()); JPanel JPanel sign == new JPanel(new BorderLayout()); sign.setBorder(new LineBorder(Color.black)); sign.setBorder(new LineBorder(Color.black)); LineBorder(Color.black)); sign.setBorder(new JPanel inner = new JPanel(new BorderLayout()); BorderLayout()); JPanel inner inner == new new JPanel(new JPanel(new JPanel BorderLayout()); inner.setBorder(new LineBorder(Color.white, 5)); inner.setBorder(new LineBorder(Color.white, LineBorder(Color.white, 5)); 5)); inner.setBorder(new inner.add(createDots(), BorderLayout.NORTH); BorderLayout.NORTH); inner.add(createDots(), inner.add(createDots(), BorderLayout.NORTH); inner.add(createDots(), BorderLayout.SOUTH); inner.add(createDots(), BorderLayout.SOUTH); BorderLayout.SOUTH); inner.add(createDots(), inner.add(createMargin(), BorderLayout.WEST); BorderLayout.WEST); inner.add(createMargin(), inner.add(createMargin(), BorderLayout.WEST); inner.add(createMargin(), BorderLayout.EAST); inner.add(createMargin(), BorderLayout.EAST); BorderLayout.EAST); inner.add(createMargin(), inner.add(lblText); inner.add(lblText); inner.add(lblText); sign.add(inner); sign.add(inner); sign.add(inner); panel.add(sign); panel.add(sign); panel.add(sign); return panel; panel; return return panel; } }}

Download free eBooks at bookboon.com 50 50 50 50

Deloitte & Touche LLP and affiliated entities.

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

More components More CoMponents

The first thing that happens is that the panel’s background is set to white. The panel has a The first thingwith thatahappens is that the panel’s background is set to white. The hasalla BorderLayout nested BorderLayout with another nested BorderLayout. Thepanel goal of BorderLayout with a nested BorderLayout nestedofBorderLayout. The goal of all this is to define some margins. The outer with panelanother has a margin 20 on the top and bottom. this to define some margins. outer panel has a margin 20 on the top bottom. The ismiddle panel (called sign) The is intended to define a thin of black frame. Thisand is done by The middle panel (called sign) is intended to define a thin black frame. This is done by assigning a LineBorder, which by default is a line of 1 pixel. Then there is the inner panel assigning a LineBorder, which by default is a line 1 pixel. Then to there the inner called inner. It has a white margin of 5 pixels (toofcreate distance the isblack frame.panel The called inner. It has a white margin of 5 pixels (to create distance to the black frame. The panel places in the corners some small squares (to symbolize screw holes) and finally the panel places in the cornerscenter. some small squares holes) label component is placed To build it all(to thesymbolize following screw methods are and used:finally the label component is placed center. To build it all the following methods are used: private JLabel createMargin() { JLabel label = new JLabel(); label.setPreferredSize(new Dimension(5, 5)); label.setOpaque(true); label.setBackground(Color.white); return label; }

360° thinking

360° thinking

.

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download

Click on the ad to read more

51 51

Dis

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL USER JAVA 2: PROGRAMS PROGRAMS WITH A A GRAPHICAL USERINTERFACE INTERFACE JAVA 2: WITH GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

More Morecomponents CoMponents More CoMponents CoMponents More

private JPanel createDots() private JPanel createDots() createDots() private JPanel { {{ JPanel panel = new JPanel(new BorderLayout()); JPanel panel == new new JPanel(new JPanel(new BorderLayout()); JPanel panel BorderLayout()); panel.add(createDot(), BorderLayout.WEST); panel.add(createDot(), BorderLayout.WEST); panel.add(createDot(), panel.add(createDot(), BorderLayout.WEST); BorderLayout.EAST); panel.add(createDot(), BorderLayout.EAST); panel.add(createDot(), BorderLayout.EAST); panel.add(createMargin()); panel.add(createMargin()); panel.add(createMargin()); return panel; return panel; panel; }return }} private JLabel createDot() private JLabel createDot() createDot() private JLabel { {{ JLabel label = new JLabel(); JLabel label == new new JLabel(); JLabel(); JLabel label label.setPreferredSize(new Dimension(5, 5)); label.setPreferredSize(new Dimension(5, 5)); 5)); label.setPreferredSize(new Dimension(5, label.setOpaque(true); label.setOpaque(true); label.setOpaque(true); label.setBackground(Color.black); label.setBackground(Color.black); label.setBackground(Color.black); return label; label; return } return label; }}

The Thefirst firstisisused usedfor foraaBorderLayout BorderLayouttotodefine defineaawhite whitebackground. background.The Thebottom bottomcreating creatingthe the The first is used for a BorderLayout to define a white background. The bottom creating the The first is used for a BorderLayout to define a white background. The bottom creating the black square (screw hole), while the middle creates a panel with two screw holes and filled black square (screw hole), while the middle creates a panel with two screw holes and filled blacka square square background (screw hole), hole), while while the the middle creates a panel with two screw holes and filled black middle with the holes. with awhite white (screw backgroundbetween between the holes.creates a panel with two screw holes and filled with aa white white background background between between the the holes. holes. with Then Thenthere thereisisthe thetop toppanel, panel,which whichisissomewhat somewhatmore morecomplex. complex.ItItactually actuallyconsists consistsofoffour four Then there is the top panel, which is somewhat more complex. It actually consists of of four four Then there is the top panel, which is somewhat more complex. It actually consists lines with tools that are laid out with a GridLayout: lines with tools that are laid out with a GridLayout: lines with with tools tools that that are are laid laid out out with with aa GridLayout: GridLayout: lines private JPanel createTop() private JPanel createTop() createTop() private JPanel { {{ JPanel panel = new JPanel(new GridLayout(4, 1)); JPanel panel == new new JPanel(new JPanel(new GridLayout(4, GridLayout(4, 1)); 1)); JPanel panel panel.add(createFont()); panel.add(createFont()); panel.add(createFont()); panel.add(createFg()); panel.add(createFg()); panel.add(createFg()); panel.add(createBg()); panel.add(createBg()); panel.add(createBg()); panel.add(createText()); panel.add(createText()); panel.add(createText()); return panel; return panel; panel; }return } }

I’ll start with the bottom line, which defines the input field to the text of the sign. The I’llstart startwith withthe thebottom bottomline, line,which whichdefines definesthe theinput inputfield fieldto tothe thetext textofof ofthe thesign. sign.The The I’ll I’ll with the line, which defines the input field to the text the sign. The fieldstart is defined as bottom an instance variable: fieldisis isdefined definedasas asan aninstance instancevariable: variable: field field defined an instance variable: private JTextField txtText = new JTextField(); private JTextField JTextField txtText txtText == new new JTextField(); JTextField(); private

Download free eBooks at bookboon.com 52 52 52 52

JAVA 2: PROGRAMS WITH A JAVA 2: 2: PROGRAMS PROGRAMS WITH AA JAVA WITH GRAPHICAL USER INTERFACE GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

More components More CoMponents CoMponents More

and the panel with the input field is created as follows: and the the panel panel with with the the input input field field isis created created as as follows: follows: and private JPanel JPanel createText() createText() private {{ txtText.setText(lblText.getText()); txtText.setText(lblText.getText()); JPanel panel panel == new new JPanel(new JPanel(new BorderLayout(10, BorderLayout(10, 0)); 0)); JPanel panel.setBorder(new EmptyBorder(5, EmptyBorder(5, 0, 0, 5, 5, 0)); 0)); panel.setBorder(new JLabel label label == new new JLabel("Tekst"); JLabel("Tekst"); JLabel panel.add(new JLabel("Tekst"), JLabel("Tekst"), BorderLayout.WEST); BorderLayout.WEST); panel.add(new panel.add(txtText); panel.add(txtText); return panel; panel; return }}

The input field is initialized with the content of the label component to the sign, but The input inputthis field initialized with the the content content of theand label component to the thecenter. sign, but but The field isis initialized with the label component to sign, otherwise is primarily a BorderLayout with aof label a input field, added In otherwise this is primarily a BorderLayout with a label and a input field, added center. In otherwise this is primarily a BorderLayout with a label and a input field, added center. In this way one obtains that the field follows the window size. this way way one one obtains obtains that that the the field field follows follows the the window window size. size. this Then there is the line to the background color, which consists of a JLabel, and three pairs Then there there the line line toathe the background color,method which consists consistssuch of aaa JLabel, JLabel,of and three pairs pairs Then the to background color, which of and three consisting ofisaisJLabel, and JSlider. The following creates couple components: consistingof ofaaJLabel, JLabel,and andaaJSlider. JSlider.The Thefollowing followingmethod methodcreates createssuch suchaacouple coupleof ofcomponents: components: consisting private JPanel JPanel createColor(String createColor(String text, text, int int width, width, JSlider JSlider slider, slider, private int min, min, int int max, max, int int value) value) int {{ JPanel panel panel == new new JPanel(new JPanel(new BorderLayout()); BorderLayout()); JPanel JLabel label label == new new JLabel(" JLabel(" "" ++ text); text); JLabel label.setPreferredSize(new Dimension(width, Dimension(width, 30)); 30)); label.setPreferredSize(new panel.add(label, BorderLayout.WEST); BorderLayout.WEST); panel.add(label, slider.setMinimum(min); slider.setMinimum(min); slider.setMaximum(max); slider.setMaximum(max); slider.setValue(value); slider.setValue(value); slider.setMajorTickSpacing(50); slider.setMajorTickSpacing(50); slider.setMinorTickSpacing(10); slider.setMinorTickSpacing(10); slider.setPaintTicks(true); slider.setPaintTicks(true); panel.add(slider); panel.add(slider); return panel; panel; return }}

Download free eBooks at bookboon.com 53 53 53

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

components More CoMponents

The first parameter specifies the text of the label component and the next the width of the component. The other four parameters are for the slider component and the values it must be initialized with. A JSlider is a component that represents an interval of integers defined with setMinimum() and setMaximum(). The component has at any time a value within this range, and it can be defined with setValue(). The two methods setMajorTickSpacing() and setMinorTickSpacing() are used to define a visual partition of the component. The method createColor() returns a JPanel with a BorderLayout containing the label component and the slider. The result is that the sliders size will follow the width of the panel. This method is used by the following method to define three pairs of label and slider:

private JPanel createColors(JSlider sldRed, JSlider sldGreen, JSlider sldBlue, int red, int green, int blue) {TMP PRODUCTION NY026057B 4 12/13/2013 JPanel panel = new JPanel(new GridLayout(1, 3)); ACCCTR00 6x4 PSTANKIE panel.add(createColor("Rød", 40, sldRed, 0, 255, red)); gl/rv/rv/baf panel.add(createColor("Grøn", 50, sldGreen, 0, 255, green)); Bookboon Ad Creative panel.add(createColor("Blå", 40, sldBlue, 0, 255, blue)); return panel; }

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

Download free eBooks at bookboon.com 54

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA WITH GRAPHICAL USER INTERFACE JAVA 2: 2: PROGRAMS PROGRAMS WITH A A JAVA 2: PROGRAMS WITH GRAPHICAL USER INTERFACE JAVA 2: PROGRAMS WITH A A GRAPHICAL USER INTERFACE GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

More components More More CoMponents CoMponents More More CoMponents CoMponents

They are laid out with a GridLayout with 1 row and 3 columns, and each pair will always They are laid out with GridLayout with 1 row and 3 columns, and each pair will always They are laidThe outJSlider with aaacomponents GridLayout with with row and and columns, and each each pair pair will will always always fill theare same. are defined as instance variables: They laid out with GridLayout 111 row 333 columns, and They are laid out with a GridLayout with row and columns, and each pair will always fill fill the the same. same. The The JSlider JSlider components components are are defined defined as as instance instance variables: variables: fill fill the the same. same. The The JSlider JSlider components components are are defined defined as as instance instance variables: variables: private private private private private private private private private private

JSlider JSlider JSlider JSlider JSlider JSlider JSlider JSlider JSlider JSlider

sldRbg sldRbg sldRbg sldRbg sldGbg sldGbg sldGbg sldGbg sldBbg sldBbg sldBbg sldBbg

== = == = == = =

new new new new new new new new new new

JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL);

After that isisthe line for adjusting the background color defined asasfollows: After that the line for adjusting the background color defined After that that is is the the line line for for adjusting adjusting the the background background color color defined defined as as follows: follows: After After that is the line for adjusting the background color defined as follows: follows: private private JPanel JPanel createBg() createBg() private JPanel private JPanel createBg() createBg() {{ { { JPanel JPanel panel panel == new new JPanel(new JPanel(new BorderLayout()); BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(new 0, panel.setBorder(new EmptyBorder(5, EmptyBorder(5, 0, 5, 5, 0)); 0)); panel.setBorder(new EmptyBorder(5, 0, 5, 0)); panel.setBorder(new EmptyBorder(5, 0, 5, 0)); JLabel label = new JLabel("Baggrungsfarve"); JLabel label = new JLabel("Baggrungsfarve"); JLabel label JLabel label = = new new JLabel("Baggrungsfarve"); JLabel("Baggrungsfarve"); label.setPreferredSize(new Dimension(120, label.setPreferredSize(new Dimension(120, 30)); 30)); label.setPreferredSize(new Dimension(120, 30)); label.setPreferredSize(new Dimension(120, 30)); panel.add(label, BorderLayout.WEST); panel.add(label, BorderLayout.WEST); panel.add(label, BorderLayout.WEST); panel.add(label, BorderLayout.WEST); panel.add(createColors(sldRbg, sldGbg, panel.add(createColors(sldRbg, sldGbg, sldBbg, sldBbg, 255, 255, panel.add(createColors(sldRbg, sldGbg, sldBbg, 255, panel.add(createColors(sldRbg, sldGbg, sldBbg, 255, return panel; return panel; return panel; panel; }}return } }

255, 255, 255, 255,

255)); 255)); 255)); 255));

The goal of all this is to ensure that the slider components are resized equally in the line The Thegoal goalofof ofall allthis thisisis istoto toensure ensurethat thatthe theslider slidercomponents componentsare areresized resizedequally equallyinin inthe theline line The goal all this ensure that the slider components are resized equally the line The goal of all this is to ensure that the slider components are resized equally in the line when the window size is changed. when the window size is changed. when the window window size isis changed. changed. when when the the window size size is changed. The line to define the text color is designed in exactly the same way, and will not show The Theline linetoto todefine definethe thetext textcolor colorisis isdesigned designedinin inexactly exactlythe thesame sameway, way,and andIIIIwill willnot notshow show The line define the text color designed exactly the same way, and will not show The line to define the text color is designed in exactly the same way, and I will not show here, but the three slider components are defined instance variables: ititithere, here,but butthe thethree threeslider slidercomponents componentsare aredefined definedasas asinstance instancevariables: variables: it it here, here, but but the the three three slider slider components components are are defined defined as as instance instance variables: variables: private private private private private private private private private private

JSlider JSlider JSlider JSlider JSlider JSlider JSlider JSlider JSlider JSlider

sldRfg sldRfg sldRfg sldRfg sldGfg sldGfg sldGfg sldGfg sldBfg sldBfg sldBfg sldBfg

== = == = == = =

new new new new new new new new new new

JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL); JSlider(JSlider.HORIZONTAL);

Then there is the top toolbar, which is the most complex. It uses the following components, Then there there is is the the top top toolbar, toolbar, which which is is the the most most complex. complex. It It uses uses the the following following components, components, Then Then there is the top toolbar, which is the most complex. It uses the following components, Then there is the top toolbar, which is the most complex. It uses the following components, all of which are defined as instance variables: all of which which are are defined defined as instance instance variables: variables: all all allofof ofwhich whichare aredefined definedasas asinstance instancevariables: variables: private private private private private private private private private private private private private private private private private private private private private private

JComboBox JComboBox lstFont; lstFont; JComboBox lstFont; JComboBox JTextField txtSize JTextFieldlstFont; txtSize == new new JTextField(); JTextField(); JTextField txtSize = new JTextField(); JTextField txtSize = new JTextField(); JCheckBox chkBold = new JCheckBox("Bold"); JCheckBox chkBold = new JCheckBox("Bold"); JCheckBox chkBold = new JCheckBox("Bold"); JCheckBox = = new JCheckBox("Bold"); chkItalic JCheckBox("Italic"); JCheckBox chkBold chkItalic = new new JCheckBox("Italic"); JCheckBox chkItalic = new JCheckBox("Italic"); JCheckBox chkItalic = new JCheckBox("Italic"); JRadioButton cmdLeft = new JRadioButton cmdLeft = new JRadioButton("Left", JRadioButton("Left", true); true); JRadioButton cmdLeft = new JRadioButton("Left", true); JRadioButton cmdLeft = new JRadioButton("Left", true); JRadioButton cmdCenter cmdCenter == new new JRadioButton("Center"); JRadioButton("Center"); JRadioButton cmdCenter = new JRadioButton("Center"); JRadioButton new JRadioButton("Right"); JRadioButton("Center"); cmdRight JRadioButton cmdCenter cmdRight === new new JRadioButton("Right"); JRadioButton cmdRight = new JRadioButton("Right"); JRadioButton cmdRight = new JRadioButton("Right");

Download free eBooks at bookboon.com 55 55 55

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA 2: PROGRAMS WITH A GRAPHICAL USER GRAPHICAL USERINTERFACE INTERFACE GRAPHICAL USER INTERFACE

More Morecomponents CoMponents More CoMponents

The The following following method method creates creates a a JPanel JPanel with with a a BorderLayout BorderLayout containing containing a a JLabel JLabel and and a a The following method creates a JPanel with a BorderLayout containing a JLabel and a JComboBox, JComboBox,and andthe thegoal goalisisthat thatthe thecombo combobox boxmust mustfollow followthe thewidth widthofofthe thewindow: window: JComboBox, and the goal is that the combo box must follow the width of the window: private JPanel createFonts() private JPanel createFonts() { { JPanel panel = new JPanel(new BorderLayout(10, 0)); JPanel panel = new JPanel(new BorderLayout(10, 0)); JLabel label = new JLabel("Fonte"); JLabel label = new JLabel("Fonte"); panel.add(new JLabel("Fonte"), BorderLayout.WEST); panel.add(new JLabel("Fonte"), BorderLayout.WEST); DefaultComboBoxModel model = new DefaultComboBoxModel(); DefaultComboBoxModel model = new DefaultComboBoxModel(); String fonts[] = String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment(). GraphicsEnvironment.getLocalGraphicsEnvironment(). getAvailableFontFamilyNames(); getAvailableFontFamilyNames(); for (int i = 0; i < fonts.length; ++i) model.addElement(fonts[i]); for (int i = 0; i < fonts.length; ++i) model.addElement(fonts[i]); lstFont = new JComboBox(model); lstFont = new JComboBox(model); Font df = label.getFont(); Font df = label.getFont(); for (int n = 0; n < fonts.length; ++n) for (int n = 0; n < fonts.length; ++n) if (df.getFamily().equals(fonts[n])) if (df.getFamily().equals(fonts[n])) { { lstFont.setSelectedIndex(n); lstFont.setSelectedIndex(n); break; break; } } panel.add(lstFont); panel.add(lstFont); chkBold.setSelected(df.isBold()); chkBold.setSelected(df.isBold()); chkItalic.setSelected(df.isItalic()); chkItalic.setSelected(df.isItalic()); txtSize.setText("" + (size = df.getSize())); txtSize.setText("" + (size = df.getSize())); return panel; return panel; } }

After Afterthe thelabel labelcomponent componentisisadded, added,the themethod methodcreates createsa adata datamodel modelfor forthe thecombo combobox. box. After the label component is added, the method creates a data model for the combo box. Next, Next,ananarray arrayofofthe thenames namesofofallallfonts fontsavailable availableon onthe thecurrent currentmachine machineisiscreated, created,and andthis this Next, an array of the names of all fonts available on the current machine is created, and this array arrayisisused usedtotoinitialize initializethe themodel. model.After Afterthe thecombo combobox boxisiscreated createdthe thelabel labelcomponent componentisis array is used to initialize the model. After the combo box is created the label component is used usedtotodetermine determinethe thecurrent currentdefault defaultfont fontfor fora aJLabel, JLabel,and andititisisused usedtotodetermine determinewhich which used to determine the current default font for a JLabel, and it is used to determine which element elementininthe thecombo combobox, box,that thatshould shouldbebeselected. selected.Finally, Finally,the thedefault defaultfont fontisisused usedtoto element in the combo box, that should be selected. Finally, the default font is used to initialize initializethe thetwo twocheck checkboxes boxesand andthe theinput inputfield fieldtotothe thefont fontsize. size. initialize the two check boxes and the input field to the font size. With Withthis thismethod methodininplace, place,the thetoolbar toolbartotofonts fontsare aredefined definedasasfollows: follows: With this method in place, the toolbar to fonts are defined as follows: private JPanel createFont() private JPanel createFont() { { JPanel panel = new JPanel(new BorderLayout(10, 0)); JPanel panel = new JPanel(new BorderLayout(10, 0)); panel.setBorder(new EmptyBorder(5, 0, 5, 0)); panel.setBorder(new EmptyBorder(5, 0, 5, 0)); panel.add(createFonts()); panel.add(createFonts()); JPanel east = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0)); JPanel east = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0)); east.add(new JLabel("Størrelse")); east.add(new JLabel("Størrelse"));

Download free eBooks at bookboon.com 5656 56

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

More components More CoMponents

txtSize.setPreferredSize(new Dimension(40, 25)); east.add(txtSize); east.add(chkBold); east.add(chkItalic); east.add(new JLabel(" | Justering")); ButtonGroup group = new ButtonGroup(); group.add(cmdLeft); group.add(cmdCenter); group.add(cmdRight); east.add(cmdLeft); east.add(cmdCenter); east.add(cmdRight); panel.add(east, BorderLayout.EAST); return panel;

Here is not Here is not createFonts() createFonts()

much new to explain, and the method must mainly insert the panel from much new to explain, and the method must mainly insert the panel from and the remaining components in a BorderLayout. and the remaining components in a BorderLayout.

After the design is completed – after a long road, but wee also talk about a very complex After the design is completed – after a long road, but wee also talk about a very complex design, and by testing you should observe that it is a stable design where the components design, and by testing you should observe that it is a stable design where the components adapts to the window size. adapts to the window size.

The Wake the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

Download free eBooks at bookboon.com 57 57

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

More components More CoMponents

Back Backisisevent eventhandling, handling,and andtotohelp helpwith withthat, that,the theprogram programprovides providesthe thefollowing followingmethods: methods: private Font createNewFont() { boolean bold = chkBold.isSelected(); boolean italic = chkItalic.isSelected(); String name = (String)lstFont.getSelectedItem(); int size = Integer.parseInt(txtSize.getText()); if (bold && italic) return new Font(name, Font.BOLD | Font.ITALIC, size); if (bold) return new Font(name, Font.BOLD, size); if (italic) return new Font(name, Font.ITALIC, size); return new Font(name, Font.PLAIN, size); } private void alignText() { if (cmdLeft.isSelected()) lblText.setHorizontalAlignment(JLabel.LEFT); else if (cmdCenter.isSelected()) lblText. setHorizontalAlignment(JLabel.CENTER); else lblText.setHorizontalAlignment(JLabel.RIGHT); } private void foreground() { lblText.setForeground( new Color(sldRfg.getValue(), sldGfg.getValue(), sldBfg.getValue())); } private void background() { lblText.setBackground( new Color(sldRbg.getValue(), sldGbg.getValue(), sldBbg.getValue())); }

The Thefirst firstcreates createsand andreturns returnsaafont fontbased basedon onthe thesettings settingsselected selectedininthe thetop toptoolbar. toolbar.The Thenext next sets the horizontal alignment of the component lblText corresponding to the radio button sets the horizontal alignment of the component lblText corresponding to the radio button that thatisispressed. pressed.Finally, Finally,the thelast lasttwo twomethods methodsdefines definesthe thecomponent’s component’s(the (thesign’s) sign’s)text textcolor color and background color from the settings for the JSlider components. and background color from the settings for the JSlider components.

Download free eBooks at bookboon.com 58 58

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

More Morecomponents CoMponents

The Thevarious variouscomponents componentscan canfire firean anevent eventwhen whenan anaction actionoccurs, occurs,and andininthe theprevious previousexamples examples I Ihave haveshown shownand andused, used,how howaabutton buttoncan canfire firean anActionEvent ActionEventwhen whenclicked, clicked,and andhow howthis this event eventcan canbe becaught caughtand andhandled handledby byan anActionListener. ActionListener.InInthis thisexample exampleI Iwill willuse usethat that --- AAJTextField JTextFieldcan canfire fireaaFocusEvent, FocusEvent,when whenititget getthe thefocus focus(when (whenthe theuser userselect selectthe the field fieldby bythe thetab tabkey keyororthe themouse), mouse),and andwhen whenititlost lostfocus focus(when (whenthe theuser userleave leavethe the field). field).These Theseevents eventscan canbe becaught caughtwith withaaFocusListener. FocusListener. --- AAJComboBox firing an ActionEvent, when the JComboBox firing an ActionEvent, when theselection selectionisischanged changed(when (whenthe theuser user select selectanother anotherelement), element),that thatcan canbe becaught caughtwith withan anActionListener. ActionListener. --- AAJCheckBox JCheckBoxand andaaJRadioButton JRadioButtonfiring firingaaChangeEvent, ChangeEvent,when whenthe thestate stateisischanged, changed, and andititcan canbe becaught caughtwith withaaChangeListener. ChangeListener. --- AAJSlider fires a ChangeEvent, JSlider fires a ChangeEvent,when whenthe thevalue valueisischanged, changed,and andititcan canbe becaught caught with withaaChangeListener. ChangeListener. With Withthis thisknowledge knowledgethe theevent eventhandlers handlerscan canbe bewritten. written.They Theyare areexcept exceptfor foraasingle singlesimple, simple, and they are written therefore as anonymous classes in method addListeners(): and they are written therefore as anonymous classes in method addListeners(): private void addListeners() { txtText.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { lblText.setText(txtText.getText()); } public void focusGained(FocusEvent e) { } }); txtSize.addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { try { int t = Integer.parseInt(txtSize.getText()); if (t > 5) { lblText.setFont(createNewFont()); return; } } catch (Exception ex) { } txtSize.setText("" + size); }

Download free eBooks at bookboon.com 5959

JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL

MoreCoMponents components More

public void focusGained(FocusEvent e) { size = Integer.parseInt(txtSize.getText()); } }); lstFont.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblText.setFont(createNewFont()); } }); chkBold.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { lblText.setFont(createNewFont()); } }); chkItalic.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { lblText.setFont(createNewFont()); } });

30 FR da EE ys tria

SMS from your computer ...Sync'd with your Android phone & number

l!

Go to

BrowserTexting.com

and start texting from your computer!

...

Download free eBooks at bookboon.com 60 60

BrowserTexting

Click on the ad to read more

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH AA GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

More More components CoMponents

cmdLeft.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { alignText(); } }); cmdCenter.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { alignText(); } }); cmdRight.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { alignText(); } }); sldRfg.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { foreground(); } }); sldGfg.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { foreground(); } }); sldBfg.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { foreground(); } }); sldRbg.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { background(); } }); sldGbg.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { background(); } });

Download free eBooks at bookboon.com 61 61

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

}

More Morecomponents CoMponents

sldBbg.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { background(); } });

There is not much to explain, but you must note that a FocusListener defines two methods, There is not much to explain, but you must note that a FocusListener defines two methods, both to be implemented. You should also note that the event handler to the input field for both to be implemented. You should also note that the event handler to the input field for the font size is relatively complex since it must take into account that the user may enter the font size is relatively complex since it must take into account that the user may enter anything illegal. You are invited to test the program and study the code thoroughly, as the anything illegal. You are invited to test the program and study the code thoroughly, as the example contains much of what is necessary in practice to write a GUI program. example contains much of what is necessary in practice to write a GUI program.

EXERCISE 5 EXERCISE 5 Make a copy of the project CreateSign. You have to expand the layout with a new toolbar Make a copy of the project CreateSign. You have to expand the layout with a new toolbar (see below). The two combo boxes and associated labels and check box must all have a (see below). The two combo boxes and associated labels and check box must all have a fixed size and be placed to the left as shown below. The button must follow the right edge. fixed size and be placed to the left as shown below. The button must follow the right edge. The meaning of the new components are as follows. The first combo box should contain The meaning of the new components are as follows. The first combo box should contain the colors that are defined as constants in the class Color – except for the colors black and the colors that are defined as constants in the class Color – except for the colors black and dark gray. The second combo box should contains the numbers from 3 to 20 inclusive. dark gray. The second combo box should contains the numbers from 3 to 20 inclusive. The 4 black square (screw holes) form the corners of a border around the sign. The two The 4 black square (screw holes) form the corners of a border around the sign. The two combo boxes indicates respectively the color and width of this edge when the width must combo boxes indicates respectively the color and width of this edge when the width must also apply the size of the 4 squares (they must always be black). The check box must be also apply the size of the 4 squares (they must always be black). The check box must be used to specify whether the sign should have a transparent background – only the interior used to specify whether the sign should have a transparent background – only the interior of the sign and not the edge. Finally, the button is used to restore all settings to default – of the sign and not the edge. Finally, the button is used to restore all settings to default – that is, as they were when the program starts. that is, as they were when the program starts. Your first task is to add the new toolbar to the program and thus expand the program Your first task is to add the new toolbar to the program and thus expand the program with the necessary design. You can start by creating the components and then place them with the necessary design. You can start by creating the components and then place them in a panel with a BorderLayout, where the button is placed EAST while the rest of the in a panel with a BorderLayout, where the button is placed EAST while the rest of the components are in a FlowLayout, which then is inserted WEST in the first panel. components are in a FlowLayout, which then is inserted WEST in the first panel. Next, you define event handlers in addListeners() – four in all. The handler for the JCheckBox Next, you define event handlers in addListeners() – four in all. The handler for the JCheckBox component is simple, but there is little problem to getting the component to update itself component is simple, but there is little problem to getting the component to update itself when switching from non-transparent to transparent background: when switching from non-transparent to transparent background:

Download free eBooks at bookboon.com 62 62

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

More components

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com 63

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

More components More CoMponents More CoMponents

public void stateChanged(ChangeEvent e) public void stateChanged(ChangeEvent e) { { lblText.setOpaque(!chkTrans.isSelected()); lblText.setOpaque(!chkTrans.isSelected()); lblText.repaint(); lblText.repaint(); } }

Here is the last statement is required for the changes tototake effect. To change the color Here Here is is the the last last statement statement is is required required for for the the changes changes to take take effect. effect. To To change change the the color color and width ofofthe frame, ititisisnecessary totohave references totothe components that make and width the frame, necessary have references the components that make and width of the frame, it is necessary to have references to the components that make up the frame: The 44black squares and the 44edges. It isiseight in total, and ititisisall JLabel up up the the frame: frame: The The 4 black black squares squares and and the the 4 edges. edges. It It is eight eight in in total, total, and and it is all all JLabel JLabel components. Start therefore by defining 88 instance variables for these components and components. Start therefore by defining instance variables for these components components. Start therefore by defining 8 instance variables for these components and and initialize them totothe respective components when they are created. Then it’s simple totowrite initialize them the respective components when they are created. Then it’s simple write initialize them to the respective components when they are created. Then it’s simple to write aahandler for the first combo box totochange the color – here, only 44ofofthe 8 components a handler handler for for the the first first combo combo box box to change change the the color color – – here, here, only only 4 of the the 8 8 components components must change color. As regards to the final combo box that is used to change the components must change color. As regards to the final combo box that is used to change the must change color. As regards to the final combo box that is used to change the components components preferred size isisaalittle more difficult. The following method can be used totochange the size preferred size little more difficult. The following method can be used change preferred size is a little more difficult. The following method can be used to change the the size size ofofaacomponent (the times that a JLabel ): component (the times that a JLabel ): of a component (the times that a JLabel ): private void resize(JLabel label, int width) private void resize(JLabel label, int width) { { label.setPreferredSize(new Dimension(width, width)); label.setPreferredSize(new Dimension(width, width)); label.doLayout(); label.doLayout(); label.revalidate(); label.revalidate(); } }

Finally, there the button the right. When you click on all settings should return Finally,there thereisis isthe thebutton buttontoto tothe theright. right.When Whenyou youclick clickon onit,it, it,all allsettings settingsshould shouldreturn returnasas as Finally, at program startup and the sign should be displayed as when the program starts. programstartup startupand andthe thesign signshould shouldbe bedisplayed displayedasaswhen whenthe theprogram programstarts. starts. atatprogram

Download free eBooks at bookboon.com 64 64 64

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Layout layout and and the tHe component’s CoMponent’s size sIze

6  6 LAYOUT AND THE COMPONENT’S SIZE As As shown shown in in the the above above examples, examples, aa component’s component’s size size and and location location isis determined determined of of the the so-called so-called layout layout managers, managers, and and the the result result isis not not always always quite quite so so easy easy to to figure figure out. out. In In this this section section II will will explain explain in in part part how how aa component’s component’s size size isis calculated, calculated, and and also also where where itit isis placed placed in in the the window. window. When When there there isis aa lot lot to to tell tell itit isis due due to to aa desire desire that that the the window window and and its its components components should should behave behave sensibly sensibly ifif the the window window size size changes. changes. If, If, for for example example you you consider consider the the above above program program several several of of the the components components change change sizes sizes when when the the window window isis resized, resized, while while others others components components follows follows the the window’s window’s right right edge. edge. ItIt isis controlled controlled by by layout layout managers, managers, which which determines determines how how the the components components of of aa window window or or panel panel are are placed. placed.

6.1 6.1 THE THE COMPONENT’S COMPONENT’S SIZE SIZE AA component component has has aa size size which which isis determined determined by by aa width width and and aa height, height, and and to to define define and and modify modify these these values values aa component component has has four four methods methods ---------

setSize() setSize() setPreferredSize() setPreferredSize() setMinimumSize() setMinimumSize() setMaximumSize() setMaximumSize()

These These methods methods all all have have aa parameter parameter of of the the type type Dimension, Dimension, however, however, the the first first has has an an overloading, overloading, where where the the parameters parameters are are two two int int values. values. The The first first has has only only effect effect ifif the the panel panel isis not not using using aa layout layout manager. manager. In In all all other other cases cases itit isis ignored. ignored. ItIt can can therefore therefore be be used used to to define define the the size size of of the the window, window, because because aa frame frame Window Window does does not not have have aa layout layout manager. manager. In In practice practice are are components components almost almost always always placed placed in in aa panel panel using using one one or or more more layout layout managers, managers, and and here here itit isis the the last last three three methods, methods, which which are are the the interesting. interesting. The The main main rule rule isis that that aa layout layout manager manager will will try try to to customize customize aa component’s component’s size size to to its its preferred preferred size, size, but but the the manager manager will will not not reduce reduce component component size size to to below below its its minimum minimum size size and and not not increase increase the the size size to to more more than than its its maximum maximum size. size. So So there there are are three three sizes sizes attached attached to to aa component, component, but but the the whole whole thing thing isis complicated complicated because because how how these these quantities quantities are are used used are are determined determined by by the the specific specific layout layout manager. manager. As As aa start start isis shown shown below below the the code code for for aa window window with with 66 buttons: buttons: package layoutpanels; import import import import

java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.border.*;

Download free eBooks at bookboon.com 65 65

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Layout layout and and the tHe component’s CoMponent’s size sIze

public class MainView extends JFrame { public MainView() { setTitle("Components and there locations"); setSize(500, 300); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); createWindow(); setVisible(true); } private void createWindow() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 30, 10)); panel.setBorder(new EmptyBorder(20, 20, 20, 20)); panel.add(createButton("BorderLayout", 150, 30, null)); panel.add(createButton("FlowLayout", 120, 40, null)); panel.add(createButton("GridLayout", 150, 30, null)); panel.add(createButton("GridBagLayout", 200, 50, null)); panel.add(createButton("BoxLayout", 150, 30, null)); panel.add(createButton("Null layout", 250, 20, null)); add(panel); }

> Apply now redefine your future

- © Photononstop

AxA globAl grAduAte progrAm 2015

axa_ad_grad_prog_170x115.indd 1

19/12/13 16:36

Download free eBooks at bookboon.com 66 66

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

Layout and the component’s size layout and tHe CoMponent’s sIze

private JButton createButton(String text, int width, int height, ActionListener listener) { JButton cmd = new JButton(text); cmd.addActionListener(listener); cmd.setPreferredSize(new Dimension(width, height)); return cmd; }

You should note the method createButton(), which creates a button with a preferred size. should the notebutton’s the method which creates a buttonis with size. InYou addition, event createButton(), handler is a parameter. The method used ainpreferred createView() addition, the button’s event handler is a parameter. The null, method is used in means createView() toIncreate the buttons, but so far the last parameter is always which simply that to create the buttons, but so far the last parameter is always null, which simply means the button not yet have an event handler, but the meaning is that when you click onthat a the button not yet have an event handler, but the meaning is that when you click on button, it opens another window which illustrates the effect of a layout manager. If youa button, it opens you another window which illustrates the effect of a layout manager. If you run the program, get the following window: run the program, you get the following window:

The method createWindow() creates a panel with a FlowLayout, which is already used several The method createWindow() creates panel with a in FlowLayout, which is already times as a layout manager that placesa components a row from left to right. Isused thereseveral not times as a layout manager that places components in a row from left to right. Is there not enough space, the components continue on the next line, and the component’s size are enough space, the components determined by their preferred size.continue on the next line, and the component’s size are determined by their preferred size.

Download free eBooks at bookboon.com 67 67

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

layout Layout and and tHe the CoMponent’s component’s sIze size

6.2 BORDERLAYOUT 6.2 BORDERLAYOUT If you click on the top button, a window opens, whose code is as follows: package layoutpanels; import java.awt.*; import javax.swing.*; public class BorderlayoutView extends JDialog { public BorderlayoutView() { super(null, "BorderLayout", Dialog.ModalityType.APPLICATION_MODAL); setSize(500, 300); this.setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createWindow(); setVisible(true); } private void createWindow() { setLayout(new BorderLayout(10, 20)); setBackground(Color.lightGray); add(createLabel("North", 0, 30, Color.white, Color.blue), BorderLayout.NORTH); add(createLabel("South", 0, 40, Color.white, Color.red), BorderLayout.SOUTH); add(createLabel("West", 80, 0, Color.black, Color.green), BorderLayout.WEST);

Download free eBooks at bookboon.com 68 68

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

}

Layout and the component’s size layout and tHe CoMponent’s sIze

add(createLabel("East", 100, 0, Color.white, Color.magenta), BorderLayout.EAST); add(createLabel("Center", 0, 0, Color.black, Color.yellow));

private JLabel createLabel(String text, int width, int height, Color color1, Color color2) { JLabel label = new JLabel(text); label.setHorizontalAlignment(JLabel.CENTER); label.setOpaque(true); label.setBackground(color2); label.setForeground(color1); label.setPreferredSize(new Dimension(width, height)); return label; }

LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!

Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.

Download free eBooks at bookboon.com 69 69

Click on the ad to read more

JAVA JAVA2:2: 2:PROGRAMS PROGRAMSWITH WITHAA A JAVA PROGRAMS WITH GRAPHICAL GRAPHICAL USER INTERFACE GRAPHICALUSER USERINTERFACE INTERFACE

Layout layout and tHe CoMponent’s sIze layoutand andthe tHecomponent’s CoMponent’ssize sIze

This Thistime timeititisisnot notaaJFrame JFramewindow, window,but butaadialog dialog––the theclass classinherits inheritsJDialog. JDialog.The Thedialog dialog box boxhas hasaaBorderLayout BorderLayoutwith withfive fiveJLabel JLabelcomponents components

Above AboveI Ihave haveexplained explainedhow howaaBorderLayout BorderLayoutworks, works,and andI Iwill willnot notfurther furthercomments commentson onthat that layout layoutmanager. manager.To Toopen openthe thedialog, dialog,the theMainView MainViewmust musthave havean anevent eventhandler handlerfor forthe thefirst first button buttonand andthere thereisisnothing nothingnew newcompared comparedtotowhat whathas haspreviously previouslybeen beensaid: said: private void border(ActionEvent e) { new BorderlayoutView(); } panel.add(createButton("BorderLayout", 150, 30, this::border));

6.3 FLOWLAYOUT 6.3 FLOWLAYOUT Clicking Clickingthe thesecond secondtop topbutton button(in (inthe theMainView), MainView),you youget getaawindow windowasasshown shownbelow, below,toto illustrate illustratethe theuse useofofaaFlowLayout FlowLayoutmanager: manager: package layoutpaneler; import import import

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

public class FlowlayoutView { public FlowlayoutView() { super(null, "FlowLayout", setSize(500, 300);

extends JDialog

Dialog.ModalityType.APPLICATION_MODAL);

Download free eBooks at bookboon.com 7070 70

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

Layout and the component’s size layout and tHe CoMponent’s sIze

this.setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createWindow(); setVisible(true);

private void createWindow() { setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); for (char c = 'A'; c 0 && price > 0) { if (cmdIncl.isSelected()) price *= 0.8; excl = price * units; vat = excl * 0.25; incl = excl + vat; txtExcl.setText(String.format("%1.2f", excl)); txtVAT.setText(String.format("%1.2f", vat)); txtIncl.setText(String.format("%1.2f", incl)); return; }

}

} catch (Exception ex) { } JOptionPane.showMessageDialog(this, "Illegal value for the number of units or unit price", "Error message", JOptionPane.ERROR_MESSAGE);

private void ok(ActionEvent e) { if (incl > 0) { model.addElement(String.format( "%1.1f units á kr. %1.2f, amount = %1.2f, VAT = %1.2f, total = %1.2f", units, price, excl, vat, incl)); exclSum += excl; vatSum += vat; inclSum += incl; txtExclSum.setText(String.format("%1.2f", exclSum)); txtVATSum.setText(String.format("%1.2f", vatSum)); txtInclSum.setText(String.format("%1.2f", inclSum)); clear(e); } } private void clear(ActionEvent e) { units = price = excl = incl = vat = 0; txtUnits.setText(""); txtPrice.setText(""); txtExcl.setText(""); txtVAT.setText(""); txtIncl.setText(""); txtUnits.requestFocus(); }

Download free eBooks at bookboon.com 83 83

JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

{

}

}

Layout size layout and and the tHe component’s CoMponent’s sIze

private void delete(ActionEvent e) model.clear(); clear(e);

The window contains this time many components: The window contains this time many components: ------

8 8 8 8 2 2 1 1 4 4

label components that are objects of the type JLabel label components that are objects of the type JLabel input fields that are objects of the type JTextField input fields that are objects of the type JTextField radio buttons that are objects of the type JRadioButton radio buttons that are objects of the type JRadioButton list box that is an object of the type JList list box that is an object of the type JList buttons that are objects of the type JButton buttons that are objects of the type JButton

If you start at the top, there is a model for the list box and a ButtonGroup. The last object If you start at the top, there is a model for the list box and a ButtonGroup. The last object should be used for the radio buttons that are attached to a ButtonGroup. This ensures that should be used for the radio buttons that are attached to a ButtonGroup. This ensures that only one radio button can be pressed. Next, are defined the components that you could only one radio button can be pressed. Next, are defined the components that you could refer to in the event handlers. It is the input fields and the two radio buttons (actually only refer to in the event handlers. It is the input fields and the two radio buttons (actually only one of them). Final is defined variables to the values of the input fields. one of them). Final is defined variables to the values of the input fields.

DO YOU WANT TO KNOW:

What your staff really want?

The top issues troubling them?

How to retain your top staff FIND OUT NOW FOR FREE

How to make staff assessments work for you & them, painlessly?

Get your free trial Because happy staff get more done

Download free eBooks at bookboon.com 84 84

Click on the ad to read more

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Layout and the component’s size

The class has several auxiliary methods: -- createLabel() is a simple method that creates a label with a preferred size. -- createField() creates in the same way an input field. It has a parameter that specify where the content can be edited. That is where the field should be used for input or it only should be used to show a value. You should note that the content is right aligned. -- createRadio() is a method that creates a radio button. It has a parameter that tells if the button should be checked, and also the group is a parameter. The group is required, because a window may well have more groups of radio buttons. -- createButton() is a method that creates a button and there are parameters for the text, the size and the event handler. -- createList() creates the list box and encapsulates the list box in a JScrollPane, so you will be able to scroll the content. Furthermore, there is defined four event handlers for the four buttons: 1. calc() is event handler to the button Calculate. When pressing it retrieves the contents of the input fields respectively the number of units and the unit price and converts the values and stored them in the respective variables. If entered legal values, the VAT if necessary pulled out of the unit price, and otherwise the product amounts and VAT are calculated and the corresponding fields are updated. Are the values of the one reason or another illegal, you gets an error message. 2. clear() is event handler to the Clear button, and it clears the input fields and fields to the result and set the variables used for the calculation to zero. 3. ok() is event handler for the OK button. If there is a calculation, the method add a line to the list box for the current item and updates the fields for the totals. The method also call the handler clear() and clears the calculation fields. 4. delete() is event handler to the Delete button and clears the list box. Now there’s the method createWindow(), and that is where it all happens. To add a component the method uses a method called addComponent(). This method creates a GridBagConstraints object and initialize it using parameters. This object is attached to the component, which is then added to the panel. createWindow() creates a JPanel with a GridBagLayout. In order to have a margin the panel is assigned a border, but otherwise the work consists of placing the 23 components in the panel. I will not go through all 23 components, but I’ll look at two as the principle is much the same for all components.

Download free eBooks at bookboon.com 85

JAVA 2: PROGRAMS WITH A JAVA WITH GRAPHICAL USER INTERFACE JAVA 2: 2: PROGRAMS PROGRAMS WITH A A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Layout and the component’s size layout layout and and tHe tHe CoMponent’s CoMponent’s sIze sIze

I’ll start with the second component, which is the input field to the number of units: I’ll I’ll start start with with the the second second component, component, which which is is the the input input field field to to the the number number of of units: units: addComponent(panel, addComponent(panel, txtUnits txtUnits = = createField(120, createField(120, 20, 20, true), true), 2, 2, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, GridBagConstraints.NONE, GridBagConstraints.LINE_START, GridBagConstraints.NONE, GridBagConstraints.LINE_START, new new Insets(0, Insets(0, 0, 0, 20, 20, 20)); 20));

The input field is created with aa suitable preferred size. This has implications for the size The The input input field field is is created created with with a suitable suitable preferred preferred size. size. This This has has implications implications for for the the size size of the cell that contains the component. Then is defined that the cell should be column 2, of the cell that contains the component. Then is defined that the cell should be column of the cell that contains the component. Then is defined that the cell should be column 2, 2, row 0. When itit isis placed in column 2, itit isis because the label component in front og itit isis row 0. When placed in column 2, because the label component in front og row 0. When it is placed in column 2, it is because the label component in front og it is spanning two columns. The next two parameters indicates that this component does not need spanning spanning two two columns. columns. The The next next two two parameters parameters indicates indicates that that this this component component does does not not need need to span the cells other than the cell in which itit isis placed. The next two parameters again, to span the cells other than the cell in which placed. The next two parameters again, to span the cells other than the cell in which it is placed. The next two parameters again, are the weights, and they indicate with the next fill parameter, the size of this component are are the the weights, weights, and and they they indicate indicate with with the the next next fill fill parameter, parameter, the the size size of of this this component component must always be its preferred size. The second last parameter tells that the component must must always be its preferred size. The second last parameter tells that the component must always be its preferred size. The second last parameter tells that the component must must be adjusted to the left side of the cell, and finally the last parameter indicates that there be be adjusted adjusted to to the the left left side side of of the the cell, cell, and and finally finally the the last last parameter parameter indicates indicates that that there there has to be a margin of 20 to the right of and below the component. has to be a margin of 20 to the right of and below the component. has to be a margin of 20 to the right of and below the component. Below is the code that adds the list box: Below Below is is the the code code that that adds adds the the list list box: box: addComponent(panel, addComponent(panel, createList(), createList(), 3, 3, GridBagConstraints.LINE_START, new GridBagConstraints.LINE_START, new

0, 0, 3, 3, 7, 7, Insets(0, Insets(0,

1, 1, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.BOTH, 0, 10, 0, 10, 0)); 0));

placed in column row 0, but should span columns and rows. Next, the weights It isis is placed placed in in column column 33 3 row row 0, 0, but but itit it should should span span 33 3 columns columns and and 77 7 rows. rows. Next, Next, the the weights weights ItIt are set to 1, and it says that the component must use all the available space both horizontally areset setto to1, 1,and andititsays saysthat thatthe thecomponent componentmust mustuse useall allthe theavailable availablespace spaceboth bothhorizontally horizontally are and vertically. At the same time telling the next parameter, the component should fill the and vertically. vertically. At At the the same same time time telling telling the the next next parameter, parameter, the the component component should should fill fill the the and entire cell out both horizontally and vertically, and the result is that the component’s size entire cell cell out out both both horizontally horizontally and and vertically, vertically, and and the the result result isis that that the the component’s component’s size size entire follows the window size. Its preferred size is ignored. The two last parameters tells the follows the the window window size. size. Its Its preferred preferred size size isis ignored. ignored. The The two two last last parameters parameters tells tells the the follows component to be adjusted to the cell’s left edge (ignored in this case, but the method component to to be be adjusted adjusted to to the the cell’s cell’s left left edge edge (ignored (ignored in in this this case, case, but but the the method method component addComponent() requires value), and there must be margin of 10 below the component. addComponent() requires requires aaa value), value), and and there there must must be be aaa margin margin of of 10 10 below below the the component. component. addComponent() As final note to the dialog box, notice that the window in the constructor assigned As aaa final final note note to to the the dialog dialog box, box, notice notice that that the the window window in in the the constructor constructor isis is assigned assigned aaa As minimum size. The reason not to made the window smaller, then the layout manager minimum size. size. The The reason reason isis is not not to to made made the the window window smaller, smaller, then then the the layout layout manager manager minimum can not display the components. can not not display display the the components. components. can

Download free eBooks at bookboon.com 86 86 86

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Layout and the component’s size

If you opens the dialog box and enter values for a few items, the result could be as shown below:

Challenge the way we run

EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…

READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM

1349906_A6_4+0.indd 1

22-08-2014 12:56:57

Download free eBooks at bookboon.com 87

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Layout and the component’s size layout and tHe CoMponent’s sIze

EXERCISE 7 EXERCISE 7 Write a program that you can call Positions that opens a window as shown below: Write a program that you can call Positions that opens a window as shown below:

The user must enter the name and position of a person, and when you click on OK, the The user must enter the name and position of a person, and when you click on OK, the program must inserts a line in the list box. The goal of the exercise is that the window program must inserts a line in the list box. The goal of the exercise is that the window should be designed using a GridBagLayout. The top entry fields must have a fixed size, but should be designed using a GridBagLayout. The top entry fields must have a fixed size, but the list box and the bottom button should follow the window size. the list box and the bottom button should follow the window size. You should first create a simple class that represents a person: You should first create a simple class that represents a person: package positions; public class Person { private String firstname; private String lastname; private String position;

Download free eBooks at bookboon.com 88 88

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

Layout layoutand andthe tHecomponent’s CoMponent’ssize sIze

public Person(String firstname, String lastname, String position) { this.firstname = firstname; this.lastname = lastname; this.position = position; }

}

public String toString() { return firstname + " " + lastname + ", " + position; }

To Tocreate createthe thewindow windowManView ManViewyou youcan cancopy copythe themethod methodaddComponent() addComponent()from fromthe theabove above example, example,and andmaybe maybeititcan canalso alsobe beaagood goodidea ideatotocopy copythe themethods methodscreateLabel(), createLabel(),createField() createField() and andcreateButton(). createButton().Subsequently, Subsequently,the thewindow windowmay maybe bedesigned designedininthe thesame samemanner mannerasasinin the theabove aboveexample. example.I Imay maymention mentionthat thatmy myGridBagLayout GridBagLayouthas hasfive fiverows rowsand andfour fourcolumns. columns.

6.6 BOXLAYOUT 6.6 BOXLAYOUT The Thenext nextlayout layoutmanager managerisisininprinciple principleaavery verysimple simplelayout layoutmanager, manager,but butisisalso alsocomplex, complex, asasthere thereare aremany manyoptions, options,and andititcan canbe bedifficult difficulttotofigure figureout outhow howthe thedifferent differentsettings settings affects affectsthe thelayout. layout.Basically, Basically,ititisisaalayout layoutmanager managerthat thatorganizes organizesits itscomponents componentsininaarow row either horizontally or vertically. Immediately it looks like a FlowLayout, but there are some either horizontally or vertically. Immediately it looks like a FlowLayout, but there are some more morethings thingstotobe beaware awareof. of. When WhenaaBoxLayout BoxLayoutorganize organizecomponents, components,their theirlocation locationand andsize sizewill willbe bedetermined determinedby by ---------

the thecomponent’s component’spreferred preferredsize size the thecomponent’s component’sminimum minimumsize size the thecomponent’s component’smaximum maximumsize size the component’s alignment the component’s alignment

ItItisisbest bestillustrated illustratedthrough throughexamples, examples,and andififyou youclick clickthe thebutton buttonBoxLayout BoxLayoutininthe thedemo demo program, program,you youget getaawindow windowwhere whereyou youcan canopen open11 11examples examples(se (sebelow). below).Here Hereare arethe thefirst first 10 examples virtualy the same, while the latter is a little different. The window’s buttons 10 examples virtualy the same, while the latter is a little different. The window’s buttons isisalso alsolaid laidout outusing usingaaBoxLayout. BoxLayout.You Youare areencouraged encouragedtotorun runthe theprogram programand andsee seewhat what happens happenswith withthe thebuttons buttonswhen whenthe thewindow windowisisresized. resized.Here Hereyou youparticularly particularlyshould shouldnotice notice three threethings: things:

Download free eBooks at bookboon.com 8989

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Layout and the component’s size

This e-book is made with

SETASIGN

SetaPDF

PDF components for PHP developers

www.setasign.com Download free eBooks at bookboon.com 90

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Layout and the component’s size layout and tHe CoMponent’s sIze

1. 1.The Thebuttons buttonsare arelocated locatedcentered centeredininthe thewindow. window.When Whenusing usingaaBoxLayout, BoxLayout,all allthe the container’s components usually have the same aligment as different alignment often container’s components usually have the same aligment as different alignment often leads leadstotounexpected unexpectedresults. results. 2. The component’s sizes 2. The component’s sizesare arenot notchanged, changed,but butisisdefined definedofoftheir theirpreferred preferredsize. size.This This isisbecause becausethey theyhave havethe thesame sameminimum, minimum,maximum maximumand andpreferred preferredsize, size,which whichthen then determines the component’s size. To ensure that a BoxLayout gives the expected determines the component’s size. To ensure that a BoxLayout gives the expected result, result,you youshould shouldalways alwaysspecify specifyall allthree threesizes sizesofofaacomponent. component. 3. The part of the window, which is not occupied by components 3. The part of the window, which is not occupied by componentsisisblank, blank,and andthe theblank blank space space(the (thecomponents componentsare arelaid laidout outininaacolumn) column)isisalways alwaysbelow belowthe thecomponents. components. The Thewindow windowcode codeisisthe thefollowing, following,where whereI Ihave havenot notshown shownthe theevent eventhandlers: handlers: package layoutpanels; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BoxlayoutView extends JDialog { public BoxlayoutView() { super(null, "BoxLayout", Dialog.ModalityType.APPLICATION_MODAL); setSize(300, 330); this.setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createWindow(); setVisible(true); } private void createWindow() { setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(createButton("Example 1", 150, 25, this::box01)); panel.add(createButton("Example 2", 150, 25, this::box02)); panel.add(createButton("Example 3", 150, 25, this::box03)); panel.add(createButton("Example 4", 150, 25, this::box04)); panel.add(createButton("Example 5", 150, 25, this::box05)); panel.add(createButton("Example 6", 150, 25, this::box06)); panel.add(createButton("Example 7", 150, 25, this::box07)); panel.add(createButton("Example 8", 150, 25, this::box08)); panel.add(createButton("Example 9", 150, 25, this::box09));

Download free eBooks at bookboon.com 91 91

JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL

layoutand andthe tHecomponent’s CoMponent’ssize sIze Layout layoutand andtHe tHeCoMponent’s CoMponent’ssIze sIze layout

panel.add(createButton("Example panel.add(createButton("Example panel.add(createButton("Example panel.add(createButton("Example panel.add(createButton("Example panel.add(createButton("Example add(panel); add(panel); add(panel); } }}

10", 10", 10", 11", 11", 11",

150, 150, 150, 150, 150, 150,

25, 25, 25, 25, 25, 25,

this::box10)); this::box10)); this::box10)); this::box11)); this::box11)); this::box11));

private JButton createButton(String text, int width, int height, private JButton JButton createButton(String createButton(String text, text, int int width, width, int int height, height, private ActionListener listener) ActionListener listener) listener) ActionListener { {{ JButton cmd = new JButton(text); JButton cmd cmd == new new JButton(text); JButton(text); JButton cmd.setPreferredSize(new Dimension(width, height)); cmd.setPreferredSize(new Dimension(width, Dimension(width, height)); height)); cmd.setPreferredSize(new cmd.setMinimumSize(new Dimension(width, height)); cmd.setMinimumSize(new Dimension(width, Dimension(width, height)); height)); cmd.setMinimumSize(new cmd.setMaximumSize(new Dimension(width, height)); cmd.setMaximumSize(new Dimension(width, Dimension(width, height)); height)); cmd.setMaximumSize(new cmd.setAlignmentX(Component.CENTER_ALIGNMENT); cmd.setAlignmentX(Component.CENTER_ALIGNMENT); cmd.setAlignmentX(Component.CENTER_ALIGNMENT); cmd.addActionListener(listener); cmd.addActionListener(listener); cmd.addActionListener(listener); return cmd; return cmd; cmd; return } }} } }}

You must primarily note how, the method createWindow() defines BoxLayout, and how that You Youmust mustprimarily primarilynote notehow, how,the themethod methodcreateWindow() createWindow()defines definesaaaaBoxLayout, BoxLayout,and andhow howthat that You must primarily note how, the method createWindow() defines BoxLayout, and how that BoxLayout.Y_AXIS BoxLayout.Y_AXIS BoxLayout.Y_AXIS

indicates that the components must be laid out in column. Note also that BoxLayout indicates indicatesthat thatthe thecomponents componentsmust mustbe belaid laidout outin inaaaacolumn. column.Note Notealso alsothat thataaaaBoxLayout BoxLayout indicates that the components must be laid out in column. Note also that BoxLayout is defined slightly differently than the other layout managers. Furthermore, note how the isisisdefined definedslightly slightlydifferently differentlythan thanthe theother otherlayout layoutmanagers. managers.Furthermore, Furthermore,note notehow howthe the defined slightly differently than the other layout managers. Furthermore, note how the method createButton() defines the alignment of the individual components: method createButton() defines the alignment of the individual components: method createButton() createButton() defines defines the the alignment alignment of of the the individual individual components: components: method cmd.setAlignmentX(Component.CENTER_ALIGNMENT); cmd.setAlignmentX(Component.CENTER_ALIGNMENT); cmd.setAlignmentX(Component.CENTER_ALIGNMENT);

that means horizontal alignment. The parameter constant of the type float and has that thatmeans meansaaaahorizontal horizontalalignment. alignment.The Theparameter parameterisisis isaaaaconstant constantof ofthe thetype typefloat floatand andhas hasaaaa that means horizontal alignment. The parameter constant of the type float and has value between and 1. The value indicated the degree to which the component must be value valuebetween between000 0and and1. 1.The Thevalue valueindicated indicatedthe thedegree degreeto towhich whichthe thecomponent componentmust mustbe be value between and 1. The value indicated the degree to which the component must be aligned from left to right, and there is defined the following constants: aligned alignedfrom fromleft leftto toright, right,and andthere thereisisisdefined definedthe thefollowing followingconstants: constants: aligned from left to right, and there defined the following constants: Component.LEFT_ALIGNMENT 000 0=== =Component.LEFT_ALIGNMENT Component.LEFT_ALIGNMENT Component.LEFT_ALIGNMENT 0.5 = Component.CENTER_ALIGNMENT 0.5 = 0.5 ==Component.CENTER_ALIGNMENT Component.CENTER_ALIGNMENT 0.5 Component.CENTER_ALIGNMENT 1 = Component.RIGHT_ALIGNMENT 111===Component.RIGHT_ALIGNMENT Component.RIGHT_ALIGNMENT Component.RIGHT_ALIGNMENT you open Example you get the window shown below. The window shows three JLabel IfIfIf Ifyou youopen openExample Example111 1you youget getthe thewindow windowshown shownbelow. below.The Thewindow windowshows showsthree threeJLabel JLabel you open Example you get the window shown below. The window shows three JLabel components that are laid out in a column by a BoxLayout. When you test this example, components that are laid out in a column by a BoxLayout. When you test this example, components that that are are laid laid out out in in aa column column by by aa BoxLayout. BoxLayout. When When you you test test this this example, example, components you need to observe what happens to the components when the window is resized. The you youneed needto toobserve observewhat whathappens happensto tothe thecomponents componentswhen whenthe thewindow windowisisisresized. resized.The The you need to observe what happens to the components when the window resized. The components changes to their maximum size and are compressed to their minimum size, components changes to their maximum size and are compressed to their minimum size, components changes changes to to their their maximum maximum size size and and are are compressed compressed to to their their minimum minimum size, size, components and finally you should note that they are adjusted with the left edge. and finally you should note that they are adjusted with the left edge. and finally finally you you should should note note that that they they are are adjusted adjusted with with the the left left edge. edge. and

Download free eBooks at bookboon.com 92 92 92 92

Deloitte & Touche LLP and affiliated entities.

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Layout and the component’s size

360° thinking

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download

Click on the ad to read more

93

Dis

JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

Layout and and tHe the CoMponent’s component’s sIze size layout

The code code is is as as follows, follows, which which requires requires no no further further explanation: explanation: The package layoutpanels; import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class Box01View extends JDialog { public Box01View() { super(null, "BoxLayout", Dialog.ModalityType.MODELESS); setSize(400, 400); this.setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createWindow(); setVisible(true); } private void createWindow() { setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.add(createLabel(100, 50, Color.red)); panel.add(createLabel(150, 75, Color.green)); panel.add(createLabel(200, 100, Color.blue)); add(panel); }

}

private JLabel createLabel(int width, int height, Color color) { JLabel label = new JLabel(); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setOpaque(true); label.setBackground(color); label.setPreferredSize(new Dimension(width, height)); label.setMinimumSize(new Dimension(width / 2, height / 2)); label.setMaximumSize(new Dimension(width * 2, height * 2)); return label; }

Download free eBooks at bookboon.com 94 94

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Layout and the component’s size layout and tHe CoMponent’s sIze

The following 9 examples are substantially identical to the above, and shows the same three The following 9 examples are substantially identical to the above, and shows the same three components. The difference is how the components are adjusted, and whether they are laid components. The difference is how the components are adjusted, and whether they are laid out vertically or horizontally. I will not show these examples here, but you should open the out vertically or horizontally. I will not show these examples here, but you should open the dialog boxes to see what is happening. dialog boxes to see what is happening. Generally a BoxLayout does not inserts gaps between the components, but it is possible to Generally a BoxLayout does not inserts gaps between the components, but it is possible to add no visual components, and I will as an example to explain Example 10. If you opens add no visual components, and I will as an example to explain Example 10. If you opens the dialog box, you get the following window: the dialog box, you get the following window:

where the components this time is laid out horizontally. Between the first two components, where the components this time is laid out horizontally. Between the first two components, has been added an invisible component of width 10, while there between the two last has been added an invisible component of width 10, while there between the two last components is inserted a gap that fills the part of the panel that are not used. The components components is inserted a gap that fills the part of the panel that are not used. The components height is as previously limited by their maximum height, and the width is their preferred height is as previously limited by their maximum height, and the width is their preferred width. The code is as follows: width. The code is as follows: package layoutpaneler; import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class Box10View extends JDialog { public Box10View() { super(null, "BoxLayout", Dialog.ModalityType.MODELESS); setSize(600, 200); this.setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createWindow(); setVisible(true); }

Download free eBooks at bookboon.com 95 95

JAVA2:2:PROGRAMS PROGRAMSWITH WITHA A JAVA GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL

Layoutand andtHe theCoMponent’s component’ssIze size layout

private void createWindow() { setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.add(createLabel(100, 50, Color.red)); panel.add(Box.createRigidArea(new Dimension(10, 0))); panel.add(createLabel(150, 75, Color.green)); panel.add(Box.createHorizontalGlue()); panel.add(createLabel(200, 100, Color.blue)); add(panel); }

private JLabel createLabel(int width, int height, Color color) { JLabel label = new JLabel(); NY026057B 4 TMP PRODUCTION 12/13/2013 label.setAlignmentY(Component.TOP_ALIGNMENT); ACCCTR00 6x4 PSTANKIE label.setOpaque(true); gl/rv/rv/baf Bookboon Ad Creative label.setBackground(color); label.setPreferredSize(new Dimension(width, height)); label.setMinimumSize(new Dimension(width / 2, height / 2));

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

Download free eBooks at bookboon.com 9696

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

}

Layout and the component’s size layout and tHe CoMponent’s sIze

label.setMaximumSize(new Dimension(width * 2, height * 2)); return label;

which whichisisalmost almostidentical identicaltotothe theprevious previousexample, example,but butyou youshould shouldnote notehow howthe thecreateWindow() createWindow() inserts spaces between the components. The important thing about this example inserts spaces between the components. The important thing about this exampleisisthat thatthe the blue bluelabel labelfollows followsthe thewindow’s window’sright rightedge. edge. Finally, Finally,the thelast lastexample example(Example (Example11), 11),which whichopens opensthe thefollowing followingdialog dialogbox: box:

The Thewindow windowplaces placesthree threecomponents componentswith withaaBoxLayout: BoxLayout: 1. 1.aaJLabel JLabel 2. a JScrollPane 2. a JScrollPanewith withaalist listbox box 3. 3.aaJPanel JPanelwith withtwo twobuttons buttons You Youshould shouldstudy studythe thecode codeand andsee seewhat whathappens happenswhen whenthe thewindow windowisisresized. resized.

EXERCISE EXERCISE88 You Youmust mustwrite writeaaprogram programthat thatyou youcan cancall callBoxes. Boxes.The Theprogram programshould shouldopen openaawindow windowasas shown shownbelow, below,that thatshows shows12 12JLabel JLabelcomponents componentsinindifferent differentcolors. colors.The Theprogram programdo donot not perform anything and there should be no event handling. perform anything and there should be no event handling.

Download free eBooks at bookboon.com 97 97

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Layout and the component’s size layout and tHe CoMponent’s sIze

The The design design isis aa panel panel with with aa BoxLayout BoxLayout that that containts containts two two other other panels panels with with aa BoxLayout BoxLayout (a left and a right). In addition, apply the following (a left and a right). In addition, apply the following -------

The The components components must must have have aa fixed fixed size. size. Vertical between the components there Vertical between the components there must must be be aa gap gap of of 5. 5. When the window is resized, the 6 components to the right must When the window is resized, the 6 components to the right mustfollow followthe thewindow’s window’s right edge, while the 6 lower components must follow the window’s bottom right edge, while the 6 lower components must follow the window’s bottom edge. edge.

6.7 6.7 NULL NULL LAYOUT LAYOUT Above Above II have have mentioned mentioned the the most most important important of of Java’s Java’s layout layout managers, managers, but but itit isis actually actually possible to place components in a window without using a layout manager. If, possible to place components in a window without using a layout manager. If, in in the the demo program you clicks the button Null layout, you get the following dialog, that has demo program you clicks the button Null layout, you get the following dialog, that has six six components (the buttons have no function) components (the buttons have no function) package layoutpanels; import java.awt.*; import javax.swing.*;

Download free eBooks at bookboon.com 98 98

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Layout and the component’s size layout and tHe CoMponent’s sIze

public class NulllayoutView extends JDialog { public NulllayoutView() { super(null, "Null Layout", Dialog.ModalityType.MODELESS); setSize(340, 200); setResizable(false); this.setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); createWindow(); setVisible(true); } private void createWindow() { setLayout(null); addComponent(this, new JLabel("Zip code"), 20, 20, 100, 20); addComponent(this, new JLabel("Town"), 20, 60, 100, 20); addComponent(this, new JTextField(), 100, 20, 50, 20); addComponent(this, new JTextField(), 100, 60, 220, 20); addComponent(this, new JButton("Cancel"), 230, 110, 90, 24); addComponent(this, new JButton("OK"), 120, 110, 90, 24); }

The Wake the only emission we want to leave behind

.QYURGGF'PIKPGU/GFKWOURGGF'PIKPGU6WTDQEJCTIGTU2TQRGNNGTU2TQRWNUKQP2CEMCIGU2TKOG5GTX 6JGFGUKIPQHGEQHTKGPFN[OCTKPGRQYGTCPFRTQRWNUKQPUQNWVKQPUKUETWEKCNHQT/#0&KGUGN6WTDQ 2QYGTEQORGVGPEKGUCTGQHHGTGFYKVJVJGYQTNFoUNCTIGUVGPIKPGRTQITCOOGsJCXKPIQWVRWVUURCPPKPI HTQOVQM9RGTGPIKPG)GVWRHTQPV (KPFQWVOQTGCVYYYOCPFKGUGNVWTDQEQO

Download free eBooks at bookboon.com 99 99

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE

}

Layout layoutand andthe tHecomponent’s CoMponent’ssize sIze

private void addComponent(Container container, Component component, int left, int top, int width, int height) { component.setBounds(left, top, width, height); container.add(component); }

Thefirst firststatement statementinincreateWindow() createWindow()sets setsthe thelayout layoutmanager managertotonull, null,which whichmeans meansthe thewindow window The hasno nolayout layoutmanager. manager.Then Thenthe themethod methodadds addscomponents componentsusing usingthe themethod methodaddComponent(). addComponent(). has definesthe thecomponents componentssize sizeand andlocation locationwith withthe themethod methodsetBounds() setBounds()where wherethe thetwo twofirst first ItItdefines parametersare arethe theupper upperleft leftcorner cornerofofthe thecomponent’s component’slocation locationininthe thepanel, panel,while whilethe thetwo two parameters lastparameters parametersare arethe thewidth widthand andheight. height.That Thatis,is,the thecomponent componentisisassigned assignedan anabsolute absolute last positionand andsize. size.These Thesevalues valuescan canalso alsobe beassigned assignedwith withsetLocation() setLocation()and andsetSize(). setSize(). position Immediatelyabove aboveworks workssimple, simple,but butiningeneral generalititisisadvisable advisabletotouse useaalayout layoutmanager, manager,asas Immediately thecomponent’s component’ssizes sizescan caninvolve involvefor forexample examplethe thecurrent currentfont. font.IfIfyou youuse useaaparticular particularfont, font, the andthe thewindow windowsize sizedoes doesnot notchange change(note (notethat thatthis thisisisnot notpossible possibleininthe theabove aboveexample), example), and theuse useofofcomponents componentsatatfixed fixedpositions, positions,however howeverisisaapossibility. possibility. the

PROBLEM11 PROBLEM Youmust mustwrite writeaaprogram programthat thatisisaaloan loancalculation calculationprogram programand andthus thusaaprogram programwhere wherethe the You usercan canenter enterthe theamount amountofofaaloan, loan,the theinterest interestrate rateand andnumber numberofofperidos. peridos.The Theprogram program user shouldthen thencalculate calculatethe thepayment paymentwhen whenthe theloan loanisisan anannuity. annuity.ItItshould shouldbe bementioned mentioned should thatthere thereare aremany manysuch suchprograms programson onthe theInternet Internetthat thatyou youcan cancompare comparethe theresult resultwith. with. that Anannuity annuityisisaaloan loanthat thatisisamortized amortizedwith withaafixed fixedpayment paymenteach eachperiod. period.AApayment paymentconsist consist An interestand andrepayment repaymentand andininthe thebeginning beginningisisaabig bigpart partofofthe thepayment paymentinterest interestand andaa ofofinterest smallerpart partisisrepayment. repayment.This Thissituation situationisischanging changingcontinuously, continuously,sosothat thattowards towardsthe theend end smaller theloan loanperiod, period,the thelargest largestpart partofofthe thepayment paymentisisrepayment. repayment.IfIf ofofthe ---------

theloan loan GG==the thepayment payment yy==the numberofofperiods periods nn==number interestrate rate r r==interest

Download free eBooks at bookboon.com 100 100

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Layout and the component’s size

the relationship between the loan and the payment is given by the following formula:

This formula assumes that the interest rate is constant throughout the loan period and the first payment must take place 1 period after you got the loan, and you should assume that these assumptions apply. The following formula determines the outstanding debt immediately after the kth payment is paid:

The program must open a window where the user must enter: ------

cost of loan formation the size of the loan the interest rate in percent pro ano the repayment period in years number of periods a year

Using this information, the program must calculate the payment. In addition, it should be possible to open a window that shows an amortization, and thus an overview of the loan that for each period shows the payment, the interest, the repayment and the debt outstanding after this date.

6.8 MVC When you study my solution of the above problem, primarily focusing on the program’s architecture and the classes that are used. The program can be written differently – and simpler – but the chosen architecture is a step toward a design pattern for a GUI program that is called for MVC for Model View Controller. In the book Java 7 I will return to this pattern, and although the pattern is first treated in this book, I will already start to use it. The pattern is very simple and means to develop a GUI program with a three-layer architecture

Download free eBooks at bookboon.com 101

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Layout and the component’s size

where the model consists of the classes that defines the program’s data and state, while controller layer has classes who mainly perform control of entries etc. and optionally also has essential calculation functions (business logic). Finally, the view layer has all the classes for the user interface and thus for windows and dialogs. The goal of the pattern is to separate the code so that the code regarding the program’s data are placed in classes in the model and code used for data control and logical operations are placed in the control layer, whereas the view layer alone must contain the code which has to do with the visual representation and user interaction. Conforms to the pattern you get a code which might be a bit bigger, but in return is far easier to read and understand. I will in the following books when there is slightly larger programs begin using the pattern, and so far it is only a question of the division of the program’s classes in logical layers, and although it does not sound like much, the pattern has proved very appropriate as architecture for a GUI program. Therefore, I would in a small way begin using the pattern only as a way to a reasonable division of the code. There is much more to say about MVC, and including how each layer should communicate with the others, and there may also be several layers, but the details I’ll defer to the book Java 7.

30 FR da EE ys tria

SMS from your computer ...Sync'd with your Android phone & number

l!

Go to

BrowserTexting.com

and start texting from your computer!

...

Download free eBooks at bookboon.com 102

BrowserTexting

Click on the ad to read more

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Paedit paedIt

7 PAEDIT 7 PAEDIT In In this this chapter chapter II will will show show aa program program that that is is aa simple simple text text editor editor and and thus thus aa program program where where the the user user can can enter enter text text and and save save the the text text in in aa file. file. The The program program is is relatively relatively simple simple and and has has only only aa single single window. window. The The layout layout is is solved solved with with aa single single BorderLayout, BorderLayout, and and concerning concerning GUI GUI programs programs the the program program mainly mainly shows shows the the following: following: -----------

how how to to create create and and use use aa menu menu how how to to create create and and use use aa toolbar toolbar how how to to use use aa JTextArea JTextArea component component how how to to use use finished finished dialog dialog boxes boxes from from the the Swing Swing API API how how to to use use the the clipboard clipboard

Regarding Regarding point point 44 II have have previously previously shown shown the the use use of of JOptionPane.showMessageDialog(), JOptionPane.showMessageDialog(), but but the the class class JOptionPane JOptionPane has has other other dialog dialog boxes boxes that that II will will use. use. Moreover, Moreover, II shows shows the the use use of of the the class class JFileChooser JFileChooser that that implements implements aa dialog dialog box box for for browsing browsing the the file file system. system. The The program program requires requires that that you you can can read read and and write write aa text text file, file, and and in in the the book book Java Java 11 II explained explained how how to to do do that. that. In In fact, fact, the the program program does does not not very very much much concerning concerning algorithms algorithms and and thus thus problem problem solving, solving, so so most most of of the the program program deals deals with with how how to to write write text text to to aa file file and and read read text text from from aa file, file, and and it’s it’s something something you you just just have have to to take take note note of, of, but but behind behind itit all, all, there there are are many many details details that that II first first are are able able to to explain explain at at aa later later time. time. Similar Similar to to what what is is said said above, above, the the program program has has aa very very simple simple architecture, architecture, consisting consisting of of aa view view and and aa model, model, and and by by far far most most of of the the program’s program’s code code is is in in the the view. view. The The program program has has aa 2-tier 2-tier architecture. architecture.

7.1 7.1 THE THE MODEL MODEL The The model model consists consists only only of of aa single single class, class, called called Document, Document, which which encapsulates encapsulates aa text text file, file, and and thus thus represents represents the the document document that that the the program program must must be be able able to to edit. edit. The The class class is is written written as as follows: follows: package paedit; import java.io.*; public class Document { private String text; private File file;

// the documents text // object that represents the document's file

Download free eBooks at bookboon.com 103 103

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Paedit paedIt

public Document() { text = ""; file = null; } public Document(File file) throws Exception { BufferedReader reader = null; try { StringBuilder builder = new StringBuilder(); reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { builder.append(line); builder.append("\n"); } text = builder.toString(); this.file = file; } catch (Exception ex) { text = ""; this.file = null; throw new Exception("The content of the file could not be read"); } finally { if (reader != null) reader.close(); } } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean save() { if (file == null) return false; else return save(file); }

Download free eBooks at bookboon.com 104 104

JAVA2:2:PROGRAMS PROGRAMSWITH WITHA A JAVA GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL

{

Paedit paedIt

public boolean save(File file) BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); writer.write(text); this.file = file; return true; } catch (Exception ex) { return false; } finally { if (writer != null) try { writer.close(); }

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

Download free eBooks at bookboon.com 105 105

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

}

}

Paedit paedIt

catch (Exception ex) { }

There are two variables, the first being for the text, while the other represents a file, and is a File object that represents a file path. The default constructor creates a blank document, not yet saved and associated with a file. The other constructor has a parameter that is a File object, and the constructor trys to read the contents of this file as a text. Most methods concerning files can raise exceptions, as there may be many reasons why a particular file operation can not be performed properly. As an example it may be that the file does not exist, or that you may not have the right to open it. Therefore, statements regarding files almost always are placed in try/catch blocks. In this case raises the constructor an exception if the content of the file for one reason or another can not be read. A text file can be read with a BufferedReader, an object that reads the file line by line. As the lines are reading the are added to a StringBuilder, which is used to build up the document. If an error occurs, the constructor go to the catch block, and the result is again a blank document. The method save() trys to save the content (the document) in a file, but this is only possible if the variable file refers to a file. If it does not, the method returns false. Otherwise the method calls another save() method but with a File as a parameter. It looks like the constructor, and you write the text to a file using a BufferedWriter. The text is saved with the method write(), that saves all the text as a whole and also all the line breaks. Note that the class also has get and set methods for variable text, such the program’s view can read the text and update it again.

7.2 THE VIEW 7.2 The program’s view layer has two classes that is the class MainView and a class Tools. The last is a simple class that contains a few tools that can also be interested in other programs. If you executes the program, it opens a window as shown below, where there at the top is a menu and a toolbar and in the bottom a status line (is empty when the program starts). Center is a JTextArea component, that is an input field like a JTextField, but a field where you can enter more lines.

Download free eBooks at bookboon.com 106 106

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH AA GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Paedit paedIt

THE THE CLASS CLASS TOOLS TOOLS

The The program program has has aa class class Tools Tools that that has has only only static static members, members, which which means means that that the the members members can be refered without an object of the type Tools: can be refered without an object of the type Tools: package paedit; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Tools { public static Font defFont = new Font("Liberation Sans", Font.PLAIN, 14); public static Font txtFont = new Font("FreeMono", Font.PLAIN, 16); public static Color statusLine = new Color(240, 240, 240); public static ImageIcon createImageIcon(String path, int width) { java.net.URL imgURL = Tools.class.getResource(path); if (imgURL != null) return new ImageIcon( new ImageIcon(imgURL, "").getImage().getScaledInstance( width, width, Image.SCALE_SMOOTH), ""); return null; }

Download free eBooks at bookboon.com 107 107

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

}

Paedit paedIt

public static JButton createCommand(Icon icon, String toolTip, ActionListener listener) { JButton cmd = new JButton(); cmd.setFont(defFont); cmd.setIcon(icon); cmd.setMargin(new Insets(0, 0, 0, 0)); cmd.setToolTipText(toolTip); cmd.addActionListener(listener); return cmd; }

Initially are defined three constants where the first two defines the font to respectively default and buttons. The third defines the color of the status bar. In many contexts you must desire to control the fonts and colors, a window must apply, and it is recommended to define that kind of values as constants, as shown above, since in this way you can easily change the values, and as such you can also use them in multiple windows.

> Apply now redefine your future

- © Photononstop

AxA globAl grAduAte progrAm 2015

axa_ad_grad_prog_170x115.indd 1

19/12/13 16:36

Download free eBooks at bookboon.com 108 108

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Paedit paedIt

The class also has two methods, which are difficult to understand (again because you still The class also has two methods, which are difficult to understand (again because you still lack many Java details), so you should largely accept them as they are. The first is used to lack many Java details), so you should largely accept them as they are. The first is used to load an icon from the application’s jar file. The two parameters are the image name and load an icon from the application’s jar file. The two parameters are the image name and the icon size. The first statement defines a reference to the image in the jar file, while the the icon size. The first statement defines a reference to the image in the jar file, while the next statement creates an icon and scale it to the desired size. The last method creates a next statement creates an icon and scale it to the desired size. The last method creates a button with an icon and associate an event handler for the button. In addition a tooltip button with an icon and associate an event handler for the button. In addition a tooltip is added to the button. is added to the button. THE MENU THE MENU

It is easy to add a menu to a window. A menu is basically just a collection of buttons, just It is easy to add a menu to a window. A menu is basically just a collection of buttons, just shown in a different way as a menu item, but the effect is the same, that you can click on shown in a different way as a menu item, but the effect is the same, that you can click on a menu item and the item sends an ActionEvent. The menu must be defined, and it can fill a menu item and the item sends an ActionEvent. The menu must be defined, and it can fill a lot, but below shows how the menu is defined i MainView in this case: a lot, but below shows how the menu is defined i MainView in this case: private void createMenu() { JMenuBar menuBar = new JMenuBar(); menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); setJMenuBar(menuBar); } private JMenu createFileMenu() { JMenu menu = new JMenu("Files"); menu.add(createMenuItem("New document", this::blank)); menu.add(createMenuItem("Open document", this::open)); menu.add(createMenuItem("Savve document", this::save)); menu.add(createMenuItem("Save document as", this::saveas)); menu.addSeparator(); menu.add(createMenuItem("Exit", this::close)); return menu; } private JMenu createEditMenu() { JMenu menu = new JMenu("Edit"); menu.add(createMenuItem("Copy", this::copy)); menu.add(createMenuItem("Paste", this::paste)); menu.add(createMenuItem("Cut", this::cut)); menu.addSeparator(); menu.add(createMenuItem("Search", this::search)); return menu; }

Download free eBooks at bookboon.com 109 109

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA 2: PROGRAMS WITH A GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL USER INTERFACE

Paedit paedIt paedIt

private private JMenuItem JMenuItem createMenuItem(String createMenuItem(String text, text, ActionListener ActionListener listener) listener) {{ JMenuItem JMenuItem item item == new new JMenuItem(text); JMenuItem(text); item.addActionListener(listener); item.addActionListener(listener); return return item; item; }}

principle, the code quite simple and easy understand. There are three components. InIn Inprinciple, principle,the thecode codeisis isquite quitesimple simpleand andeasy easyofof ofunderstand. understand.There Thereare arethree threecomponents. components. The menu is a JMenuBar which is a component, that contains the menu and can be added The menu is a JMenuBar which is a component, that contains the menu and can The menu is a JMenuBar which is a component, that contains the menu and canbe beadded added to the window and automatically is placed at the top of the window. The JMenuBar totothe thewindow windowand andautomatically automaticallyisisplaced placedatatthe thetop topofofthe thewindow. window.The TheJMenuBar JMenuBarisis is added to the window with the method setJMenuBar(). The second component is JMenu added addedtotothe thewindow windowwith withthe themethod methodsetJMenuBar(). setJMenuBar().The Thesecond secondcomponent componentisisJMenu JMenu and represents a menu, while the last is JMenuItem and represents a menu item. You should and represents a menu, while the last is JMenuItem and represents a menu item. You should and represents a menu, while the last is JMenuItem and represents a menu item. You should note that you assign listener quite the same way you assign listener button. The note notethat thatyou youassign assignaaalistener listenerinin inquite quitethe thesame sameway wayyou youassign assignaaalistener listenertoto toaaabutton. button.The The individual event handlers are written at the end of the class. individual individualevent eventhandlers handlersare arewritten writtenatatthe theend endofofthe theclass. class. THE TOOLBAR THE THETOOLBAR TOOLBAR

The program’s window has toolbar that merely container that can contains components. The Theprogram’s program’swindow windowhas hasaaatoolbar toolbarthat thatisis ismerely merelyaaacontainer containerthat thatcan cancontains containscomponents. components. this case, there are four buttons, but the buttons are this time not represented by text, InIn this case, there are four buttons, but the buttons are this time not represented In this case, there are four buttons, but the buttons are this time not representedby byaaatext, text, but an image. but an image. but an image. Each these controls include an image (an icon), which must be available for the Each Eachofof ofthese thesecontrols controlsinclude includean animage image(an (anicon), icon),which whichmust mustbe beavailable availablefor forthe the program. This can be done in several ways, but if, as here it are small icons, you can use program. This can be done in several ways, but if, as here it are small icons, you can use program. This can be done in several ways, but if, as here it are small icons, you can use the following procedure: the thefollowing followingprocedure: procedure: 1. add package the NetBeans project this case sub package paedit 1. 1.add addpackage packagetoto tothe theNetBeans NetBeansproject project–––inin inthis thiscase caseitititisis isaaasub subpackage packagetoto topaedit paedit called images, and after you creates the package the name is paedit.images called images, and after you creates the package the name is paedit.images called images, and after you creates the package the name is paedit.images 2. copy the images the corresponding folder (the folder images has this case 2. copy 2. copythe theimages imagestoto tothe thecorresponding correspondingfolder folder(the (thefolder folderimages imageshas hasinin inthis thiscase caseisis is 4 png files) 44png pngfiles) files) The advantage this method that the icons are packed together with the class files The Theadvantage advantageofof ofthis thismethod methodisis isthat thatthe theicons iconsare arepacked packedtogether togetherwith withthe theclass classfiles filesinin in the project’s jar file. the project’s jar file. the project’s jar file. Then there the toolbar, which defined follows: Then Thenthere thereisis isthe thetoolbar, toolbar,which whichisis isdefined definedasas asfollows: follows: private private JToolBar JToolBar createToolbar() createToolbar() {{ JToolBar JToolBar toolBar toolBar == new new JToolBar(); JToolBar(); toolBar.setBackground(Tools.statusLine); toolBar.setBackground(Tools.statusLine); toolBar.add(Tools.createCommand( toolBar.add(Tools.createCommand( Tools.createImageIcon("/paedit/images/copy.png", Tools.createImageIcon("/paedit/images/copy.png", 26), 26), "Copy "Copy text text to to the the clip clip board", board", this::copy this::copy )); )); toolBar.addSeparator(new toolBar.addSeparator(new Dimension(10, Dimension(10, 10)); 10));

Download free eBooks at bookboon.com 110 110 110

JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

}

Paedit paedIt

toolBar.add(Tools.createCommand( Tools.createImageIcon("/paedit/images/paste.png", 26), "Insert text from the clip board", this::paste )); toolBar.addSeparator(new Dimension(10, 10)); toolBar.add(Tools.createCommand( Tools.createImageIcon("/paedit/images/cut.png", 26), "Delete text and copy the text to the clip board", this::cut )); toolBar.addSeparator(new Dimension(20, 20)); toolBar.add(Tools.createCommand( Tools.createImageIcon("/paedit/images/search.png", 26), "Search the document", this::search )); toolBar.setPreferredSize(new Dimension(0, 36)); return toolBar;

Here I am using the methods from the Tools class and you should primarily notice how one refers to the individual images. An image is a resource in the application’s jar file, and you must specify the path leading to the current image, the path is relative to the project. Note also the use of the same event handlers as used in the menu. The class JTextArea supports also copy/paste, so there is actually not really need for the buttons, but they are included because the goal is to show how to create a toolbar. In this case includes the toolbar buttons, but it may contain any other components.

LIGS University based in Hawaii, USA is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by October 31st, 2014 and ▶▶ save up to 11% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!

Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.

Download free eBooks at bookboon.com 111 111

Click on the ad to read more

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA2:2:PROGRAMS PROGRAMS WITHAA GRAPHICAL USER JAVA WITH GRAPHICAL USER INTERFACE INTERFACE JAVA 2: PROGRAMS WITH A GRAPHICALUSER USER INTERFACE GRAPHICAL GRAPHICAL USERINTERFACE INTERFACE

paedIt paedIt paedIt Paedit paedIt

THE STATUS LINE THE STATUS LINE THE THESTATUS STATUSLINE LINE

It is actually not a real status bar, but just a JLabel which can display a left-aligned text: actually not real status bar, but just JLabel which can display left-aligned text: ItIt Itisis isactually actuallynot nota aareal realstatus statusbar, bar,but butjust justa aaJLabel JLabelwhich whichcan candisplay displaya aaleft-aligned left-alignedtext: text: private JLabel createStatus() private JLabel createStatus() private JLabel createStatus() { { { JLabel label = new JLabel(); JLabel label = new JLabel(); JLabel label = new JLabel(); label.setFont(Tools.defFont); label.setFont(Tools.defFont); label.setFont(Tools.defFont); label.setOpaque(false); label.setOpaque(false); label.setOpaque(false); label.setBackground(Tools.statusLine); label.setBackground(Tools.statusLine); label.setBackground(Tools.statusLine); label.setHorizontalAlignment(JLabel.LEFT); label.setHorizontalAlignment(JLabel.LEFT); label.setHorizontalAlignment(JLabel.LEFT); label.setPreferredSize(new Dimension(0, 25)); label.setPreferredSize(new Dimension(0, 25)); label.setPreferredSize(new Dimension(0, 25)); return label; return label; } return label; } }

Assignwith withthe thelabel labelisisa amethod methodthat thatisisused usedtotoupdate updatethe thetext: text: Assign Assign Assign with with the the label label is is aa method method that that is is used used to to update update the the text: text: private void setStatus() private void setStatus() private void setStatus() { { { status.setText(String.format("%d linje, %d tegn", status.setText(String.format("%d linje, %d tegn", status.setText(String.format("%d linje, %d tegn", 1)); txtDoc.getLineCount(), txtDoc.getText().length()+ txtDoc.getLineCount(), txtDoc.getText().length()+ 1)); } txtDoc.getLineCount(), txtDoc.getText().length()+ 1)); } }

ItItrefers referstotothe theJTextArea JTextAreacomponent componentcalled calledtxtDoc, txtDoc,and andthe thestatus statusline lineshows showsthe thenumber number It refers to the JTextArea component called txtDoc, and the status line shows the refers to the JTextArea component called txtDoc, the status line shows the number number ofIt characters ininthe field. oflines linesand and thenumber numberofof charactersentered entered theand field. of lines and the number of characters entered in the field. of lines and the number of characters entered in the field. THE THELAYOUT LAYOUT THE THE LAYOUT LAYOUT

MainView MainViewdefines definesfour fourinstance instancevariables: variables: MainView defines four instance MainView defines four instance variables: variables: private private private private private private private private private

JTextArea txtDoc = new JTextArea(); JTextArea txtDoc = new JTextArea(); JTextArea txtDoc = new JTextArea(); JLabel status; JLabel status; JLabel status; Document doc = new Document(); Document doc = new Document(); Document changed doc = new Document(); boolean = false; boolean changed = false; boolean changed = false;

The Thefirst firstisisthe theJTextArea JTextAreacomponent componentwhich whichisisa acomponent, component,where whereone onecan canenter enterand andedit edit The first is the JTextArea component which is a component, where one can enter and edit any number of lines of text, and thus an arbitrary document. The next is a JLabel to the The first is the JTextArea component which is a component, where one can enter and any number of lines of text, and thus an arbitrary document. The next is a JLabel to edit the any number of lines of text, and thus an arbitrary document. The next is aa JLabel to the status line, and the third is the Document and then the model. The last keeps track of any number of lines of text, and thus an arbitrary document. The next is JLabel to status line, and the third is the Document and then the model. The last keeps trackthe of status line, and the third is the Document and then the model. The last keeps track of whether the document is changed. status line, and the third is the Document and then the model. The last keeps track of whether the document is changed. whether the document is changed. whether the document is changed. The Themethod methodcreateWindow() createWindow()isissimilar similartotothe theprevious previousexamples, examples,and anddefines definesthe thewindow’s window’sdesign: design: The method createWindow() is similar to the previous examples, and defines the The method createWindow() is similar to the previous examples, and defines the window’s window’s design: design: private void createWindow() private void createWindow() private void createWindow() { { { createMenu(); createMenu(); createMenu(); setLayout(new BorderLayout()); setLayout(new BorderLayout()); setLayout(new BorderLayout());

Download free eBooks at bookboon.com 112 112 112 112 112

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA 2: PROGRAMS WITH A GRAPHICAL GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL USER INTERFACE

} }

Paedit paedIt paedIt

JPanel panel = new JPanel(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(3, 3, 3, 3)); panel.setBorder(new EmptyBorder(3, 3, 3, 3)); panel.add(createToolbar(), BorderLayout.NORTH); panel.add(createToolbar(), BorderLayout.NORTH); panel.add(status = createStatus(), BorderLayout.SOUTH); panel.add(status = createStatus(), BorderLayout.SOUTH); panel.add(createField()); panel.add(createField()); add(panel); add(panel); txtDoc.requestFocus(); txtDoc.requestFocus();

The Thefirst firststatement statementcreates createsand andadds addsaamenu menutotothe thewindow. window.Otherwise Otherwiseconsists consiststhe thewindow window The first statement creates and adds a menu to the window. Otherwise consists the window only onlyofofaaJPanel JPanelwith withaaBorderLayout BorderLayoutwhich whichNORTH NORTHhas hasaatoolbar, toolbar,SOUTH SOUTHhas hasaastatus status only of a JPanel with a BorderLayout which NORTH has a toolbar, SOUTH has a status bar bar(the (theabove abovelabel) label)while whilethe theJTextArea JTextAreacomponent componentencapsulated encapsulatedininaaJScrollPane JScrollPanefills fillsthe the bar (the above label) while the JTextArea component encapsulated in a JScrollPane fills the rest restofofthe thewindow. window. rest of the window. The Thefollowing followingmethod methodinitializes initializesthe thecomponent componenttxtDoc txtDocwhich whichisisthe theeditor: editor: The following method initializes the component txtDoc which is the editor: private JScrollPane createField() private JScrollPane createField() { { txtDoc.setFont(Tools.txtFont); txtDoc.setFont(Tools.txtFont); txtDoc.setWrapStyleWord(true); txtDoc.setWrapStyleWord(true); txtDoc.setLineWrap(true); txtDoc.setLineWrap(true); txtDoc.addKeyListener(new TextChanged()); txtDoc.addKeyListener(new TextChanged()); return new JScrollPane(txtDoc); return new JScrollPane(txtDoc); } }

Themethod method definesthe the texttotowrap wrap to thenext next linewhen when theline line doesnot not haveroom room for The The methoddefines defines thetext text to wraptotothe the nextline line whenthe the linedoes does nothave have roomfor for more,and andthat thatthe thedivision divisionmust mustbe bedone doneon onword wordboundaries. boundaries.Finally, Finally,there thereisisattached attached more, more, and that the division must be done on word boundaries. Finally, there is attached anKeyListener, KeyListener, anevent event handlerthat that is performedeach each timeaakey key is pressed.ItItsets sets the an an KeyListener,an an eventhandler handler thatisisperformed performed eachtime time a keyisispressed. pressed. It setsthe the variable changed to true, which says that the document has changed, and then called the variable variablechanged changedtototrue, true,which whichsays saysthat thatthe thedocument documenthas haschanged, changed,and andthen thencalled calledthe the method setStatus(), which updates the status line with the current number of lines and the method methodsetStatus(), setStatus(),which whichupdates updatesthe thestatus statusline linewith withthe thecurrent currentnumber numberofoflines linesand andthe the currentnumber numberofofcharacters: characters: current current number of characters: class TextChanged extends KeyAdapter class TextChanged extends KeyAdapter { { public void keyTyped(KeyEvent e) public void keyTyped(KeyEvent e) { { changed = true; changed = true; setStatus(); setStatus(); } } } }

Download free eBooks at bookboon.com 113 113 113

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Paedit paedIt

The event handler is defined as a method in a class that inherits KeyAdater. When a key is The event handler is defined as a method in a class that inherits KeyAdater. When a key is pressed, a JTextArea raises more events, and the class KeyAdapter is a class that implements the pressed, a JTextArea raises more events, and the class KeyAdapter is a class that implements the interface KeyListener which defines three event handlers regarding the keyboard. KeyAdapter interface KeyListener which defines three event handlers regarding the keyboard. KeyAdapter implements these handlers as empty methods, and you can then write a class that overrides implements these handlers as empty methods, and you can then write a class that overrides these handlers that you want to use. Note that it is exactly the same principle that I used these handlers that you want to use. Note that it is exactly the same principle that I used in the previous program related events regarding change of the window size, and you also in the previous program related events regarding change of the window size, and you also used the same principle in exercise 4 to catch the event when double-click on in item in used the same principle in exercise 4 to catch the event when double-click on in item in a list box. a list box. EVENT HANDLERS EVENT HANDLERS

Finally, there are 8 event handlers (there are 8 menu items). Below is the event handler Finally, there are 8 event handlers (there are 8 menu items). Below is the event handler that opens a document: that opens a document: private void open(ActionEvent e) { if (changed && JOptionPane.showConfirmDialog(this, "The document is changed. Should document be saved?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) save(); JFileChooser fileChooser = new JFileChooser();

Download free eBooks at bookboon.com 114 114

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH AA JAVA GRAPHICAL USER INTERFACE GRAPHICAL USER USER INTERFACE INTERFACE GRAPHICAL

Paedit paedIt paedIt

fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); File(System.getProperty("user.home"))); fileChooser.setCurrentDirectory(new fileChooser.setDialogTitle("Open text text document"); document"); fileChooser.setDialogTitle("Open if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {{ File file file == fileChooser.getSelectedFile(); fileChooser.getSelectedFile(); File try try {{ doc == new new Document(file); Document(file); doc txtDoc.setText(doc.getText()); txtDoc.setText(doc.getText()); changed == false; false; changed } } catch (Exception (Exception ex) ex) catch { { JOptionPane.showMessageDialog(this, "The "The document document could could not not be be opened", opened", JOptionPane.showMessageDialog(this, "Error message", JOptionPane.OK_OPTION); "Error message", JOptionPane.OK_OPTION); txtDoc.setText(""); txtDoc.setText(""); changed == false; false; changed }} setStatus(); setStatus(); }} } }

The Thefirst firststatement statementtests testswhether whetherthe thecurrent currentdocument documentisisismodified. modified.In Inthis thiscase caseitititopens opensaaa The first statement tests whether the current document modified. In this case opens popup, popup,but butthis thistime timeit’s it’saaaconfirm confirmdialog, dialog,aaadialog dialogbox boxwith withaaaYes Yesand andaaaNo Nobutton, button,and and popup, but this time it’s confirm dialog, dialog box with Yes and No button, and the theuser userwill willbe beasked askedifififthe thedocument documentshould shouldbe besaved. saved.In Inthis thiscase, case,the themethod methodsave() save()isisis the user will be asked the document should be saved. In this case, the method save() called, called,which whichsaves savesthe thedocument. document.Next NextIIIdefined definedaaaJFileChooser JFileChooserwhich whichopens opensaaadialog dialogbox box called, which saves the document. Next defined JFileChooser which opens dialog box where whereyou youcan canbrowse browsethe thefile filesystem systemfor forthe thefile filethat thatyou youwant wantto toopen. open.Accepting Acceptingaaafile, file, where you can browse the file system for the file that you want to open. Accepting file, you get a File object representing the file’s path, and the object is used in the constructor you get get aa File File object object representing representing the the file’s file’s path, path, and and the the object object isis used used in in the the constructor constructor you in inthe theclass classDocument Documentto toopen openthe thefile. file.After Afterthat thatthe theinput inputfield fieldisisisinitialized initializedwith withthe thefile’s file’s in the class Document to open the file. After that the input field initialized with the file’s content. content.You Youshould shouldnote notethat thatthe thecreation creationof ofthe thedocument documentisisisplaced placedin inaaatry/catch, try/catch,as asthe the content. You should note that the creation of the document placed in try/catch, as the constructor of the class Document may raise an exception. constructor of of the the class class Document Document may may raise raise an an exception. exception. constructor The Theevent eventhandler handlerwill willpossibly possiblycall callthe themethod methodsave() save() The event handler will possibly call the method save() private void void save() save() private { { doc.setText(txtDoc.getText()); doc.setText(txtDoc.getText()); if (doc.save()) (doc.save()) changed changed == false; false; else else saveas(); saveas(); if }}

This Thismethod methodcopies copiesthe thecontents contentsof ofthe theinput inputfield fieldto tothe themodel modeland andask askthe themodel modelto towrite write This method copies the contents of the input field to the model and ask the model to write the text back to the file using the model’s save() method. Is it not possible (because the text text back back to to the the file file using using the the model’s model’s save() save() method. method. IsIs itit not not possible possible (because (becauseitititisisis the aanew newdocument documentthat thathas hasnot notbeen beensaved) saved)the themethod methodcalls callssaveas(), saveas(),where wherethe theuser useragain again a new document that has not been saved) the method calls saveas(), where the user again using a JFileChooser object will be able to browse the file system and enter a file name. using aa JFileChooser JFileChooser object object will will be be able able to to browse browse the the file file system system and and enter enter aa file file name. name. using

Download free eBooks at bookboon.com 115 115 115

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Paedit paedIt

The event handlers to Save, Saveas and New Document works in principle the same way, The event handlers to Save, Saveas and New Document works in principle the same way, and I will not show the code here. and I will not show the code here. Then there are the three event handlers regarding the clipboard. Below is the handler that Then there are the three event handlers regarding the clipboard. Below is the handler that copies text to the clipboard: copies text to the clipboard: private void copy(ActionEvent e) { try { String text = txtDoc.getSelectedText(); Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); cb.setContents(new StringSelection(text), null); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Text could not be copied to the clipboard", "Error message", JOptionPane.OK_OPTION); } }

Firstthe First theselected selectedtext textisisstored storedininaavariable. variable.Next, Next,define defineaareference referencetotothe theclipboard, clipboard,and and thetext textisisstored storedininan anobject objectofofthe thetype typeStringSelection, StringSelection,and andthis thisobject objectisissaved savedom omthe the the clipboard. clipboard.The Thenext nexthandler handlerinserts insertstext textstored storedon onthe theclipboard clipboardininthe thedocument: document: private void paste(ActionEvent e) { try { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable data = cb.getContents(this); if (data == null) return; String str = (String)data.getTransferData(DataFlavor.stringFlavor); String text = txtDoc.getText(); int p = txtDoc.getSelectionStart(); int q = txtDoc.getSelectionEnd(); if (q > p) txtDoc.setText(q < text.length() ? text.substring(0, p) + str + text.substring(q + 1) : text.substring(0, p) + str); else { p = txtDoc.getCaretPosition(); txtDoc.setText(text.substring(0, p) + str + text.substring(p)); }

Download free eBooks at bookboon.com 116 116 116

JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH A A JAVA 2: PROGRAMS WITH A JAVA GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

paedIt Paedit paedIt

changed == true; true; changed setStatus(); setStatus(); } } catch (Exception (Exception ex) ex) catch {{ JOptionPane.showMessageDialog(this, JOptionPane.showMessageDialog(this, "The text text could could not not be be pasted pasted from from the the clipboard", clipboard", "The "Error message", JOptionPane.OK_OPTION); "Error message", JOptionPane.OK_OPTION); } } }}

The The handler handler first first defines defines aaa reference reference to to the the clipboard, clipboard, and and the the value value is is taken taken as as an an object object of of The handler first defines reference to the clipboard, and the value is taken as an object of the type Transferable. The object is converted into a String with a method getTransfereData(). the type type Transferable. Transferable. The The object object is is converted converted into into aa String String with with aa method method getTransfereData(). getTransfereData(). the This string must be inserted into the input field, either to replace a selected This string string must must be be inserted inserted into into the the input input field, field, either either to to replace replace aa selected selected text text or or inserted inserted This text or inserted at in principle in the same way. at the the cursor cursor position. position. The The event event handler handler cut() cut() works works in in principle principle in in the the same same way. way. at the cursor position. The event handler cut() works Back search: Back is is the the event event handler handler for for search: search: Back is the event handler for private void void search(ActionEvent search(ActionEvent e) e) private { { String str str == JOptionPane.showInputDialog(this, JOptionPane.showInputDialog(this, "Enter "Enter aa search search text", text", "Search", "Search", String JOptionPane.INFORMATION_MESSAGE); JOptionPane.INFORMATION_MESSAGE);

Download free eBooks at bookboon.com 117 117 117

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA 2: 2: PROGRAMS PROGRAMS WITH AA JAVA WITH GRAPHICAL USER GRAPHICAL USERINTERFACE INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Paedit paedIt paedIt paedIt

if (str != null && str.length() > 0) if (str (str != != null null && && str.length() str.length() >> 0) 0) if { { { String text = txtDoc.getText(); String text text == txtDoc.getText(); txtDoc.getText(); String int p = text.indexOf(str); int p = text.indexOf(str); int p = text.indexOf(str); if (p >= 0) if (p (p >= >= 0) 0) if { { { txtDoc.select(p, p + str.length()); txtDoc.select(p, pp ++ str.length()); str.length()); txtDoc.select(p, txtDoc.requestFocus(); txtDoc.requestFocus(); txtDoc.requestFocus(); } } } else JOptionPane.showMessageDialog(this, "The text does not exist", else JOptionPane.showMessageDialog(this, JOptionPane.showMessageDialog(this, "The "The text text does does not not exist", exist", else "Information", JOptionPane.OK_OPTION); "Information", JOptionPane.OK_OPTION); JOptionPane.OK_OPTION); "Information", } } } } } }

does not work quite as should, since only finds the first occurrence of the search ItItIt Itdoes doesnot notwork workquite quiteas asititit itshould, should,since sinceititit itonly onlyfinds findsthe thefirst firstoccurrence occurrenceof ofthe thesearch search does not work quite as should, since only finds the first occurrence of the search string. It is a limitation of a JTextArea. The code is easy enough to understand, but you must string. string.ItItItisisisaaalimitation limitationof ofaaaJTextArea. JTextArea.The Thecode codeisisiseasy easyenough enoughto tounderstand, understand,but butyou youmust must string. limitation of JTextArea. The code easy enough to understand, but you must the enter search text. For this purpose is used an input dialog, which is a simple popup the enter search text. For this purpose is used an input dialog, which is a simple popup the enter enter search search text. text. For For this this purpose purpose isis used used an an input input dialog, dialog, which which isis aa simple simple popup popup the where you can enter a string, and the popup is opend with the method showInputDialog() where whereyou youcan canenter enteraaastring, string,and andthe thepopup popupisisisopend opendwith withthe themethod methodshowInputDialog() showInputDialog() where you can enter string, and the popup opend with the method showInputDialog() that is a method in the class JOptionPane. that thatisisisaaamethod methodin inthe theclass classJOptionPane. JOptionPane. that method in the class JOptionPane. When the window closed (and the program stops), want to test whether the document When Whenthe thewindow windowisisis isclosed closed(and (andthe theprogram programstops), stops),IIIIwant wantto totest testwhether whetherthe thedocument document When the window closed (and the program stops), want to test whether the document is changed and possibly should be saved. For this purpose, I has written an inner class that isisischanged changedand andpossibly possiblyshould shouldbe besaved. saved.For Forthis thispurpose, purpose,IIIhas haswritten writtenan aninner innerclass classthat that changed and possibly should be saved. For this purpose, has written an inner class that implements an event handler for the event, that the window closes: implements implementsan anevent eventhandler handlerfor forthe theevent, event,that thatthe thewindow windowcloses: closes: implements an event handler for the event, that the window closes: class WindowCloser extends WindowAdapter class WindowCloser WindowCloser extends extends WindowAdapter WindowAdapter class { {{ public void windowClosing(WindowEvent e) public void void windowClosing(WindowEvent windowClosing(WindowEvent e) e) public { {{ if (changed && JOptionPane.showConfirmDialog(MainView.this, if (changed (changed && && JOptionPane.showConfirmDialog(MainView.this, JOptionPane.showConfirmDialog(MainView.this, if "The document is changed. Do you want to save it?", "The document document is is changed. changed. Do Do you you want want to to save save it?", it?", "The "Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) save(); "Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) save(); "Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) save(); } }} } } }

There no mystery in the code, but the window must be defined as listener for the event, Thereisisis isno nomystery mysteryin inthe thecode, code,but butthe thewindow windowmust mustbe bedefined definedas asaaaalistener listenerfor forthe theevent, event, There There no mystery in the code, but the window must be defined as listener for the event, that happens in the constructor: thathappens happensin inthe theconstructor: constructor: that that happens in the constructor: addWindowListener(new WindowCloser()); addWindowListener(new WindowCloser()); WindowCloser()); addWindowListener(new

Download free eBooks at bookboon.com 118 118 118 118

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Paedit

TEST

When the program is finished, it must be tested. In this case there is not much else to do than try to use the program. However, it can be hard to ensure that you get tested all the situations that may occur. Here it may help to make a test plan where you write down what it is you want to test. It naturally gives no guarantee, but partly just that to write the plan means that you think through what it is you must test, and secondly it helps you remember to get all the points with when you performs the test. A test plan could for instance be something like the following: 1. the program’s visual look and feel 2. enter a document 3. save the document 4. enter more text in the same document 5. save it again 6. close the program 7. open the document again 8. edit the content 9. save the document 10. copy text to the clipboard 11. paste the text in the document without replace 12. paste the text in the document and replace selected text 13. cut a selected text 14. paste the text in the document again 15. copy text from another program to this program 16. test the search functionen 17. save the document 18. create a new document 19. open the test document again 20. modify the document 21. close the program without saving the document 22. open the program again 23. open test document 24. open another text document, as an example a java program 25. open a document, that is not text Later I will deal with testing programs, but a simple test plan as above is better than nothing. One should however be aware that if you find errors during the test, the errors must of course be corrected, and then repeat the test – all the points in the test plan again – and repeating the process until you have completed a test without errors.

Download free eBooks at bookboon.com 119

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Final example

8 FINAL EXAMPLE The task is to write a program that simulates a solitaire. It is a very simple solitaire game where the rules are as follows: On the table is 16 cards. One must then remove the cards on two criteria: 1. cards of the same color with value less than 10, and where the sum of the card’s values are 15 (thus as an example es, five and nine in the same color, or seven and eight in the same color) 2. 10, Jack, Queen and King of the same color When you have removed cards, the unused places must be filled with cards from the deck – if there are more cards. The solitaire is solved when all cards are removed, but when you get into a situation where you can not remove cards, it means that the solitaire can not be solved.

Download free eBooks at bookboon.com 120

Click on the ad to read more

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Final example

8.1 THE PROGRAM’S CLASSES In principle, it is a very simple program in which the user interface has to display images of playing cards, which the user then should be able to click on with the mouse. The program has in principle no other functions, but there must be a possibility to be able to select new game. There must be kept track of which cards are on the table, which are left in the deck and which have been taken, and for this purpose the program should define a model that always represents the program’s current state. The program must therefore in principle work in that way, that when the user clicks on a card, a message is sent to the model on which card is clicked, and the model should then from the cards that are marked determine whether the cards can is removed from the table according to the solitaires rules. If this is the case the model must remove the cards from the table, and selecting new cards from the deck. The basic concept in the program is a playing card, which is a very simple concept. A playing card must have three characteristics: 1. a value that must be a number from 1 to 13: 1 = es, 11 = Jack, 12 = Queen and 13 = king 2. a color which should be a character: D (diamonds), H (Hearts), S (spade) C (clubs) 3. an image of the card Otherwise, a card is passive and can be defined as follows:

Besides a playing card it is also natural to think of a deck of 52 cards. It is not much more than an array of 52 Card objects and a variable that can keep track of how many cards are left in the deck:

Download free eBooks at bookboon.com 121

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Final example

The first method returns while the deck is empty, and the next how many cards left in the deck. The third method returns and remove the card that is on top of the deck and as so simulates that a dealer share a card. The last method shuffles the cards and should be used when selecting a new game. The model must have an object of type Cards, and thus a deck of cards. In order to control the game’s state is needed three data structures -- a list of the cards that has been taken -- an array that keeps track of which cards are on the table -- an array which keeps track of which of the cards on the table is marked and thus you can outline the model class as follows:

The class has only two essential methods, where move() is the most important and is used each time the user clicks on a card. The method reset() is for selecting new game. The program’s design will consist of the following classes:

Download free eBooks at bookboon.com 122

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Final example FInal exaMple

8.2 PROGRAMMING 8.2 PROGRAMMING The starting point is a NetBeans project called Solitaire16. To write the program you must The starting point is a NetBeans project called Solitaire16. To write the program you must have pictures of playing cards. The folder for this book has a package with the name cards. have pictures of playing cards. The folder for this book has a package with the name cards. tar.gz containing images of the cards. In addition to the 52 cards, there are also two back tar.gz containing images of the cards. In addition to the 52 cards, there are also two back side cards and an icon to be used in a simple toolbar. To get the pictures packed in the side cards and an icon to be used in a simple toolbar. To get the pictures packed in the application’s jar file, I’ve created a package named solitaire16.images, unpackaged the tar file application’s jar file, I’ve created a package named solitaire16.images, unpackaged the tar file and copied all the images to that folder. and copied all the images to that folder. THE MODEL LAYER THE MODEL LAYER

The model layer is composed of the three classes referred to above, and the class Card is The model layer is composed of the three classes referred to above, and the class Card is trivial and are not discussed further. The same applies in principle to the class Cards, but trivial and are not discussed further. The same applies in principle to the class Cards, but it is this class that has to load the images to the cards, and for this I added a helper class it is this class that has to load the images to the cards, and for this I added a helper class with a method that can load an image from the jar file: with a method that can load an image from the jar file: package solitaire16; import java.awt.Color; import javax.swing.*;

93%

OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION

MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE

5 Specializations

Personalize your program

www.ie.edu/master-management

#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES

[email protected]

Download free eBooks at bookboon.com 123 123

Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

Click on the ad to read more

JAVA JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA 2: PROGRAMS WITH A GRAPHICAL USER GRAPHICAL USERINTERFACE INTERFACE GRAPHICAL USER INTERFACE

Final FInalexample exaMple FInal exaMple

public class Tools public class Tools { { public static Color selected = Color.darkGray; public static Color selected = Color.darkGray;

} }

public static ImageIcon createImage(String path, String description) public static ImageIcon createImage(String path, String description) { { java.net.URL imgURL = Cards.class.getResource(path); java.net.URL imgURL = Cards.class.getResource(path); if (imgURL != null) return new ImageIcon(imgURL, description); if (imgURL != null) return new ImageIcon(imgURL, description); return null; return null; } }

The classreally really doesnot not belongininthe the modellayer, layer, sinceits its purposeisistotocreate create ImageIcon The Theclass class reallydoes does notbelong belong in themodel model layer,since since itspurpose purpose is to createImageIcon ImageIcon objectsthat thatare areobjects objectsthat thatbelongs belongstotothe theuser userinterface. interface.On Onthe thewhole, whole,the theboundary boundary objects objects that are objects that belongs to the user interface. On the whole, the boundary between modeland and viewlayers layers in thecurrent current solutionisisnot not quitesharp sharp becausethe the classes between betweenmodel model andview view layersininthe the currentsolution solution is notquite quite sharpbecause because theclasses classes inthe themodel modellayer layerare areusing usingobjects objectsthat thatbelongs belongstotothe theview viewlayer, layer,and andthe theprogram programthen then inin the model layer are using objects that belongs to the view layer, and the program then does notmeets meets theprinciple principle behindMVC MVC as themodel model layerininaamanner manner knowsthe the view does doesnot not meetsthe the principlebehind behind MVCasasthe the modellayer layer in a mannerknows knows theview view layer.One Onecan canmade madeaadifferent differentdesign designofofthe theprogram, program,where wherethe theclasses classesininthe themodel modellayer layer layer. layer. One can made a different design of the program, where the classes in the model layer does notknow know theimages, images, butyou you canalso also takethe the currentsolution solution of theprogram program as an does doesnot not knowthe the images,but but youcan can alsotake take thecurrent current solutionofofthe the programasasan an exampleofofhow howpatterns patternsand andprinciples principlesare aregood, good,but butconversely converselyyou youshould shouldnot notcomplicate complicate example example of how patterns and principles are good, but conversely you should not complicate the codejust just to complyaapattern. pattern. the thecode code justtotocomply comply a pattern. With theabove above classavailable, available, it is simpletotowrite write thecode code forthe the classCards. Cards. It mustload load With Withthe the aboveclass class available,ititisissimple simple to writethe the codefor for theclass class Cards.ItItmust must load the 52playing playing cardsinto into anarray, array, andininaddition addition loadthe the imagestototwo two backcards. cards. The the the52 52 playingcards cards intoan an array,and and in additionload load theimages images to twoback back cards.The The classalso alsohas hasaamethod methodtotoshuffle shufflethe thecards, cards,which whichisisdone donewith withthe thefollowing followingalgorithm: algorithm: class class also has a method to shuffle the cards, which is done with the following algorithm: public void shuffle() public void shuffle() { { for (int n = 0; n < 1000; ++n) for (int n = 0; n < 1000; ++n) { { int i = rand.nextInt(array.length); int i = rand.nextInt(array.length); int j = rand.nextInt(array.length); int j = rand.nextInt(array.length); Card temp = array[i]; Card temp = array[i]; array[i] = array[j]; array[i] = array[j]; array[j] = temp; array[j] = temp; } } top = array.length; top = array.length; } }

Download free eBooks at bookboon.com 124 124 124

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE JAVA WITH JAVA 2: 2: PROGRAMS PROGRAMS WITH A A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

Final example FInal exaMple FInal FInal exaMple exaMple

The class Model defines the following instance variables: The class Model defines the following instance variables: The The class class Model Model defines defines the the following following instance instance variables: variables: public class Model public class Model {public class Model {{ private Cards deck = new Cards(); // the deck of cards to be used private // of cards to private Cards Cards deck deck == new new Cards(); Cards(); // the the deck deck of are cards to be be used used private ArrayList used = new ArrayList(); // the cards taken private ArrayList used == new ArrayList(); // the cards are taken private ArrayList used new ArrayList(); // the cards are taken private Card[][] table = new Card[4][4]; // the cards on the table private Card[][] == new Card[4][4]; // the on the table private boolean[][] Card[][] table table new Card[4][4]; // cards the cards cards table private marked = new boolean[4][4]; // that on is the marked private private boolean[][] boolean[][] marked marked == new new boolean[4][4]; boolean[4][4]; // // cards cards that that is is marked marked

In In addition addition to to what what isis shown shown in in the the design design isis the the class class extended extended by by aa number number of of other other In In addition addition to to what what isis shown shown in in the the design design isis the the class class extended extended by by aa number number of of other other methods, methods, which which has has the the sole sole purpose purpose that that the the user user interface interface can can read read the the model’s model’s state. state. As As methods, methods, which which has has the the sole sole purpose purpose that that the the user user interface interface can can read read the the model’s model’s state. state. As As mentioned, mentioned, the the method method move() move() isis the the most most complex, complex, as as itit isis the the method method to to test test whether whether the the mentioned, mentioned, the the method method move() move() isis the the most most complex, complex, as as itit isis the the method method to to test test whether whether the the cards cards may may be be removed removed from from the the table. table. This This isis done done with with the the following following algorithm: algorithm: cards cards may may be be removed removed from from the the table. table. This This isis done done with with the the following following algorithm: algorithm: if all cards has the same color then if all has the same color then if all cards cards color values then calculate thehas sumthe of same the cards calculate the sum of the cards values calculate sum of thethen cards values if there isthe a face card if there is aa face card then if there is face card then if the sum = 46 then move cards if if the the sum sum == 46 46 then then move move cards cards else else else if the sum = 15 then move cards if if the the sum sum == 15 15 then then move move cards cards

THE PROGRAM’S PROGRAM’S VIEW VIEW THE THE THE PROGRAM’S PROGRAM’S VIEW VIEW

The user user interface interface contains contains only only aa single single class, class, which which isis MainWindow. MainWindow. The The class class does does not not The The The user user interface interface contains contains only only aa single single class, class, which which isis MainWindow. MainWindow. The The class class does does not not take up up so so much much and and defines defines the the following following instance instance variables: variables: take take take up up so so much much and and defines defines the the following following instance instance variables: variables: public class MainWindow extends JFrame public class MainWindow extends JFrame {public class MainWindow extends JFrame {{ private Model model = new Model(); private Model == new private JLabel[][] Model model modelcenter new =Model(); Model(); private new JLabel[4][4]; private JLabel[][] center = new private JLabel[][] center = new JLabel[4][4]; JLabel[4][4]; private JLabel[] left = new JLabel[36]; private JLabel[] left == new JLabel[36]; private JLabel[] left new JLabel[36]; private JLabel[] right = new JLabel[52]; private private JLabel[] JLabel[] right right == new new JLabel[52]; JLabel[52];

Here isis the the center center for for the the cards cards on on the the table, table, left left isis the the deck deck and and must must show show which which cards cards Here Here Here isis the the center center for for the the cards cards on on the the table, table, left left isis the the deck deck and and must must show show which which cards cards are left left in in the the deck, deck, and and finally finally right right for for the the cards cards that that are are taken. taken. center center shows shows cards cards spread spread are are are left left in in the the deck, deck, and and finally finally right right for for the the cards cards that that are are taken. taken. center center shows shows cards cards spread spread out over over the the table table with with the the front front up, up, while while right right shows shows the the cards cards that that isis taken taken as as aa deck. deck. out out out over over the the table table with with the the front front up, up, while while right right shows shows the the cards cards that that isis taken taken as as aa deck. deck. left shows shows just just aa backing backing card: card: left left shows just a backing card: left shows just a backing card:

Download free eBooks at bookboon.com 125 125 125

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Final example

DO YOU WANT TO KNOW:

What your staff really want?

The top issues troubling them?

How to retain your top staff FIND OUT NOW FOR FREE

How to make staff assessments work for you & them, painlessly?

Get your free trial Because happy staff get more done

Download free eBooks at bookboon.com 126

Click on the ad to read more

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

Final example

The window layout is a BorderLayout, where NORTH has a toolbar with a single button, WEST has the deck with the cards not yet dealt, EAST has a deck with the cards taken, and finally the 16 cards on the table are CENTER. The images for the cards are displayed with a JLabel that specifically can display an image. To show that a card is marked when it is clicked, the background color for the JLabel component that contains the image is changed, and it appears as a frame around the picture. The color is defined in the class Tools. It is a very simple solitaire, but it is relatively difficult to solve the solitaire, and you get very quick in a situation where you have to give up, so there is no question of that it is not the most entertaining solitaire.

Download free eBooks at bookboon.com 127

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

A last example

9 A LAST EXAMPLE As shown in this book require the programming of a graphical user interface many lines of code, and there is even talk of code that is difficult to remember how to write. Conversely, the book’s examples also shows that it is the same thing you have to write every time, or at least that the development of the various user interfaces have a number of common features. One can facilitate the work by creating a class library that contains classes with methods of the tasks typically encountered, and this library can then be made available to all of the GUI programs that you develop. I will in this last chapter show how to write such a class library, which I will call PaLib, and I also shows a program that use the library. The class library is used in all subsequent books and not only that, the library will continuously be expanded and more of the upcoming exercises and problems actually has to do with how to expand the library. You are therefore encouraged to carefully study how the class library is made and how it is used in the program History, a test program that I shows last in this chapter. Although the program relative to GUI programs do not contain anything new, it is nevertheless an appropriate conclusion to this introduction to GUI applications and Swing.

9.1 CREATING THE LIBRARY In principle, it is quite simple to create a class library, and in NetBeans you creates a project in the usual way, just it have to be a Java Class Library project:

Download free eBooks at bookboon.com 128

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

A last example a last exaMple

The The result result isis aa project project that that isis empty, empty, and and you you can can then then start start to to add add packages packages and and classes. classes. My library is as mentioned called PaLib, and so far it consists only of a single package My library is as mentioned called PaLib, and so far it consists only of a single package named named palib.gui palib.gui and and aa single single class class called called Tools Tools (se (se below). below). The The class class consists consists exclusively exclusively of of static methods that are methods that I find useful in the design of user interfaces. I will static methods that are methods that I find useful in the design of user interfaces. I will not not show show the the code code here, here, as as itit isis extensive extensive (it (it takes takes up up 800 800 lines), lines), but but many many of of the the lines lines are are comments, and the methods are almost all used in the previous examples. As an example comments, and the methods are almost all used in the previous examples. As an example II will will show show aa single single method method (in (in several several overloadings), overloadings), which which shows shows aa little little about about what what the the class contains. class contains.

ItIt isis aa method method that that creates creates aa JTextField: JTextField: /** * Creates and returns a JTextField with the following properties: * @param width The width of the field * @param height The height of the field

Challenge the way we run

EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…

READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM

1349906_A6_4+0.indd 1

22-08-2014 12:56:57

Download free eBooks at bookboon.com 129 129

Click on the ad to read more

JAVA JAVA 2: 2: PROGRAMS PROGRAMS WITH WITH AA GRAPHICAL GRAPHICAL USER USER INTERFACE INTERFACE

Aa last last example exaMple

* @return A JTextField component */ public static JTextField createField(int width, int height) { return createField(null, JTextField.LEFT, true, width, height, null, null, null); } /** * Creates and returns a JTextField with the following properties: * @param text The text that must initialize the field * @param width The width of the field * @param height The height of the field * @return A JTextField component */ public static JTextField createField(String text, int width, int height) { return createField(text, JTextField.LEFT, true, width, height, null, null, null); } /** * Creates and returns a JTextField with the following properties: * @param text The text that must initialize the field * @param width The width of the field * @param height The height of the field * @param font The font to be used * @return A JTextField component */ public static JTextField createField(String text, int width, int height, Font font) { return createField(text, JTextField.LEFT, true, width, height, font, null, null); } /** * Creates and returns a JTextField with the following properties: * @param text The text that must initialize the field * @param alignment The text alignment, can be JTextField.LEFT or JTextField.RIGHT * @param editable Where the contents of the field may be edited or not * @param width The width of the field * @param height The height of the field * @param font The font to be used * @return A JTextField component */ public static JTextField createField(String text, int alignment, boolean editable, int width, int height, Font font) { return createField(text, alignment, editable, width, height, font, null, null); }

Download free eBooks at bookboon.com 130 130

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

A last example a last exaMple

/** * Creates and returns a JTextField with the following properties: * @param text The text that must initialize the field * @param alignment The text alignment, can be JTextField.LEFT or JTextField.RIGHT * @param editable Where the contents of the field may be edited or not * @param width The width of the field * @param height The height of the field * @param font The font to be used * @param fg The field's text color * @param bg The field's background color * @return A JTextField component */ public static JTextField createField(String text, int alignment, boolean editable, int width, int height, Font font, Color fg, Color bg) { JTextField field = new JTextField(); if (text != null) field.setText(text); field.setHorizontalAlignment(alignment); field.setEditable(editable); if (font != null) field.setFont(font); if (fg != null) field.setForeground(fg); if (bg != null) field.setBackground(bg); field.setPreferredSize(new Dimension(width, height)); return field; }

As Asregards regardsthe themethods methodsthemselves, themselves,and andhow howthey theywork, work,there thereisisnot notmuch muchtotoexplain, explain,but but I Iwill tell you about the considurations concerning the method createField(). In practice, will tell you about the considurations concerning the method createField(). In practice, I Ioften oftenneed needtotocreate createaaJTextField JTextFieldand andI Ioften oftenhas hastotoinitialize initializeseveral severalproperties. properties.ItItmay may therefore thereforebe beuseful usefulwith withaamethod methodwhich whichparameters parametershas hasvalues valuesfor forthe theproperties propertiestotobe beset, set, and andaamethod methodthat thatcreates createsand andreturns returnsaaJTextField JTextFieldwith withthese theseproperties propertiesinitialized. initialized.Now Now you can define many properties of a JTextField, and it would not be appropriate by methods you can define many properties of a JTextField, and it would not be appropriate by methods ofofall allpossible possiblecombination combinationofofproperties, properties,but butthe thelast lastversion versionofofthe themethod methodcreateField() createField() has hasparameters parametersfor forthe themost mostcommon commonproperties properties––atatleast leastininrelation relationtotothe theprograms programsthat that I Iwrite. write.Since Sincethere thereisisfar farfrom fromalways alwaysneed needofofall allthese theseparameters, parameters,I Ihave havewritten writtenseveral several overloading methods that has fewer parameters. overloading methods that has fewer parameters. When Whenyou youhave havetotowrite writethat thatkind kindofoflibrary libraryclasses classesthe thebiggest biggestconsiderations considerationsare arewhat what parameters parametersthe themethods methodsshould shouldhave. have.On Onthe theone onehand, hand,methods methodsshould shouldhave havesosomany many parameters that they are flexible enough to be used as tools in many applications. On parameters that they are flexible enough to be used as tools in many applications. Onthe the other hand there should not be so many parameters that it is confusing and the methods other hand there should not be so many parameters that it is confusing and the methods equally equallybecomes becomesdifficult difficulttotouse. use.The Thechoice choiceshould shouldreflect reflecttypical typicalapplications, applications,and andininthis this case casethe theneeds needsI Itypically typicallyhave havetotocreate createaaJTextField. JTextField.

Download free eBooks at bookboon.com 131 131

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

A last example

I shall not show the rest of the class, but there are similar methods to create the most basic Swing components. Furthermore, there are methods to place components in the containers. This is a class with tools, and it is natural that the class is continuously expanded with new methods as you need them. Similarly, the class library may be extended with new classes, and as an example I will extend the library with a class that has methods to write an object to and read an object from a file. First I has extended the library with a new package called palib.util and here a class called Files:

This e-book is made with

SETASIGN

SetaPDF

PDF components for PHP developers

www.setasign.com Download free eBooks at bookboon.com 132

Click on the ad to read more

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

A last example a last exaMple

InInthe thebook bookJava Java11I Ishows showshow howtotostore storean anabritary abritaryobject objectininaafile file(object (objectserialization) serialization) and how to read the object again (object deserialization). It can be difficult to and how to read the object again (object deserialization). It can be difficult toremember remember how write the statements, and when it is the same you has to write every time it how write the statements, and when it is the same you has to write every time itpays paystoto write writetwo twolibrary librarymethods methodsfor forthese thesepurposes: purposes: package palib.util; import java.io.*; public class Files { public static boolean serialize(Object obj, String filename) { try { ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(filename)); stream.writeObject(obj); stream.close(); return true; } catch (Exception ex) { return false; } }

}

public static Object deserialize(String filename) { try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(filename)); Object obj = stream.readObject(); stream.close(); return obj; } catch (Exception ex) { return null; } }

Download free eBooks at bookboon.com 133 133

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

A last example a last exaMple

9.2 THE TEST PROGRAM 9.2 THE TEST PROGRAM I will finally show how my class library can be used in a program. I have written a program I will finally show how my class library can be used in a program. I have written a program called History, where you can maintain a list of historical persons. It requires that the called History, where you can maintain a list of historical persons. It requires that the program can save the list somewhere. When the program starts the first time, it initialize program can save the list somewhere. When the program starts the first time, it initialize the list of the Danish kings, and each time the list is changed, it is stored in a file on your the list of the Danish kings, and each time the list is changed, it is stored in a file on your hard disk. When the program opens the next time, it starts to read the updated list from hard disk. When the program opens the next time, it starts to read the updated list from the file – if possible. Otherwise the list is initialized of the Danish kings. The file is stored the file – if possible. Otherwise the list is initialized of the Danish kings. The file is stored in the same location as the program and you do not need to study how the file is stored in the same location as the program and you do not need to study how the file is stored and read, as the library has the necessary methods. and read, as the library has the necessary methods. A person is defined as follows (where I removed the comments and all the get and set methods): A person is defined as follows (where I removed the comments and all the get and set methods): package history; import java.io.*; public class Person implements Comparable, Serializable { private String name; // the person's name private String job; // the person's position private String text; // a description private int from; // birth, start of reign or otherwise private int to; // year of when the person is dead public Person(String name, String job, String text, int from, int to) { this.name = name; this.job = job; this.text = text; this.from = from; this.to = to; } …. }

When Whenyou youread readthe thecode, code,you youshould shouldspecifically specificallynoting notinghow howthe thecomparison comparisonofofobjects objectsare are defined definedby bythe themethod methodcompareTo() compareTo()where wherethe theobjects objectscompared comparedby bythe theyear yearnumbers numbers(the (the class implements the interface Comparable), and note that the class implements class implements the interface Comparable), and note that the class implements the theinterface interfaceSerializable. Serializable.You Youshould shouldalso alsonote notethat thatthe theclass classoverrides overridesequals(), equals(),sosopeople people are arecompared comparedsolely solelyon ontheir theirnames. names.

Download free eBooks at bookboon.com 134 134

Deloitte & Touche LLP and affiliated entities.

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

A last example a last exaMple

Then Thenthere thereisisthe theclass classPersons Personsrepresenting representingthe thelist listofofPerson Personobjects. objects. package history; import java.util.*; import palib.util.*; public class Persons implements Iterable { private static String filename = "persons.dat"; private ArrayList list; public Persons() { list = (ArrayList)Files.deserialize(filename); if (list == null) initialize(); } public Iterator iterator() { return list.iterator(); }

360° thinking

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discoverfree theeBooks truth atatbookboon.com www.deloitte.ca/careers Download

Click on the ad to read more

135 135

Dis

JAVA 2: PROGRAMS WITH A JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE GRAPHICAL USER INTERFACE

A last example a last exaMple

public void add(Person pers) { list.add(pers); Collections.sort(list); Files.serialize(list, filename); } public void remove(Person pers) { list.remove(pers); Files.serialize(list, filename); } public void update(Person pers) { for (Person p : list) { if (p.equals(pers)) { p.setJob(pers.getJob()); p.setText(pers.getText()); p.setFrom(pers.getFrom()); p.setTo(pers.getTo()); break; } } Files.serialize(list, filename); } private void initialize() { list = new ArrayList(); for (int i = 0;i < navne.length; ++i) { String job = navne[i][0].equals("Margrete d. 1.") || navne[i][0].equals("Margrethe d. 2.") ? "Queen" : "King"; int fra = navne[i][1].length() > 0 ? Integer.parseInt(navne[i][1]) : -9999; int til = navne[i][2].length() > 0 ? Integer.parseInt(navne[i][2]) : 9999; list.add(new Person(navne[i][0], job, "", fra, til)); } Collections.sort(list); }

}

private static String[][] navne = { { "Gorm den Gamle", "", "958" }, { "Harald Blåtand", "958", "986" }, … };

Download free eBooks at bookboon.com 136 136

JAVA2:2:PROGRAMS PROGRAMSWITH WITHAA JAVA GRAPHICALUSER USERINTERFACE INTERFACE GRAPHICAL

lastexample exaMple Aalast

Firstyou younote notethe theimport importstatement statement First import palib.util.*;

referringtotothe thepackage packagecontaining containingthe theclass classFiles. Files.InInorder ordertotobebepossible, possible,the thejar jarfile filefor forthe the referring classlibrary librarymust mustbebeavailable availablefor forthe theprogram. program.ItItisisobtained obtainedfor forthe theproject project(the (theprogram program class History),by byright-click right-clickon onLibraries Librariesand andhere herechoose chooseAdd AddJAR JAR/ /Folder…You Folder…Youcan canthen thenbrowse browse History), classlibrary’s library’sjar jarfile fileand andadd additittotothe theproject: project: totoclass

Nowthe theapplication applicationcan canuse usethe thejar jarfile fileand anditsitsclasses. classes.IfIfwe wenow nowbuilds buildsthe theproject projectand and Now copythe thefile fileHistory.jar History.jartotoanother anotherfolder folderand andtry trytotorun runthe theprogram programfrom froma aTerminal Terminal copy window,you youget getananerror errormessage messagebecause becausethe theprogram programcan cannot notfind findthe theclass classlibrary. library.The The window, classlibrary libraryisisnot notpart partofofthe theprogram’s program’sjar-file. jar-file.IfIfyou youopens opensthe theproject’s project’sdist distfolder, folder,you you class willsee seethat thatthere thereisisa asubdirectory subdirectorynamed namedlib. lib.ItItcontains containsthe thejar jarfile filetotoclass classlibrary, library,and and will forthe theprogram programtotorun, run,this thissubfolder subfoldermust mustalso alsobebecopied. copied. for Theclass classPersons Personsisisininprinciple principlesimple simpleand andyou youshould shouldnotice noticehow howPerson Personobjects objectsare arestored stored The ArrayList,and andthe theclass classhas hasmethods methodstotoadd addananitem, item,update updateananitem, item,and anddelete deleteanan ininananArrayList, item.Note Notespecifically specificallythat thateach eachofofthese thesemethods methodsserialize serializethe thelist listusing usingthe themethod methodserialize() serialize() item. theclass classFiles, Files,which whichare area aclass classininthe theclass classlibrary. library. ininthe Themost mostcomplex complexininthe theclass classisisthe theconstructor. constructor.ItIttries triestotodeserialize deserializethe thelist listfrom froma afile. file.IfIf The thisfails, fails,for forexample examplebecause becausethe thefile filedoes doesnot notexist exist(and (andindeed indeedititdoes doesnot notthe thefirst firsttime time this theprogram programruns), runs),the thelist listisisinitialized initializedusing usingdata datathat thatisislaid laidout outininthe theprogram program(Danish (Danish the kingsand andI Ihave haveonly onlyshown shownthe thefirst firsttwo). two).The Thelist listisiscreated createdininthe themethod methodinitialize(), initialize(), kings whichruns runsthrough throughthe thestatic staticarray arraywith withdata. data. which Youshould shouldalso alsonote notethe themethod methoditerator(). iterator().ItItwill willfirst firstbebeexplained explainedininthe thenext nextbook, book,but but You meansthat thatititisispossible possibletotoiterate iterateover overa aPersons Personsobject’s object’sitems itemswith witha afor forstatement. statement. ititmeans

Download free eBooks at bookboon.com 137 137

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

A last example

If you run the program, you get a window as shown below. The window is the program’s main window, and I will not show the code here, as there not is something new, but you should notice how the class use the class library for constructing the user interface. If you double click on a line (a name) in the list, you get a window where you can see all the information, edit them and possibly delete the person (see below). The class is named PersonView, where I will not show the code, but the window layout is defined by a GridBagLayout and the class makes widely use of the class library. If you in the main window, click the button Create person opens the same window, but with all fields blank, and you can then enter the name of a person and thus add a new Person to the list.

NY026057B

TMP PRODUCTION 6x4

4

12/13/2013

ACCCTR00

PSTANKIE

gl/rv/rv/baf

Bookboon Ad Creative

All rights reserved.

© 2013 Accenture.

Bring your talent and passion to a global organization at the forefront of business, technology and innovation. Discover how great you can be. Visit accenture.com/bookboon

Download free eBooks at bookboon.com 138

Click on the ad to read more

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

A last example

Below is an example of the window PersonView, when double clicked on a line in the list box:

Download free eBooks at bookboon.com 139

JAVA 2: PROGRAMS WITH A GRAPHICAL USER INTERFACE

A last example

If you now have many programs that use the class library, each program must have a copy of the class library’s jar file. Of course it is not particularly useful, and it should be such that there is only one copy, that all programs are using. It can be solved in several ways, but a very simple way (although far from the best) is to place the jar file as shown below:

Here are jdk1.8.0_111 the folder containing my Java and can of course be replaced by another. To make a jar file available in that way by placing it in the folder as shown above is not necessarily the best way, but it’s a simple way, which is well worth knowing.

Download free eBooks at bookboon.com 140