Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 311


Previous 1060 Stories (530 Pages, 2 Per Page) Next

The Java Lesson 31: Choice, List, and Checkbox controls

Go to all tips in Java Lessons by Jon Huhtala
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 31: Choice, List, and Checkbox controls

The Choice class

  • Is part of the java.awt package

  • Is an extension of the Component class

Object

Component

Choice

  • Creates a pop-up menu from which the user can choose a single item. The current item is displayed as the title of the choice menu. The application can cause some processing to be performed when a selection is made by

  1. Implementing the ItemListener interface

  2. Registering an ItemListener by calling the choice's addItemListener() method

  3. Coding an itemStateChanged() method within the registered ItemListener that defines the processing to be performed

When the user selects an item within the choice menu, an ItemEvent will be fired to the itemStateChanged() method of the registered ItemListener for processing.

  • Has a single constructor for instantiating a choice menu having no items. For example,

Choice parts = new Choice();

will create an empty choice menu. To add items to a choice menu, call its add() method passing it a string representing the text of the item to be added. For example,

parts.add("Framistan");
parts.add("Whatsit");
parts.add("Widget");

will add three items to the parts choice menu. By default, the first item added to the choice menu will be the current item and the preferred column size of the choice menu is determined by the size of its largest item (depending upon the layout manager).

  • Has many useful methods. Commonly used methods are:


Method

Usage

add()

Adds an item to this choice menu

addItem()

Adds an item to this choice menu. This is an older version of the add() method but is not yet deprecated.

addItemListener()

Adds the specified ItemListener to receive ItemEvent objects from this choice menu

getItem()

Gets the string at the specified index in this choice menu

getItemCount()

Gets the number of items in this choice menu

getSelectedIndex()

Gets the index of the currently selected item

getSelectedItem()

Gets the string representation of the currently selected item

insert()

Inserts an item into this choice menu at the specified position

remove()

Removes an item from this choice menu (overloaded)

removeItemListener()

Removes the specified ItemListener so it no longer receives ItemEvent objects from this choice menu

select()

Selects the specified item within this choice menu (overloaded)

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener, ItemListener {

Choice itemChoice;
Label price;
String[] items = {"Apples", "Bananas", "Grapes", "Oranges"};
double[] prices = {1.19, .79, .99, 1.49};

public static void main(String[] args) {
App myWindow = new App("Fruit market using Choice");
myWindow.setSize(400, 100);
myWindow.setVisible(true);
}

public App(String title) {
super(title);
addWindowListener(this);
setLayout(new FlowLayout());
add(new Label("Fruit selection"));
itemChoice = new Choice();
for (int i=0; i < items.length; i++) {
itemChoice.add(items[i]);
}
add(itemChoice);
itemChoice.addItemListener(this);
price = new Label("Select one of the " +
itemChoice.getItemCount() + " listed fruits to see its price");
price.setFont(new Font("SanSerif", Font.BOLD + Font.ITALIC, 16));
price.setForeground(Color.red);
price.setAlignment(Label.CENTER);
add(price);
}

public void itemStateChanged(ItemEvent e) {
price.setText(itemChoice.getSelectedItem() + " are " +
prices[itemChoice.getSelectedIndex()] + " per pound");
}

public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}

Notes:

  1. In order to become a registered ItemListener, the class implements the ItemListener interface

  2. The application class has instance variables for referencing the choice menu (itemChoice), an item price label (price), an array of item names (items), and an array of corresponding item prices (prices)

  3. The choice menu is instantiated and populated in the class constructor. The for loop adds each item name (from the array of item names) as an item in the choice menu. The choice menu is then added to the application frame and its ItemListener registered.

  4. Near the end of the class constructor, the price label is instantiated and added to the frame It initially displays the number of items available in the choice menu and prompts the user to choose one.

  5. The itemStateChanged() method is required by the ItemListener interface. It is automatically called when the user selects an item within the choice menu and receives an ItemEvent object as a parameter. In this sample, only one action will trigger this event so the ItemEvent object isn't tested or used. The method simply displays the name of the item the user selected and its price per pound.

The List class

  • Is part of the java.awt package

  • Is an extension of the Component class

Object

Component

List

  • Presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items. Clicking on an item that isn't selected selects it. Clicking on an item that is already selected deselects it. If the list only allows a single selection, selecting an item causes any other selected item to be automatically deselected.

  • Can fire both ActionEvent objects and ItemEvent objects. When an item is selected or deselected, an instance of ItemEvent is sent to the list's registered ItemListener for processing by its itemStateChanged() method. When the user double-clicks on an item in the list or presses the RETURN key while an item is selected, an instance of ActionEvent is sent to the list's registered ActionListener for processing by its actionPerformed() method.

  • Has a several overloaded constructors. For example,

