• No results found

User Interface method, we can start by creating a button with a label like this:

N/A
N/A
Protected

Academic year: 2021

Share "User Interface method, we can start by creating a button with a label like this:"

Copied!
19
0
0

Loading.... (view fulltext now)

Full text

(1)

Lab 1

This lab includes basic revision: what are a class, object, and constructor? What is a variable declaration? What do private and public mean? What does void mean?

Objects and Classes

We know what an object is: a table, ball, person, for example. In our GUIs we will use objects like buttons, text fields, layouts and colours. In a GUI Nils has probably written at some time, his button might have the label “OK” on it; whereas Ivan may have a button with “Exit”. These two buttons are two individual buttons; they are separate instances of buttons. But they have things in common: each has a label, each can be pressed and (hopefully) something will happen when you press the button. A class is a kind of a description, a model or a blueprint for an object in general in this example describing these common features that all buttons have. Using the pre- defined class Button: which has a setLabel() and an addActionListener() method, we can start by creating a button with a label like this:

Button nilsButton = new Button(); //creates the button nilsButton

nilsButton.setLabel(“OK”); //gives it a label In Java you create an object of a class with the reserved word new.

Note that the first word in this definition, Button , says what kind of object we want to create (something described by the Button class), whereas the second time it appears, it looks like this: Button() with parentheses. This is obviously a method. In fact, it is a special method called a constructor (see below).

Next we can use the other pre-defined method from the Button class mentioned above:

nilsButton.addActionListener(this);

that tells Java to keep an eye on this button in case it gets pressed. And when it does get pressed, what happens? Nothing. Nils will have to write a method to say what will happen and it will look like this:

public void actionPerformed(ActionEvent e) { … }

What you should note here is that setLabel and addActionListener are

predefined in the Button class. We can use them for all our instances when creating buttons (objects); we do not have to define them ourselves for every button we create.

This is what classes are all about!

In summary, Button is a class that describes buttons in general. nilsButton is an instance of that class or, in other words, an object.

Declare/Initiate variables

When you declare a variable it’s automatically given a default value; when you initiate a variable you give it a new value.

Example:

private int number; //Declaration of an integer, gets the default value 0 number = 3; //Initiation of number to 3

(2)

You often put the initiations of instance variables in a constructor. A constructor is a method in a class that has the same name as the class.

Public and Private

These words specify accessibility of classes, methods and variables.

¾ Public: Variables and methods can be used in this class and also reached from other classes.

¾ Private: A variable or method can only be used in the class where it is defined.

Any variable declared inside a method is private, ie. it exists only in this method.

Here is an example of a public method defined in the Math class:

public static double max(double a, double b)

Of course this method must be public so that we can all use it in our own programs (classes). If it were private, it would be of no use to us, we could not reach it from our classes. As it is public, we can now write, for example:

double largest = Math.max(3.0, 3.01)

An example of a private method in the Math class is how to set the value of π. We can’t use this method, we can’t even see it. For us it doesn’t exist (this is what the compiler would tell us if we tried to access it). What we can use, though, is the value

Math.PI, obviously declared public so that we can use it.

As you work your way through these labs, check what is private and what is public

and explain them (to yourself). (Hint: this is a favourite question when it comes to the test!)

In the first exercise you have some Java code already prepared. The code is in two separate classes Lab1 and Oompa1. Why two classes?

Exercise1.1: Look at the code in Lab1 and Oompa1. The class Lab1 contains the main method that is called first at execution, ie. this is where the program starts. The file Oompa1 does not have a main method and must therefore be started from Lab1.

In Java you create an object of a class with the reserved word new and then the class name followed by “( )”.

Create an object of Oompa1 in the main method of Lab1 and name it oompa1.

Look at the Oompa1 class. It only has one variable – a String labelled name that is not yet defined.

• Give your oompa a name.

The oompa is yet not turned on.

• Declare in Oompa1 a private boolean variable named awake and set it to

false. This will symbolize that the oompa is turned off.

