Instructor s Notes Java - Beginning GUI Classes and Swing. Java - Beginning GUI Classes and Swing

Instructor’s Notes Java - Beginning GUI Classes and Swing Java - Beginning 152-130 GUI Classes and Swing Notes Activity Quick Links Pages 74 – 7...
Author: Barry Bradford
6 downloads 0 Views 307KB Size
Instructor’s Notes

Java - Beginning

GUI Classes and Swing

Java - Beginning 152-130

GUI Classes and Swing Notes

Activity

Quick Links Pages 74 – 78, 479 484 – 485 Easy Eclipse Pages (see Help system) Creating GUI Projects Pages (see Help system) Creating GUI Class Page 78, 481 – 482 Containers Pages 485 Container Layouts Pages 516 - 522 Adding Components Pages 488 – 494 Adding Code Events Pages 503 – 509 Get/Set Text Properties Pages Project Images Pages Implementing Radio Buttons Pages Combining Event Handlers Pages Implementing Check Boxes Pages Implementing Date Pickers Pages Centering the Form Pages Background

Page 1 of 15

Instructor’s Notes

Java - Beginning

Notes

GUI Classes and Swing

Activity

Background Java GUI classes have been around since the beginning of GUI operating systems, but they have evolved significantly The original GUI support class is called AWT (Abstract Windows Toolkit  Most of the more current GUI classes are based on (inherit) this class  Import java.awt.*  All Windows components are rendered using the style of the current operating system. Application appears differently on different platforms Eclipse has its own enhancement of AWT called SWT (Standard Widget Toolkit) Sun’s enhancement to AWT is called Swing  Draws components without referencing OS APIs  Very transportable and very powerful  Projects can have the same appearance on all platforms.

Easy Eclipse

Install Easy Eclipse

Easy Eclipse is an enhance version of Eclipse that comes preconfigured with GUI, drag and drop plug-ins. Makes creating GUI classes almost as easy as Visual Studio. Free download at www.EasyEclipse.org Also available on the I: drive. As far as I can tell, Easy Eclipse functions exactly the same as the Eudora version of Eclipse we’ve been using.

Creating GUI Project GUI projects are no different than other projects Click the New Java Project button and create a project as we’ve always done.

Create a MyFirstGUI project

Page 2 of 15

Instructor’s Notes

Java - Beginning

Notes

Creating a GUI Class Drop down the list of new class options Choose Visual Class Enter a name for the class Select the Style for the visual class  We will always be using Swing Select the primary container object for the class  We will be using Frames  Tip: The Application style gives you a form with a menu and About form already built

GUI Classes and Swing

Activity Create a BowlingForm class. Swing style with Frame Include main method

If appropriate, click the check box to include a main module, making the GUI class an executable program. Click Finish Review each pane An Eclipse perspective will appear with four important window panes  Form preview. As in VB, this is where you’ll drag and drop and manipulate components (Java term for control)  Code view This pane shows you the code that is automatically generated as you drag components to the form and change the component properties. This window pane is also where you’d write the event code that is to execute when events occur  Properties pane Shows the current values of the properties of the currently selected component. There is also a Java Beans tab in this pane. Use this tab to access (select) invisible components  Palette Initially collapsed on right side of form preview pane The palette contains the selection of components that are available based on the GUI style selected Note: Swing components are distinguished from AWT (and SWT) components because their names all start with ―J‖

Page 3 of 15

Instructor’s Notes

Java - Beginning

Notes

Containers All Swing basic components must be placed in a container  The form itself is a container (Frame) with another container embedded in it (a content panel) Often a container will include other containers to help organize the form components Similar to VB panels and group boxes

GUI Classes and Swing

Activity Select the Form Select the content panel

Page 4 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing

Container Layouts All containers have a Layout property. This property controls how components are laid out when they are dragged into the container. These layouts are designed to ensure the components on a form reposition and resize appropriately when the form is resized at run-time  I find them very difficult to use. For any type of layout, right-click the container and choose Customize Layout, to control the amount of space between and around objects, and the object alignment. Border layout  Container divided into 5 zones  Each zone can hold one control or container

West

North Center South

Demonstrate each type of layout.

East

Box Layout (Y_Axis)  Components are stacked on top of each other Box Layout (X_Axis)  Components are placed next to each other Card Layout  Stacks components like overlaying cards. I’d avoid this one. Flow layout  Components are added to the form, left to right until the no longer fit, then a new row is started Grid layout  Components are added in multiple columns and then multiple rows Grid Bag layout  Similar to Grid Layout, but more flexible.  Drag components onto dividing lines to create new rows or columns  Each component in the container can have designated spacing. Null  No predefined layout  Similar to how VB does layout  Components don’t adjust when form is resized  Select multiple objects  Objects don’t autosize to contents

Page 5 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing

Adding Components to Containers Select (click) component in palette Move mouse to appropriate location in container Click or drag (in Null container) to position component  In many containers, the component will automatically size to fill the area  Many components, like buttons and labels, automatically resize to fit the size of the text. Change the Preferred Size property to force a component to be bigger. Preferred Size actually defines the preferred minimum size. Modify the properties of the object  Captions (text) of objects that display text can be easily changed by clicking the object (twice) and then typing the new caption Some properties have dropdown selections, others open dialog boxes (just like VB)

Adding Code to Events Java components focus on just a few events (unlike VBs myriad of events) For our simple needs, buttons respond to an actionPerformed event. To create event code for a component:  Right-click the component  Choose Events and then the event name you want  Java creates an embedded class (class within this class) to handle the event (Action Listener)  Replace the System.out command with the code of your choice.

Getting and Setting Text Properties One of the most common code you’ll write is code to change or retrieve the text in text boxes and labels. Unlike VB, you can’t simply access the components properties.  Properties are actually private class members  Componentname.getText();  ComponentName.setText(string); All properties have setter and getter methods except those that are read only (getter only)

Page 6 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing

Project Images Most components (buttons, labels, Frames) support icons Java icons should be 16 x 16 gif or jpg files  Ico files are not supported Images on buttons and labels, etc. are NOT resized to fit the button. Images used for the form (Frame) icon are sized to fit the standard title bar. Best to store images in the same folder as the form class file. Most components allow multiple icons  disabledIcon: icon that displays when object is disabled (if not specified, grayed version of icon is displayed)  icon: icon that normally displays  pressedIcon: icon that displays while a button is depressed  rollOverIcon: icon that displays when mouse touches this component Horizontal Text Position: designates whether icon comes before or after the text (Leading vs. Trailing) Use a label without text to insert a regular picture

Implementing Radio Buttons You can add radio buttons to your form in the same way you add other objects In order for radio buttons to work as a group, you’ll have to add a ButtonGroup object for each group of radio buttons Because the ButtonGroup is not a visible object, you’ll have to add it to the code manually and then add the radio buttons to the group.  Differs from VBs group control. Java ButtonGroup is a logical grouping of buttons

Page 7 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing

First, you need to import the ButtonGroup class  Add import javax.swing.ButtonGroup; to the rest of the import statements. Next, you instantiate a ButtonGroup  Locate the initialize() method  Add the following lines to the end of the method ButtonGroup grpName grpName.add(rdo1); etc.

= new ButtonGroup();



Replace grpName and rdo1 with the names of your objects Finally, create events for each radio button  Right-click the button (as with all objects)  I recommend using the itemStateChanged event

Combining Event Handlers As in VB, you can combine event handlers for multiple objects, but once again, you’ll have to manually modify the class code If you’re combining events, don’t create the embedded code classes (event code) for the buttons. Delete them if you already did. First we’ll modify the class definition to handle nonembedded events  Locate the public class statement  AFTER the extends JFrame clause add implements ActionListener (if combining command buttons) implements ItemListener (if combining radio buttons)  NOTE: until you complete all the steps below, the class name will report an error. The event listener classes also need to be imported: import java.awt.event.*;

Page 8 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing

Next, for each radio button (or command button) you need to tell Java the form itself will be listening for the events  Locate the initialize() method  Add the following to the end of the method rdo1.addItemListener(this);

or btn1.addActionListener(this);



Repeat for each radio button or command button

Finally, we need to add a method to process the itemStateChanged event (for radio buttons) or the actionPerformed event (for command buttons).  These methods process all events of the appropriate type I normally place this method below the initialize method public void itemStateChanged(ItemEvent ie) {

or public void actionPerformed(ActionEvent ae) {

The parameters (ie, ae) are like the sender parameter in VB—they allow us to determine which object caused the event  Because Java has such a limited (select) case structure, we’ll have to use an if-else if-else structure to determine which object caused the event JRadioButton whichButton = (JRadioButton)ie.getSource(); if (whichButton==rdo1) //java code here; else if (whichButton==rdo2) //java code here; else if (whichButton==rdo3) //java code here; //etc. else //code for last button here; //End If

Page 9 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing



The first command uses the getSource method to figure out which radio button caused the event  This object is saved in a variable of the appropriate type. Using the variable in the if statements should be faster than using getSource over and over again. It’s the easiest thing in the world to code, but it works.

Implementing Check Boxes Add check boxes to the form just like other objects Normally, each check box processes differently. Use an embedded class (itemStateChanged) to handle the event code If you want to combine event code for check boxes, use the same technique (ItemListener, not ActionListener) that is used for radio buttons. Sometimes, check boxes don’t have event code. Other methods simply check to see if the check box is checked and process accordingly. if (chkPartTime.isSelected()) //java code here;

Implementing Date Pickers

Create a new visual class called dtpSample

Java Swing does not include a Date Picker class that you might be used to from VB. Add the javadatepicker However, there are open source Date Picker classes archive to the project available on the web, one of which I’ve downloaded to the I: drive from javaboutique.internet.com The class that implements the Date Picker is stored in a Java Archive (.jar) file: javadatepicker.jar After creating your project file, I recommend you copy this archive file into the project folder. To provide your application access to this archive file:  Right-click the project folder in the Package Explorer  Choose Build Path Add External Archives  Locate the .jar file you copied to your project folder  The javadatepicker.jar file should now appear in the Package Explorer list and the rest of your classes should now have access to the JDatePicker and JMonthView classes. Note: you don’t have to uncompress the .jar to use the Java class within it.

Page 10 of 15

Instructor’s Notes

Java - Beginning

Unfortuately, the JDatePicker and JMonthView don’t appear in the Palette. You’ll have to add them to your application manually.  NOTE: I recommend you add objects that are available in the palette to your form first, then add the Date Picker code in the appropriate place.  The first thing you’ll need to do is import the appropriate classes import com.standbysoft.datepicker.DefaultMonthModel; import com.standbysoft.datepicker.JDatePicker; import com.standbysoft.datepicker.JMonthView;

com.standbysoft is embedded in the .jar file 

For each date picker you need, define a pointer (variable) for the date picker in the JFrame class (under the JContentPane definition) private JDatePicker enrollDate;

GUI Classes and Swing

Change to FlowLayout Add btnLongDate ―Display Long Date‖ Add btnChristmas ―Select Christmas‖ Add lblLongDate width 200 no text Add the standbysoft import statements import java.text.*; import java.util.*; Define a DatePicker named dtpSample

This defines the variable, but doesn’t instantiate it. 

Next, we’ll instantiate a new date picker Using the examples provided by the Visual Editor, the following seems to be the approved method Create a new method that instantiates the date picker and sets any additional properties you may need (min max date for instance)

Create a method to instantiate dtpSample Set width 200

private JDatePicker getEnrollDate() { if (enrollDate == null) { enrollDate = new JDatePicker(); //Object customization here } return enrollDate; }

Page 11 of 15

Instructor’s Notes



Java - Beginning

Next, we’ll call this method to add the date picker to the appropriate panel This might occur in the GetJContentPane method. Insert this command after the command that sets the content pane layout

GUI Classes and Swing

Add the DatePicker to the content pane above the label

jContentPane.add(getEnrollDate(),null);

You should now see the date picker on your form ▪ If not, try saving the project Code btnDisplay to change the label to show the varCalendar.setTime(varDate); currently selected date in Note, getSelectedDate returns a Date class which Long format cannot be directly assigned to a Calendar. The second statement transfers the Date class to the Code btnChristmas to Calendar. change the date pickers datePicker.setSelectedDate(varCalendar); current date to 12/31 of current year.

Setting and getting the month value of a Date Picker  varDate = datePicker.getSelectedDate();



Responding to the Date Picker date changed  Right-click the Date Picker on the form and choose Events from the popup menu  Note, no default events appear  Choose Add Events... A list of event type appears  Expand dateSelection  Choose dateSelectionChanged  Click Finish  



Code date picker dateSelectChanged to immediately display the long date format in the label

Java will add the DateSelectionListener embedded class to your code. This class includes three methods You cannot delete the unneeded methods, you must implement them when you use DateSelectionListener Simply leave the code section blank Add the appropriate code within the dateSelectionChanged method

Page 12 of 15

Instructor’s Notes

Java - Beginning

Month View objects are created in the same manner, but the class needs to know what type of model the Month View should use  A Month View always displays a complete monthly calendar.  Models control how the Month View appears and behaves. I have not experimented with different models yet (I was just happy to get the Month View on the form)  Declare the Month View and Model variables private JMonthView birthDay; private DefaultMonthModel monthModel;



Create a method to instantiate the Month View, setting its model.

private JMonthView getBirthDay() { if (birthDay == null) { monthModel = new DefaultMonthModel(); birthDay = new JMonthView(); birthDay.setMonthModel(monthModel); } return birthDay; }



GUI Classes and Swing

Copy dtpSample class Paste naming MonthViewSample Remove all date picker code. Define the standard month model Define a MonthView variable called monSample

Create a method to instantiate the monSample, instantiate monthModel, set monSample monthModel

Add monSample to the Content Pane after label

Add the Month View to the form

jContentPane.add(getBirthDay(), null);

Page 13 of 15

Instructor’s Notes

Java - Beginning

Setting and getting the month value of a Month View  The Month View control is more complicated that the Date Picker (when it comes to selecting dates) Date Pickers allows you to select one date; Month Views allows you to select multiple dates  Because of the underlying complexity, setting or getting a single date from the Month View is more complicated.  Set:

GUI Classes and Swing

Code btnDisplay to change the label to show the currently selected date in Long format

monSample.getDateSelectionModel() .setDateSelectionIterval (myDate.getTime(), myDate.getTime());

Underlying the Month View is a Date Selection Model that controls how dates are selected This command gets the Date Selection Model for the Month View (monSample) and sets the interval of selected dates ▪ Remember, a Month View can have multiple selected dates ▪ To select only one date, the start date and end date are set to the same value 

Get: myDate = monSample.getDateSelectionModel() .getAnchorSelectionDate()));

Again, the Date Selection Model is accessed, but this time the getAnchorSelectDate method is called to determine the first date in the selection. ▪ Since we only expect one date to be selected, the first one should be the only one.

Code btnChristmas to change the date pickers current date to 12/31 of current year. Code date picker dateSelectChanged to immediately display the long date format in the label

Responding to the Month View date changed  See instructions for responding to date picker changed above.  Actually, the Month View responds to the date selection (may be multiple) changed  When inside the dateSelectionChanged method, the event parameter (e) provides a simpler access to the anchor selection date. myDate = e.getFirstDate();

Page 14 of 15

Instructor’s Notes

Java - Beginning

GUI Classes and Swing

Centering a Form In the initialize module, after the SetContentPane command, enter: this.setLocationRelativeTo( null );

Page 15 of 15