List parts = new List(Cool;

will create an empty list capable of displaying 8 items without scrolling and only permitting a single selection. To create an empty list capable of displaying 5 items without scrolling and permitting multiple selections, one could code

List parts = new List(5, true);

To add items to a list, call its add() method passing it a string representing the text of the item to be added. For example,

parts.add("Framistan");
parts.add("Whatsit");
parts.add("Widget");

will add three items to the parts list. By default, the items will appear in the list in the order they are added and none will be initially selected.

  • Has a number of useful methods. Commonly used methods are:

Method

Usage

add()

Adds an item to this list (overloaded)

addActionListener()

Adds the specified ActionListener to receive ActionEvent objects from this list

addItemListener()

Adds the specified ItemListener to receive ItemEvent objects from this list

deSelect()

Deselects the specified item within this list

getItem()

Gets the string at the specified index in this list

getItemCount()

Gets the number of items in this list

getItems()

Gets an array of strings representing all items in this list

getSelectedIndex()

Gets the index of the currently selected item

getSelectedIndexes()

Gets an array of indexes for all currently selected items

getSelectedItem()

Gets the string representation of the currently selected item

getSelectedItems()

Gets an array of strings representing all currently selected items

isMultipleMode()

Determines whether this list allows multiple selections

remove()

Removes an item from this list (overloaded)

removeActionListener()

Removes the specified ActionListener so it no longer receives ActionEvent objects from this list

removeAll()

Removes all items from this list

removeItemListener()

Removes the specified ItemListener so it no longer receives ItemEvent objects from this list

replaceItem()

Replaces a specified item within the list

select()

Selects the specified item within this list

setMultipleMode()

Sets the flag that determines whether this list allows multiple selections

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener, ItemListener {

List itemList;
TextArea priceInfo;
String[] items = {"Apples", "Bananas", "Grapes", "Oranges"};
double[] prices = {1.19, .79, .99, 1.49};

public static void main(String[] args) {
App myWindow = new App("Fruit market using List");
myWindow.setSize(300, 200);
myWindow.setVisible(true);
}

public App(String title) {
super(title);
addWindowListener(this);
setLayout(new FlowLayout());
setBackground(Color.lightGray);
add(new Label("Fruit selection"));
itemList = new List(4, true);
for (int i=0; i < items.length; i++) {
itemList.add(items[i]);
}
add(itemList);
itemList.addItemListener(this);
priceInfo = new TextArea("", 4, 30, TextArea.SCROLLBARS_NONE);
priceInfo.setText("Select one or more of the " +
itemList.getItemCount() + " listed fruits to see the price");
priceInfo.setFont(new Font("SanSerif", Font.PLAIN, 12));
priceInfo.setEditable(false);
add(priceInfo);
}

public void itemStateChanged(ItemEvent e) {
if (itemList.getSelectedIndexes().length == 0) {
priceInfo.setText("You must select at least one item");
}
else {
StringBuffer temp = new StringBuffer("");
int[] selections = itemList.getSelectedIndexes();
for (int i = 0; i < selections.length; i++) {
temp.append(itemList.getItem(selections[i]) + " are " +
prices[selections[i]] + " per pound ");
}
priceInfo.setText(temp.toString());
}
}

public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}

Notes:

  1. In order to become a registered ItemListener, the class implements the ItemListener interface

  2. The application class has instance variables for referencing the list (itemList), an item price text area (priceInfo), an array of item names (items), and an array of corresponding item prices (prices)

  3. In the class constructor, the list is instantiated to display up to 4 items without scrolling and to allow multiple selections. It is then populated by the for loop which adds each item name (from the array of item names) as an item in the list. The list is then added to the application frame and its ItemListener registered.

  4. Near the end of the class constructor, the priceInfo text area is instantiated and added to the frame It initially displays the number of items available in the list and prompts the user to choose one or more.

  5. The itemStateChanged() method is required by the ItemListener interface. It is automatically called when the user selects or deselects an item within the list and receives an ItemEvent object as a parameter. In this sample, only one action will trigger this event so the ItemEvent object isn't tested or used. If no items are currently selected, the method displays a message advising the user to do so. Otherwise, it builds a multi-line message that shows the item name and price per pound of each selected item and sets it in the text area.

  6. When testing this sample, see what happens when the list constructor is modified to allow only a single item to be selected. Just change the second parameter in the constructor call from true to false or omit it entirely.

The Checkbox class

  • Is part of the java.awt package

  • Is an extension of the Component class

Object

Component

Checkbox

  • Is used to create a graphical component that can be in either an "on" (true) or "off" (false) state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on."

  • Can fire ItemEvent objects. When a checkbox is selected or deselected, an instance of ItemEvent is sent to the checkbox's registered ItemListener for processing by its itemStateChanged() method.

  • Can be added to a CheckBoxGroup object. When so grouped, exactly one checkbox can be in the "on" state at any given time. If a checkbox is "on" when the user selects another checkbox within the group, it will be set to "off" and the newly selected checkbox will be set to "on". On most platforms, round, radio-style buttons are used to differentiate grouped checkbox objects from ungrouped checkbox objects (that have a square button).

  • Has a number of overloaded constructors. For example,

Checkbox mi = new Checkbox("Michigan resident");

will create a checkbox with the label "Michigan resident" that will be initially "off". If you had wanted the checkbox to be initially "on", you could have coded

Checkbox mi = new Checkbox("Michigan resident", true);

Other constructors allow a checkbox to be added to a group of related checkboxes. For example,

CheckboxGroup residency = new CheckboxGroup();
Checkbox mi = new Checkbox("Michigan resident", residency, false);
Checkbox ny = new Checkbox("New York resident", residency, true);
Checkbox oh = new Checkbox("Ohio resident", residency, false);
Checkbox pa = new Checkbox("Pennsylvania resident", residency, false);

Creates a CheckboxGroup object named residency and four Checkbox objects named mi, ny, oh, and pa that are part of the group. The ny checkbox is initially "on".

  • Has a number of useful methods. Commonly used methods are:

Method

Usage

addItemListener()

Adds the specified ItemListener to receive ItemEvent objects from this checkbox

getCheckboxGroup()

Gets the checkbox group of this checkbox

getLabel()

Gets the label of this checkbox

getState()

Determines if this checkbox is in the "on" or "off" state

removeItemListener()

Removes the specified ItemListener so it no longer receives ItemEvent objects from this checkbox

setCheckboxGroup()

Sets the checkbox group of this checkbox

setLabel()

Sets the label of this checkbox

setState()

Sets the state of this checkbox to either "on" or "off"

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener, ItemListener {

Panel itemPanel;
Checkbox[] itemBoxes;
TextArea priceInfo;
String[] items = {"Apples", "Bananas", "Grapes", "Oranges"};
double[] prices = {1.19, .79, .99, 1.49};

public static void main(String[] args) {
App myWindow = new App("Fruit market");
myWindow.setSize(300, 200);
myWindow.setVisible(true);
}

public App(String title) {
super(title);
addWindowListener(this);
setLayout(new FlowLayout());
setBackground(Color.lightGray);
add(new Label("Fruit selection"));
itemPanel = new Panel();
itemPanel.setLayout(new GridLayout(2,2));
itemBoxes = new Checkbox[items.length];
for (int i=0; i < items.length; i++) {
itemBoxes[i] = new Checkbox(items[i]);
itemBoxes[i].addItemListener(this);
itemPanel.add(itemBoxes[i]);
}
add(itemPanel);
priceInfo = new TextArea("", 4, 30, TextArea.SCROLLBARS_NONE);
priceInfo.setText("Select one or more of the " +
itemBoxes.length + " listed fruits to see the price");
priceInfo.setFont(new Font("SanSerif", Font.PLAIN, 12));
priceInfo.setEditable(false);
add(priceInfo);
}

public void itemStateChanged(ItemEvent e) {
StringBuffer temp = new StringBuffer("");
for (int i = 0; i < itemBoxes.length; i++) {
if (itemBoxes[i].getState() == true) {
temp.append(itemBoxes[i].getLabel() + " are " +
prices[i] + " per pound ");
}
}
if (temp.length() == 0) {
temp.append("No items are selected");
}
priceInfo.setText(temp.toString());
}

public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}

Notes:

  1. In order to become a registered ItemListener, the class implements the ItemListener interface

  2. The application class has instance variables for referencing a panel to display a checkbox for each item (itemPanel), an array to reference the checkbox for each item (itemBoxes), an item price text area (priceInfo), an array of item names (items), and an array of corresponding item prices (prices)

  3. In the class constructor, the itemPanel is constructed and given a GridLayout. The itemBoxes array is then instantiated to hold a reference for each checkbox (one per item). The for loop constructs each item's Checkbox object, registers its ItemListener, and adds it to the itemPanel. The itemPanel is then added to the application frame.

  4. Near the end of the class constructor, the price text area is instantiated and added to the frame It initially displays the number of items available for selection and prompts the user to choose one or more.

  5. The itemStateChanged() method is required by the ItemListener interface. It is automatically called when the user selects or deselects an item's checkbox and receives an ItemEvent object as a parameter. In this sample, only one action will trigger this event so the ItemEvent object isn't tested or used. An empty StringBuffer object (temp) is constructed to which item pricing information may be appended. The for loop tests the state of each item's checkbox and, if "on", appends the item's name and price to temp. If the loop ends with no values being appended, it means no items are currently selected and a message is constructed advising the user to do so. The method ends by setting the string value of temp in the priceInfo text area.

  6. To see how the use of a checkbox group affects this sample, insert the statement

CheckboxGroup itemGroup = new CheckboxGroup();

immediately in front of the for loop within the application's constructor method and the statement

itemBoxes[i].setCheckboxGroup(itemGroup);

inside the for loop immediately after the construction of the Checkbox object.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. Which statements are true of a Choice object? (choose two)

  1. it may fire an ActionEvent

  1. it never allows more than one item to be selected at the same time

  2. it inherits the features of the Component class

  3. it may be grouped with other Choice objects in a ChoiceGroup

  4. its event handling is defined within the itemChanged() method of its registered ItemListener

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following statement?

    List myList = new List(6);

  1. a compile error

  1. a runtime error

  2. a List object that can never contain more than 6 items in its menu

  3. a List object that will permit more than one item to be selected at the same time

  4. none of the above

  1. Which of the following expressions can be used to determine the number of items currently selected within a List object named myList? (choose two)

  1. myList.getItemCount()

  1. myList.getSelectedItemCount()

  2. myList.getSelectedIndexes().length

  3. myList.getSelectedItems().length

  4. myList.getItems().length

  1. Assume that hourly and salaried are Checkbox objects in the same checkbox group and each has properly registered the same ItemListener whose event handler is shown by the following code. Based on this code, what will result from the user clicking the hourly checkbox when the salaried checkbox is currently "on"? Assume that all unseen code is correct and that line numbers are for reference purposes only.

1
2
3
public void itemStateChanged(ItemEvent e) {
salaried.setState(hourly.getState());
}
  1. a compile error will occur at line 2

  2. the salaried checkbox will be "on" and the hourly checkbox will be "off"

  3. the salaried checkbox will be "off" and the hourly checkbox will be "on"

  4. both the salaried and hourly checkboxes will be "on"

  5. both the salaried and hourly checkboxes will be "off"


48405 bytes more | 1 comment | Printer Friendly Page  Send to a Friend | Score: 5
Posted by jalex on Monday, February 28, 2005 (00:00:00) (13876 reads)

The Java Lesson 30: Drawing geometric shapes

Go to all tips in Java Lessons by Jon Huhtala
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 30 by Jon Huhtala: Drawing geometric shapes


Drawing overview

  • Drawing can be performed on any subclass of the Component class. By so doing, a programmer can create customized buttons, labels, scrollbars, etc. For general drawing, the Canvas class is useful. It extends Component to represent a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.

  • The paint() method of the component must be overridden to perform custom drawing. It receives a Graphics object as a parameter (to be discussed shortly). For example, the technique for defining a customized Button is to code something like this

public class CustomButton extends Button {
public void paint(Graphics g) {

custom drawing code goes here...

}
}

To instantiate a customized CustomButton object would only require a single statement such as

CustomButton myButton = new CustomButton();

Through inheritance, myButton would have all the features of a Button object. It would also be automatically rendered when necessary by the JVM through internal calls to its customized paint() method.

Note: An application should never call a component's paint() method directly. It should request painting by calling repaint() instead.

  • To keep device dependencies out of application code, a Java application never works directly with the display screen. Instead, it acts upon a graphics context (a pseudo display). The Java Virtual Machine maps changes to the graphics context to the actual display screen.

Application

<->

context

<->

JVM

<->

display

The paint() method automatically receives an object of the Graphics class as a parameter. This object represents the graphics context of the component and encapsulates methods for drawing within that context.

Every pixel in the component's context has a unique set of x-axis and y-axis coordinates with the origin located in the top-left corner. For example, the context of a component that is 300 pixels wide and 400 pixels high may be visualized as follows:

(0, 0)

x-axis

(299, 0)

y-axis

(0, 399)

(299, 399)


The Graphics class

  • Is part of the java.awt package

  • Is an extension of the Object class

Object

Graphics
  • Permits drawing onto components that are realized on various devices, as well as onto off-screen images. It encapsulates state information needed for the basic rendering operations that Java supports.

  • Has numerous methods that are relatively easy to use and have descriptive names. Commonly used methods are:

Method

Usage

clearRect()

Clears a specified rectangle by filling it with the background color of the component

drawArc()

Draws the outline of a circular or elliptical arc within a specified rectangle

drawLine()

Draws a line between two points

drawOval()

Draws the outline of an oval within a specified rectangle

drawRect()

Draws the outline of a specified rectangle

drawString()

Draws the text of a specified string using the graphics context's current font and color

fillArc()

Draws a filled circular or elliptical arc within a specified rectangle

fillOval()

Draws a filled oval within a specified rectangle

fillRect()

Draws a filled rectangle

getColor()

Gets the graphics context's current color

getFont()

Gets the graphics context's current font

setColor()

Sets the graphics context's current color

setFont()

Sets the graphics context's current font

Many methods require you to specify the x-axis and y-axis coordinates of where an action is to occur. These may be coded as integer literals, variables, or expressions. Consult the help facility of your Java development environment or the Java API for details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener {

public class MyCanvas extends Canvas {
public void paint(Graphics g) {
g.setColor(Color.yellow);
g.fillOval(10,10,50,50);
g.setColor(Color.black);
g.drawOval(10,10,50,50);
g.fillOval(20,28,8,Cool;
g.fillOval(40,28,8,Cool;
g.drawArc(25,35,20,15,190,160);
g.setFont(new Font("SanSerif", Font.BOLD + Font.ITALIC, 16));
g.setColor(Color.blue);
g.drawString("Have a happy day!", 10, 80);
g.setColor(Color.red);
g.drawLine(10,84,150,84);
}
}

MyCanvas picture;

public static void main(String[] args) {
App myWindow = new App("Smiley");
myWindow.setSize(180,130);
myWindow.setVisible(true);
}

public App(String title) {
super(title);
addWindowListener(this);
picture = new MyCanvas();
add(picture);
}

public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}

Notes:

  1. This sample defines an inner class named MyCanvas that extends Canvas and overrides the inherited paint() method. The statements within this method use the graphics context to draw the head, eyes, and mouth of a smiley face, draw a text message, and draw a line under the message.

  2. For drawing shapes, the top-left corner is used for positioning. For drawing text, the bottom-left corner is used for positioning.

  3. The application's constructor instantiates a MyCanvas object and adds it to the application container. Rendering of the object is automatic.

  4. Any valid component could have been extended by the MyCanvas class. For instance, if Button had been extended, the object created by the application constructor would be a button. Try it!

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. Assume that all unseen code is correct and that g references the graphics context of a component that is 200 pixels wide and 200 pixels high. Which of the following statements are true of executing this code? (choose three)

g.drawString("Hello World!",50,50);
g.fillRect(50,50,100,100);
  1. the text will be outside the rectangle

  2. the text will be inside the rectangle

  3. the text will be hidden by the rectangle

  4. the rectangle will be filled with color

  5. the rectangle and text will have the same color

  1. If g references the graphics context of a component that is 100 pixels wide and 50 pixels high, code a single statement to draw a diagonal line in the current color from the bottom-left corner to the top-right corner of the component.

  2. If g references the graphics context of a component that is 100 pixels wide and 100 pixels high, which of the following will draw a solid red arc in the top-left quadrant of a ellipse? (choose two)

  1. g.setColor(Color.red);
    g.fillArc(50,50,100,100,180,-90);

  1. g.setColor(Color.red);
    g.drawArc(50,50,100,100,90,90);

  2. g.setColor(Color.red);
    g.fillArc(50,50,100,100,180,90);

  3. g.setColor(Color.red);
    g.fillArc(50,50,100,100,90,90);

  4. g.setColor(Color.red);
    g.fillArc(50,50,100,100,90,-90);

  1. Assuming that all unseen code is correct, what does the following paint() method draw?

public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(0,0,100,100);
g.setColor(Color.white);
g.drawOval(1,1,98,9Cool;
}

  1. The statements will not compile

  2. a white circle within a solid green square

  3. a white ellipse that is wider than it is tall inside a solid green square

  4. a solid white circle within a solid green square

  5. a solid white ellipse that is wider than it is tall inside a solid green square


14053 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 5
Posted by jalex on Thursday, February 24, 2005 (00:00:00) (11594 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312|
311
| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy