graphical user interfaces (gui)

Click here to load reader

Upload: apollo

Post on 24-Feb-2016

89 views

Category:

Documents


0 download

DESCRIPTION

Graphical User Interfaces (GUI). PART ONE. About GUI’s. GUI’s are important because it’s an effective way for the user to interact with the program. The way Java allows you to create GUI’s is the Abstract Windowing Toolkit, or AWT. The java.awt package includes : - PowerPoint PPT Presentation

TRANSCRIPT

Graphical User Interfaces (GUI)

Graphical User Interfaces (GUI)1PART ONEAbout GUIs2GUIs are important because its an effective way for the user to interact with the programThe way Java allows you to create GUIs is the Abstract Windowing Toolkit, or AWT. The java.awt package includes:Buttons, checkboxes, labels, other basic componentsText fields, text areas, and other more complex componentsDialog boxes and other windowsDrop down boxes and other menus

3ButtonsFirst, heres an example of code to produce a basic AWT component the button:

import java.awt.*;public class SimpleButton extends java.applet.Applet {Button helloButton = new Button(Hello World!);public void init() {add(helloButton);}}The result of this code is this:

4LabelsNow, labels... Labels just give information to the user. They cant be changed, you set their text when you initialize them. For example, a label might say what to enter into a text field.

Label eMailLabel = new Label("E-mail address: ");add(eMailLabel);

The result of that is: Email address:

5Text FieldsText fields allow the user to input data in such as their name. Text fields allow only one line of text. You decide how big the text box is by telling it how big in characters wide. So if you put it to be 10 characters wide, itd be big enough to fit 10 characters, NOT 10 pixels wide. Also, you can give it a starting text when you initialize it.TextField txtName = new TextField(Donny, 10);add(txtName);

The result of this code is this :

6Text AreasNow, text fields can only hold one line of text. What if you want to have a multi-line input area? Well, you can use a text area for that. With a text area, you specify how high and how wide in characters the text area is. So, lets say you wanted one 20 characters wide and 3 characters tall:

TextArea comments = new TextArea(This is on line 1\nThis is on line 2, 3,20);add(comments);

The result of this code is this:

7Check BoxesA check box is a box which has two values, true or false, and a label beside it describing what it is. Another thing is the option box, or radio button. Radio buttons can only be in groups, and only one of them can be selected at a time.Checkbox goodTutorial = new Checkbox(Is this a good tutorial?);add(goodTutorial);The above code will create a checkbox with no value (False)The result of this code is this:

Now, you can also set the default value to true if you want by changing it to this:Checkbox goodTutorial = new Checkbox(Is this a good tutorial?, true);add(goodTutorial);The result of this code is this:

8Radio Buttons (or Option Boxes)Radio buttons are a bunch of option boxes in a group. Only one of then can be checked at a time. This is useful if you need to give the user a few options where only one will apply, for example what age range they are. First, you need to create a checkbox group and then specify that certain checkboxes are part of the group. Finally, you add the checkboxes to the screen.

CheckboxGroup age = new CheckboxGroup();Checkbox chkUnder10 = new Checkbox(Under 10 years old, false, age);Checkbox chk10to15 = new Checkbox(10 to 14 years old, false, age);Checkbox chk15to20 = new Checkbox(15 to 19 years old, true, age);Checkbox chkOver20 = new Checkbox(Over 20 years old, false, age);add(chkUnder10);add(chk10to15);add(chk15to20);add(chkOver20);

The result of this code is this:

9Drop Down ListsDrop down lists are lists of different options that you can select. Only one is shown until you click to bring up the rest. These are the same as radio buttons except its in a list.First, you need to create the choice object, and then you add different text to the choice. Finally, you add the choice object to the screen.

Choice textAlignment = new Choice();textAlignment.add(Left);textAlignment.add(Center);textAlignment.add(Right);textAlignment.add(Random);add(textAlignment);By default it will look like this:But after you click on the arrow, it expands to show all option:

10PanelsA panel is an object which holds other objects. Its just a container to organize and arrange your GUI better. Once, you learn about Layout Managers youll see why panels are a useful tool. For now, just know that theyre useful. Heres an example of a set of buttons added into a panel:

Panel myPanel = new Panel();myPanel.add(helloButton);myPanel.add(goodbyeButton);add(myPanel);

It looks no different than if you just added the buttons regularly, but youll see why you might want to use panels later on... This is what it looks like:

11Layout ManagersUp until now, all the objects on screen have been displayed on screen in no particular fashion. Theyre added in the order you use the add( command. If youve experimented with the code and added more of any object, youll see that theyre left to right until theres no more room, and then they go to the next line. But layout managers allow you to organize the objects more. The default layout manager is the FlowLayout. You set the layout by creating a layout object and setting the layout to that object. FlowLayout myLayout = new FlowLayout();setLayout(myLayout);Heres an example of a bunch of buttons using the FlowLayout manager:Button btnHey = new Button(Hey);Button btnHow = new Button(how);Button btnAre = new Button(are);Button btnYou = new Button(you);Button btnQuestion = new Button(?);add(btnHey); add(btnHow);add(btnAre); add(btnYou);add(btnQuestion);

The result of this code is this:

12Now, there are other layout managers. Theres the GridLayout manager which, as you might have guessed, arranges the objects on the screen like a grid. You specify how many spaces high and how many wide. This will create a grid 2 spaces high and 3 wide:

GridLayout myLayout = new GridLayout(2, 3);setLayout(myLayout);

The result of this code is this:

13There is yet another layout manager: the BorderLayout manager. It lets you choose where the objects are placed north, south, east, west, and center.With this layout manager, it nothing changes when you create the buttons, but when you add them to the screen you must specify where they go:

BorderLayout myLayout = new BorderLayout();add(btnHey, North);add(btnHow, West);add(btnAre, Center);add(btnYou, East);add(btnQuestion, South);The result of this code is this:

14Also, you can specify how far apart the objects are by adding a few parameters to the constructor. This would make all objects 10 pixels apart from each other on the X axis and 15 apart on the Y axis:

BorderLayout myLayout = new BorderLayout(10,15);

The result of this code is this:

15Now, youre probably wondering Well, Ive learned about panels... Ive learned about layout managers... but I still dont know why Id want to use a panel! Well, this is why youd want to use a panel you can use different layout managers in different panels.

So, if its easier to layout one part with the GridLayout and another part with the BorderLayout, you can create two panels and use different layout managers where appropriate. Then you put all the panels together under whatever manager you like!16PART TWOUp until now youve only learned how to make a nice looking GUI, what youll learn now will teach you how to make them actually *DO* stuff! You do this using the java.awt.event.* package.17Setting Up Your ProgramTo receive events, first you have to include some packages and an interface or two. An interface is something which adds to your programs functionality. First, you must import the java.awt.event.* package:

import java.awt.event.*;

Next, you need to include one of the EventListener interfaces. This applet includes the ActionListener interface:public class MyApplet extends java.applet.Applet implements ActionListener {

18The EventListener interfaces enable a component of a graphical user interface to generate user events. Without one of the listeners in place, a component cannot do anything that can be heard by other parts of a program. A program must include a listener interface for each type of component it wants to listen to. If you need to include multiple interfaces, separate them with a coma:

public class MyApplet extends java.applet.Applet implements ActionListener, MouseListener {

Well, thats all you need to do to set up your program to listen for events. Next you need to make your components generate the events.

19Let Your Buttons Be Heard!After you let your program listen for the events, your components must generate them. To let a component generate an event, you use the addActionListener() method. For example, to make a button generate events, you would type:

Button clearForm = new Button(Clear);clearForm.addActionListener(this);

That code produces a regular looking button which generates an event. The this statement means the current class. The code creates a button and tells it to direct all events to this class to be dealt with.

20How To Handle EventsWhen an event is generated by a component, it is sent to the specified class to be handled. Each EventListener has its own method to be called. For example, with the clear form button the method that would be called is the actionPerformed() method. This is what the method looks like:

public void actionPerformed(ActionEvent evt) { // method goes here}21If there is only one component that will generate an event, you can put the code to handle that objects event right in the method. However, if there is more than one object that can generate an event, youll need to find out which one did it. To do that you can use the getActionCommand() function:

String cmd = evt.getActionCommand();

The getActionCommand() sends back a string. If the object is a button, itll be the caption of that button. If its a text field, itll send the text. To get the actual object that created the event, you can use the getSource() function.

22This will decide which object generated the event, between a Button named Fred, a text field named Texty, and another text field named James :

public void actionPerformed(ActionEvent evt) {Object source = evt.getSource();if (source == fred) {//Fred (the button) caused the event}else if (source == Texty) {//Texty (the text field) caused the event}else if (source == James) {//James (the other text field) cause the event}}

The getSource() function works with all objects to see which one caused the event23Check Box/Radio Button EventsCheck boxes and radio buttons (aka choice boxes) require a different ActionEvent interface namely the ItemListener interface. The following code produces a check box and adds the item listener stuff:

Checkbox goodTutorial = new Checkbox("Good tutorial?", true);goodTutorial.addItemListener(this);24Also, checkboxes receive events through the itemStateChanged() method. To see which checkbox caused the event, you can use the getItem() method. To check what value the checkbox or radio button has, you can use the getState() method. This will check which of two checkboxes caused the event and what value they are in:

25public void itemStateChanged(ItemEvent event) {String command = (String) event.getItem();if (command == "Item One's Caption") {boolean value = item1.getState();if (value == true) {//It's selectedshowStatus("Item 1 true");}else {//It's not selected)showStatus("Item 1 false");}}else if (command == "Item Two's Caption") {boolean value = item2.getState();if (value == true) {//It's selectedshowStatus("Item 2 true");}else {//It's not selected)sshowStatus("Item 2 false");}}}26Text Field EventsIf you want to get the text thats in a TextField before someone presses a button, you can do that as its changed. You do it with the textValueChanged method:

public void textValueChanged(TextEvent txt) {Object source = txt.getSource();if (source == name) {showStatus(Name + name.getText());} else {showStatus(Age + age.getText());}}27MiscellaneousHow to enable and disable components You may have seen some components grayed out so you cant edit them. Well, this is done with the setEditable(boolean) method. For example, this will let someone enable the button named fred: Button fred = new Button();fred.setEditable(true);

This will make it so it cannot be edited by users and is grayed out:fred.setEditable(false);

28