• Try to change awake to true in Lab1 from oompa1: oompa1.awake = true; What happens and why?

• Change awake to public and try again. What happens now and why? Change it back to private.

(3)

• Write two public void methods – turnOn() and turnOff() in Oompa1 that will change awake to true and false. Print out a line in each method for example

System.out.println(“The oompa is now awake!”); that tells the state of the oompa. Use them in Lab1.

• Explain what void means.

Return statement

The return statement is extremely useful when you are working with several classes. It will return a copy of a variable to where the method was called.

Example:

In Class1:

int number = class2.getValue();

In Class2:

private int getValue() { //int is the return type

return value; //A private variable in Class2

}

Exercise1.2:

• Write two methods - getName() that will return the variable name, and

setName(String new_name) that will change the name of the robot.

Constructor

A constructor is a method that is automatically called every time you create a new object. If you don’t write your own constructor, Java will create a default-constructor (empty) for you. It’s possible to define several constructors, but the type/number of arguments must differ.

Example:

public Oompa1() {} //An empty constructor public Oompa1(String new_name) {//A constructor that sets a variable name = new_name; }

Oompa objects can then be created either with new Oompa1() or new Oompa1(“name”).

Exercise1.3: In Exercise 1.2 you only used the automatically generated default constructor.

Write your own constructor in Oompa1 with no parameters where you initiate the variable name and awake. That means you have to move the initiations inside the constructor.

• Write a second constructor that takes a String new_name as an argument and changes the name of the oompat.

Now create two Oompa1 objects, one with new Oompa1() and a second with new Oompa1(“myName”). Name the objects oompa2 and oompa3.

(4)

Now write one more constructor that takes both a String new_name and also a

String gender argument that will make your oompa male or female. When you use this constructor, eg. Oompa1 oompa4 = new Oompa1("Betty", "female"); it will print out this:

Oompa Betty is female

(5)

Lab2

In this lab we will revise: static, private; and type conversions. We will also recall dialogue boxes. For these we will need to import the swing package.

Remember that swing makes graphical components available to us (eg. the dialogue boxes in the JOptionPane class.

In Lab2 we will meet different types of oompas (entertainers, cleaners, and guards).

We will distinguish them by giving each type of oompa a number. So an entertainer will be given the value 0, a cleaner 1 and a guard 2. We will still use the name

entertainer, for example, so that we don’t need to keep track of what number signifies what category. By choosing numbers to represent categories, we avoid a situation where a robot has two categories: a 0 cannot also be a 1, etc. In this lab the oompa object communicates via dialogue boxes.

The two short dialogues in this lab are to show how to easily get information from the user (first to select an oompa type and secondly two ask the user for two numbers that should be added together – something every decent oompa should be capable of.)

Static

Normally an object has its own copy of variables, eg. in Lab1 each oompa had its own name, its own state of wakefulness. When a variable is declared static, though, there only exists one instance. A static variable is also accessible without having to create an object of the class containing the variable.

Example:

int state = Oompa2.entertainer //entertainer is a static variable in class Oompa2

As you can see, you access this variable by stating the name of the class, then a dot and then the name of the variable. You can do this even without creating any objects of the Oompa2 class. Going back to PI, we can write:

double area = Math.PI * radius * radius; //no objects involved

Here geometric shapes (objects) can share the static PI. They do not need their own copy.

Final

Final is used to describe a constant, ie. a kind of variable that will not change value during execution of the program. Going back to a previous example, we have

public static final double PI;

in the Math class. It will always provide the same value. Note that PI is written in capital letters. This is a convention in Java. It makes it easy to spot them (you probably remember typing Font.BOLD previously, where BOLD in the Font class is defined as static and final). As our entertainer is always going to be referred to as 0, we declare it as final and thus change the letters to capitals:

int state = Oompa2.ENTERTAINER //entertainer is a static final variable in class oompa2

Type Conversion

(6)

It’s often necessary to do type conversions between for example int and double values, or text and numbers. Sometimes this is done automatically, like a conversion from int to double where no precision is lost. But other times you must force a conversion, like from double to integer where the decimals are lost. An explicit type conversion can be made by (type) in front of the variable to be converted.

Example:

int i1 = 2;

double d1 = d; //type conversion, no precision lost

double d2 = 2.52;

int i = d2; //loss of precision, Java does not compile

int i = (int) d2; // Ok! You force Java to convert. This is called a cast.

// What is the value of i?

Everything the user of your program types as user input is a string, even if you type, for example, 30. If you want to convert String to int you use the method

parseInt() in class Integer, and corresponding parseDouble() in Double for a double value conversion.

Example:

String str1 = “134.56”; //eg. The user has typed in 134.56

double a = Double.parseDouble(str1); //type conversion from String to double

Exercise 2.1 First have a look at the files Lab2 and Oompa2. JOptionPane has several methods for showing different standard types of input and output dialogs.

They can also be modified in a number of ways. The default language for the buttons and title bar of the dialog is the one installed on your system. Try to compile and run Robot2. It doesn’t do anything more than showing an input dialog right now.

• The System.exit(0); at the end of the main method is necessary to end the program correctly when using dialogs this way. Try to remove it and see what happens.

• The showInputDiolog() method ALWAYS returns a string. Save the input in a string called textinput. This can simply be done like this:

String textInput = JOptionPane.showInputDialog(and so on…

• Add an extra type of oompa in Oompa2, for example Guard or Cleaner. Give it index 1 or 2. Also change the input message text so that you can choose the new robot type for example “CLEANER”.

• To be able to change the state of a robot through the input dialog we have to convert the String input to an int. This can be done by

Integer.parseInt(textInput); Do this and save the integer in a variable called value.

• Now we want to create a method setType that changes the type of the Robot.

It will have an in-parameter new_type and it will set the variable type to the value input by the user.

(7)

Exercise2.2

• Look at Oompa2, it has an empty method called public void

getResponse(int value). We want a different response from the robot according to which type it is. Start by filling the method with:

if (type==ENTERTAINER) //if type is 0

System.out.println(“Robot says:\n Have you heard the one about Bellman?”);

• Continue with the other types and invent new suitable responses.

Exercise2.3

Every advanced robot needs to be able to calculate a sum of two integers.

• Create two new InputDialogs in Lab2 that save one number each to String variables, and then convert them to integers called number1 and number2.

• Write a method in Oompa2 that takes two integers as parameters and returns the sum, call the method “addNumbers”.

• Call the method from Lab2 with number1 and number2 and store the result in a variable called sum.

• Create a JOptionPane.showMessageDialog that displays the sum.

• Write another method “calculateMean” that takes two integers and calculates the mean value. You don’t have to use a dialog to display the result, just print it out in the console window. OBS! Type conversion to double is required.

Check out the numerous extra functions for JOptionPane in the Java API. You can for example change the title bar or the image shown in the dialog box. To change the title bar try:

JOptionPane.showInputDialog(null, "Message”, “Title”, JOptionPane.

INFORMATION_MESSAGE);

Exercise2.4

• What other types of dialog boxes are predefined in the JoptionPane class?

(8)

Lab3

In Lab3 we will look at some standard components for interfaces: JButton, JLabel, JFrame, ImageIcon, FlowLayout and ActionListener.

You will need three images for this lab (see coursepage). In the folder where you have the Lab3 Java file, create a new folder called images. Copy the three images into the images folder.

Here you will see the oompas you have already ‘met’ in Lab1 and Lab2. The aim is to create an interface, a window, with pictures of an oompa in different colours.

Schematically it looks like this:

Three buttons

grey red blue

Image

title

The grey button will load in a grey oompa. So let’s start by defining a window.

Fortunately this is easy – we just need to use a ready-made window in Java.

(Make sure you import java.awt.*, java.awt.event.* and javax.swing first.)

Then we can use (inherit) a JFrame using the keyword extends when defining the class:

public class Lab3 extends JFrame { }

The first thing you normally do now is to decide which components you need (eg.

Buttons) and declare them. But let us take a quick look ahead at the constructor in this class. You can’t just put components straight into the JFrame. We will need

something to put the components in – a container. So the constructor starts like this:

Lab3() {

Container c = getContentPane();

c.setBackground(Color.white);

c.setLayout(new FlowLayout());

…)

Exercise 3.1

• Why do you have to import java.awt.event.* when you have already imported java.awt.*?

What does the J in JButton, etc mean?

The layout manager in this GUI is a FlowLayout. What does this mean?

(9)

Exercise 3.2

Putting an image in the frame is done in four steps. The components you need in the four steps below will be declared at the beginning of the class. Actually doing something with the components is done in the constructor.

1. Put the image into an ImageIcon object. Start by creating an ImageIcon object that is just waiting for an image to come along.

private ImageIcon robotImage1; //variable declarations at top of class 2. In the constructor put the image in the ImageIcon object:

oompaImage1 = new ImageIcon("images/oompaGrey.jpg");

3. To place the ImageIcon in the frame, it must be in some sort of container. Here we use a JLabel. Assuming that in your declarations at the top of the file you have something like:

private JLabel imageLabel;

you can then write:

imageLabel = new JLabel();

imageLabel.setIcon(oompaImage1);

4. Now we are down to the final step – putting the Label into the container in the frame – this should look familiar:

c.add(imageLabel);

Let’s continue with the grayButton.

Exercise 3.2

• You will find some of the code above already in the file Lab3 to provide some structure to the program. Complete it according to the instructions.

• You will also need to load the images oompaRed.jpg and oompaBlue.jpg.

Prepare this.

Exercise 3.3

Right. Let’s now go back to the declarations. As you see the grey button has already been declared:

private JButton grayButton;

• Add the red and blue buttons.

• Follow the code in the constructor for the grey button and do likewise for the other two buttons.

• Make sure the colour of the label in the buttons is appropriate.

• The size of the text in the buttons is too big. Reduce it to something more appropriate.

Exercise 3.4

Explain each of these five lines at the end of the constructor.

setTitle("Oompa Color Manipulator");

setResizable(false);

setSize(340,262);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

When you press a button you will want something to happen (in this case change the image). To get this to happen you need to do the following:

(10)

Exercise 3.5

• When defining the class you have to say that events will take place (when you press the buttons), so complete the introduction so that it looks like this:

public class Lab3 extends JFrame implements ActionListener {…

• Explain each line of code in the actionPerformed method.

• Add similar code to deal with the red and blue buttons.

• The buttons:

You have declared them.

You have defined them in the constructor.

You have told the class that you want an ActionListener.

You have defined an actionPerformed method.

But still they do not do anything. Why not?

Add three lines of code to get them working.

Exercise 3.6

Here we will just look at some extra features of the GUI..

• .The method setEnabled works on all objects of type Component. Try for example to disable a button and see what happens. Put the following line in at the end of the constructor:

grayButton.setEnabled(false);

• Change places among the components so that the buttons come first and the image last (to the right of the buttons).

• Add another button. You do not need to add anything to the actionPerformed method, ie. it does not have to do anything.

How does it affect the layout?

• Change the background colour of the GUI.

• Change the background colour of the buttons.

• The text in the label of the buttons is currently with serifs. This is commonly assumed to be a bad choice for this kind of text on the screen. Change it so that the text is without serifs.

(11)

Lab4

This lab presents a number of useful components and layout managers for interfaces.

They include BorderLayout, Color, JPanel, JTextArea, and JComboBox..

Let’s start with a layout manager. In Lab 3 you used a FlowLayout where each new component is simply placed after (to the right of) the previous one and where

components are centred both horizontally and vertically. The image of the robot was placed first and then came the colour-changing buttons.

BorderLayout.specifies more closely where you place components. Schematically it works like this:

west east center

north

south

If north or south is not occupied, the other regions expand vertically to fill the space.

If east or west is not occupied, the centre region expands horizontally. But better than words, do the following.

Exercise 4.1

Here is the code for a simple BorderLayout program. Go through the code to see how the program works. Copy and paste the code into JpadPro and run the

BorderLayoutTester program. (It doesn’t do very much, but it is the layout we are concerned with here.)

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class BorderLayoutTester extends JFrame {

private JButton northButton, southButton, eastButton, westButton, centerButton;

BorderLayoutTester () {

Container c = getContentPane();

(12)

c.setLayout(new BorderLayout());

northButton = new JButton("North");

southButton = new JButton("South");

eastButton = new JButton("East");

westButton = new JButton("West");

centerButton = new JButton("Centre");

c.add(northButton, BorderLayout.NORTH);

c.add(southButton, BorderLayout.SOUTH);

c.add(eastButton, BorderLayout.EAST);

c.add(westButton, BorderLayout.WEST);

c.add(centerButton, BorderLayout.CENTER);

setSize(300,250);

setVisible(true);}

public static void main (String[] args) { new BorderLayoutTester();

} }

Note that components fill the whole area.

• Comment out one or more Buttons and compare the result with the description above, eg.

//c.add(eastButton, BorderLayout.EAST);

and view the result..

• Compare it with FlowLayout. Comment out all the lines like the one above.

Change the layout manager to FlowLayout and add the buttons as you did in Lab3.

Next we create a new colour and try it on one of the buttons. This is easily done using the Color class. Assume you want a nice autumn colour and name it myDarkRed. Add these lines to the BorderLayoutTester program after defining the northButton.. The numbers are RGB values.

Color myDarkRed = new Color(200, 50, 50);

northButton.setBackground(myDarkRed);

//note the difference in syntax in the following line

northButton.setForeground(Color.white);

Exercise 4.2

• Colour some more buttons in the program with colours of your own.

• In the last line of code above, white is a predefined colour in Java. What other colours are predefined?

(13)

Oompas like to build robots. We will use a BorderLayout to produce a shop for oompas. It will look like this:

or schematically

Textarea showing what has been ordered, what items cost and what the total price is Pictures of items

List of items to purchase

button button

logo

Each of the regions in a BorderLayout (north, south, etc) can have a layout of its own.

In this lab we will use all but the centre region. To put components – including layouts – in these, we need a container so we choose a JPanel for each of them. We’ll call the JPanels topPanel, leftPanel, rightPanel and bottomPanel and it should be obvious which will go in the north region, south region, etc.

(14)

As a preliminary, copy the folder imagesLab4 from the course site and put it into the same folder as the file Lab4.

Let’s start with the topPanel. This is where the logotype is going to go. The logotype is a png-file found at Lab4images/RobShop.png. Let’s get this file ready in the same way as the robot image in Lab3 – make it an icon, put it in a JLabel and put the JLabel into topPanel.

In the declarations at the top of the program write:

private ImageIcon logo;

private JLabel logoLabel; private JPanel topPanel;

In the constructor we define the panel and state what we want in it. In this case we want to place the logotype image, so we need:

logo = new ImageIcon("Lab4images/Robshop.png");

logoLabel = new JLabel(logo);

topPanel = new JPanel();

topPanel.add(logoLabel);

Exercise 4.3

• Set the topPanel’s background to black.

• Then add the following line of code (you can guess what it means, more explanation later):

topPanel.setPreferredSize(new Dimension(300,50));

• Finally we put topPanel into the GUI:

c.add(topPanel, BorderLayout.NORTH);

OK, three more regions to go. Let’s do the left panel – the most difficult. In the diagram above it looks like we have to add two components – a list of items and images of these items. In reality the list of items is a drop-down list (JComboBox) so we need some space before the images so that the list does not cover the image. (We also need to ‘fill out’ before and after the components – otherwise it will look ugly, so what we really have in the leftPanel is this):

space image space JComboBox

space

So what kind of layout will give us a vertical layout? The answer is a BoxLayout. It arranges components either vertically, BoxLayout.Y_AXIS (or horizontally

BoxLayout.X_AXIS ). This layout is good for creating precise columns (vertical) or rows (horizontal). We need the vertical one. Let’s do the layout first and then add the

(15)

components (the sizes of the components have been made by experimentation; they vary according to your aesthetic requirements).

Exercise 4.4

Following the instructions above for the topPanel:

• Declare a JPanel called leftPanel.

• Define leftPanel in the constructor

• In the constructor give the panel a preferred size of 200, 250.

leftPanel.setPreferredSize(new Dimension(200,250));

• Give it a background colour of blue

• Give it a BoxLayout manager like this:

leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.Y_AXIS));

• Add the components, first the spaces (that are not negotiable) – just accept the sizes, as stated above:

leftPanel.add(Box.createRigidArea(new Dimension(200,20)));

leftPanel.add(Box.createRigidArea(new Dimension(200,90)));

leftPanel.add(Box.createRigidArea(new Dimension(200,20)));

Now we come to the interesting parts – a JComboBox asnd the images that come between the spaces.

Exercise 4.5

• First declare a JComboBox that will present the items that are on sale:

private JComboBox itemSelector;

In the constructor you will need to state what items can be selected:

itemSelector = new JComboBox();

itemSelector.addItem("Choose Item:");

You will also need the following items:

”Visor"), “Fuel cells” and “Jump Springs”.

and add an Action listener so that Java can keep an eye on what is selected:

itemSelector.addActionListener(this);

• Add the itemSelector to the leftPanel in the right place We have now created a drop-down list of the items for sale.

To ‘get hold of’ the choices in a JComboBox we use the method

getSelectedIndex() which ranges from 0 and up. We will say that when

getSelectedIndex() == 0 is called, something will happen.

What happens when you make a choice? The first thing is to present the png-images corresponding to these items. This is done in the actionPerformed method, ie. if you have selected a certain item, then present its image.

To present an image we need to do the same as we did to put the logotype file into a panel - make it into an icon, put it in a JLabel and this time put the JLabel into leftPanel.

Exercise 4.6

(16)

We begin by declaring each image as an icon in the declarations at the top of the file.

We need to be ready for the following four files:

Lab4images/Empty.png // before a choice has been made Lab4images /Visor.png //image

Lab4images /Fuelcells.png //image Lab4images /Springs.png //image

• In the declarations add:

private ImageIcon empty, visor, fuel, springs;

In the constructor define each file as an icon:

//no image when the JCombobox is presented at the beginning

empty = new ImageIcon("imagesLab4/Empty.png");

visor = new ImageIcon("imagesLab4/Visor.png");

fuel = new ImageIcon("imagesLab4/Fuelcells.png");

springs = new ImageIcon("imagesLab4/Springs.png");

Looking at the picture of the GUI we are aiming for, we can see that there is a place in the leftPanel for an image. This place is a JLabel – just what we want for putting our icons in. Let’s define it.

Exercise 4.7

• In the declarations you will need

private JLabel imageLabel;

and in the constructor we add

imageLabel = new JLabel();

//we start with the empty image, nothing has yet been selected //in actionPerformed we will change this

imageLabel.setIcon(empty);

imageLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);

imageLabel.setAlignmentY(JLabel.CENTER_ALIGNMENT);

• We have the icons. We have a JLabel to put them in. Put the JLabel,

imageLabel, into the correct place in leftPanel:

Now we are ready to say what happens when an item in the JComboBox is selected.

The JComboBox we are using has been given the name itemSelector (see declarations). To choose one of its items we write:

if (itemSelector.getSelectedIndex() == 0) { } //first item if (itemSelector.getSelectedIndex() == 1) { } //second item

Let’s do so. These lines of code obviously belong in an actionPerformed method.

The actionPerformed method comes after the constructor. Here’s how it starts:

public void actionPerformed(ActionEvent e) {

if (itemSelector.getSelectedIndex() == 0) { imageLabel.setIcon(empty);

selectedIndex = 0;}

else if (itemSelector.getSelectedIndex() == 1) { imageLabel.setIcon(visor);

(17)

…}

As you can see, there are three lines of code for each choice.

The first is the test to see which item has been chosen in the JComboBox. The second selects the image and puts it in imageLabel in leftPanel.. The third is used for the next stage: if you have chosen visor which entails selectedIndex = 1; the 1 will later determine what is presented in the textArea.

Exercise 4.8

• Add the other conditions to actionPerformed for indexes 2 and 3.

• Put leftPanel into the GUI (compare with 4.3 above).

Now we are done with topPanel and leftPanel. Let’s turn to rightPanel. Here we want a JTextArea to write in. However, the JTextArea does not automatically come with a scrollbar. So rightPanel will be a scrollable area called a JScrollPane. We will put a textArea into it.

Exercise 4.9

• In the declarations add private JScrollPane rightPanel;

• In the declarations add private JTextArea textArea;

You will find these two methods useful in your textArea:

.textArea.setLineWrap(true);

textArea.setWrapStyleWord(true);

In the constructor add

rightPanel = new JScrollPane(textArea);

rightPanel.setPreferredSize(new Dimension(200,250));

rightPanel.setBackground(Color.white);

• Put rightPanel into the GUI (compare with 4.3 and 4.8).

Let’s turn our attention to the last JPanel, bottomPanel. This is the easiest one. It will contain the buttons (see diagram above).

Exercise 4.9

• In the declarations add private JPanel bottomPanel;

In the constructor give it a layout and a size:

bottomPanel.setLayout(new FlowLayout());

bottomPanel.setPreferredSize(new Dimension(400,40));

• Give it a background colour, black.

Next we need the buttons. We need one to write something in the textArea (the cart of items we are going to buy) and one to send in the order.

Exercise 4.10

• In the declarations define two JButtons: addToCart and order

• They are already defined in the given code

• Add them to bottomPanel

Add the following to actionPerformed:

if (e.getSource() == addToCart) { if (selectedIndex == 0) {

textArea.append("Choose an item below\n\n");

(18)

}

else if (selectedIndex == 1) { sum += 400;

textArea.append("Night Vision Visor CQW98 added to cart\n\n");

}

else if (selectedIndex == 2) { sum += 200;

textArea.append("24h Fuel Cells TT13 added to cart\n\n");

}

else if (selectedIndex == 3) { sum += 800;

textArea.append("Spring Jump System SSP-X added to cart\n\n");

} }

Finally we need to deal with the order button which confirms the order and presents the total sum of the prices.

Exercise 4.10

• Add the following to actionPerformed: else if (e.getSource() == order) {

textArea.append("Your order has been sent. Price: $" + sum + "\n\n");

sum = 0;

}

(19)

Lab5

In this lab we introduce menus, placing components exactly using coordinates, and sound.

Here you get fully functioning code and your job is to understand how it works.

When you have done this, create your own GUI. You can use the code from this program or any previous code on this course. Your GUI will have the following properties:

1. It will contain two menus and each menu item will function, eg. it will write a text or change the colour of some component.

2. Place three components in your GUI using coordinates: a button, a text area and an image (use the image from lab 3 if you don’t have any other one handy). When you press the button a text should appear in the text area.

3. Set the background colour of your GUI using your own defined colour.

References

Related documents

Additional information on “Backflow Prevention”: The user can cancel the Backflow Prevention by pressing the zero flow button and setting the required flow with the rotary knob..

• The field variables of an object can be used by any method of that object just like a variable defined in the method.. Access Outside

(optional except for main method, which is public): one of public - accessible to every user of the class.. private - accessible only

Findings of the study are clear indicators that public libraries can provide services that can help boost the employability of job seekers These services show that Nigerian

An instance variable declared as protected can be accessed by any non-static method of the class in which it is

If a class component (data member or method) is declared private, no outside methods can access it2. If a class component is declared public, any outside

• Methods that are declared either static or private are automatically final, so a class method or a private instance method can’t be overridden... 11.8 Inheritance in the

Our model gives two important characterisations of bubbles in economics: firstly, a rapid super-exponential growth; secondly, an illusion of certainty as described by a