Java’s Advanced User Interface Components

javaLast time, we mastered some basic UI components and worked on how to add them to panels, organize their layout, and manage their events. Having covered all the basic techniques that we’ll need to get started with Java interface programming in our first article, Java’s Basic User Interface Components, we will move on to some advanced UI components. Today, I’ll be covering scrolling lists, scrollbars, and canvases, and their functionality. It is amazing to see how many of complex tasks are simplified with the help of these advanced user interface components.

Last time, we mastered some basic UI components and worked on how to add them to panels, organize their layout, and manage their events. Having covered all the basic techniques that we’ll need to get started with Java interface programming in our first article, Java’s Basic User Interface Components, we will move on to some advanced UI components. Today, I’ll be covering scrolling lists, scrollbars, and canvases, and their functionality. It is amazing to see how many of complex tasks are simplified with the help of these advanced user interface components.

The List Class

The list class allows us to create a scrolling list of values. We can enable single or multiple selections using a list. All that the user has to do is double-click on an item to make a selection. A scrolling list is functionally similar to a choice menu in that it lets us pick several options from a list, but scrolling lists differ in two significant ways:
  • Scrolling lists are not pop-up menus. They’re displayed as a list of items from which you can choose one or more items. If the number of items is larger than the list box, a scrollbar is automatically provided so that you can see the other items.
  • You can choose more than one item in the list (if the list has been defined to allow multiple selection).

In short, scrolling lists provide a menu of items that can be selected or deselected. Unlike choice menus, scrolling lists are not pop-up menus and can be defined to allow multiple selections. To create a scrolling list, an instance of the List class is created and then we add individual items to that list.

To create a scrolling list use, one of the following constructors:
  • List() creates an empty scrolling list that enables only one selection at a time.
  • List(int, boolean) creates a scrolling list with the indicated number of items visible on the list (there is no limit as to the number of actual items you can add to the list). The boolean argument indicates whether this list enables multiple selections (true) or not (false).

After creating a List object, add items to it using the addItem() method and then add the list itself to the panel that contains it. Here’s an example that creates a list five items high that allows multiple selections
{mospagebreak title=More on the List Class} The following example is a simple applet that creates a scrolling list and populates it with items, the list is added to the container in this case Applet using the add() method. In the example below we have a list of seven dairy items with multi-select option set to true.

/* <Applet code “ScrollListTest.class”
Width = 200
Height = 200>
</applet>
*/

Import java.awt.*;

Public class ScrollListTest extends java.applet.Applet
{
 List Dairy = new List (7,true)

 Public void init ()
 {
  Diary.addItem (“Whole Milk”);
  Diary.addItem (“Skimmed Milk”);
  Diary.addItem (“Butter”);
  Diary.addItem (“Cheese”);
  Diary.addItem (“Yogurt”);
  Diary.addItem (“Ice Cream”);
  Diary.addItem (“ Butter Milk ”);
 }
}


Scrolling lists generate actions when the user double-clicks a list item, for example a single mouse click generates a LIST_SELECT or LIST_DESELECT event ID. A scrolling list action has the argument of the string of the item that was double-clicked. The following table shows some of the methods available to scrolling lists. See the API documentation for a complete set.

Method Action
getItem(int)

Returns the string item at the given position (items inside a list begin at 0, just like arrays)

countItems()

Returns the number of items in the menu

getSelectedIndex()

Returns the index position of the item that’s selected

getSelectedIndexes()

Returns an array of index positions (used for lists that allow multiple selections)

getSelectedItem()

Returns the currently selected item as a string

getSelectedItems()

Returns an array of strings containing all the selected items

select(int)

Selects the item at the given position

select(String)

Selects the item with the given string



The following example creates a slightly complex Applet which contains the following UI components: A TextField to accept user input; a Label, to inform the user of the contents that is to be entered in the TextField; a List, which displays a number of items; a “but_add” button, which let’s the user to add text in the TextField to the List. When the applet is started, the UI components specified are added to the applet. The addItem() method is used to add the items to the list. The text entered in the TextField is added to the List on clicking the add button. The ActionListener() method enables the program to listen to the button click events. The items are added to the list inside the actionPerformed() method.

/*
&lgt;applet code = “ListTest1.class” height = 300 width = 200>
&lgt;/applet>
*/

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

Public class ListTest1 extends Applet
{
 List acts = new List();
 TextField tx = new TextField(10);
 Button but_add = new Button(“ADD”);
 String stringlist[] = {“One”, “Two”, “Three”, “Four”};

 Public void start ()
 {
  add(new Label(“Text”));
  add(tx);
  for(int i = 0; i < stringlist.length; ++i)
  acts.addItem(stringlist[i]);
  add(acts);
  but_add.addActionListener(new AddLisn());
  add(but_add);
 }
Class AddLisn implements ActionListener
{
 public void actionPerformed(ActionEvent e)
 {
 acts.addItem(tx.getText());
 }
}

}


{mospagebreak title=Scrollbars and Sliders} Scrollbars are components that enable us to select a value by sliding a box between two arrows. We have already seen that text areas and scrolling lists come with their own scrollbars. These UI components have built-in scrollbars functionality, which enables us to manage both the text area and the list and its scrollbar as a single unit. We can also create individual scrollbars or sliders to manipulate a range of values. The scrollbar class is used for other scrollbars, and a scrollbar can be either horizontal or vertical
Scrollbars are normally created by specifying the maximum and a minimum value using the components. Scrollbars are visual elements, hence choosing any of these visual elements cause a change in the scrollbars value; we don’t have to update anything or handle any events. We just have give the scrollbar a maximum and minimum, and Java will handle the rest. To change the current value of that scrollbar, you can use three different parts of the scrollbar given below.
  • The arrows on either end, which increment or decrement the values by some small unit (1 by default).

  • A range in the middle, which increments or decrements the value by a larger amount (10 by default).

  • A box in the middle, often called a thumb, whose position shows where in the range of values the current value is located. Moving this box with the mouse causes an absolute change in the value, based on the position of the box within the scrollbar.

To create a scrollbar, you can use one of three constructors:
  • Scrollbar () creates a scrollbar with its initial maximum and minimum values both 0, in a vertical orientation.

  • Scrollbar (int) creates a scrollbar with its initial maximum and minimum values both 0. The argument represents an orientation, for which you can use the class variables Scrollbar.HORIZONTAL and Scrollbar.VERTICAL.

  • Scrollbar( int, int, int, int, int) creates a scrollbar with the following arguments (each one is an integer, and they must be presented in this order):

    • The first argument is the orientation of the scrollbar either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.


    • The second argument is the initial value of the scrollbar, which should be a value between maximum and minimum values of a scrollbar.


    • The third argument is the overall width or height, depending on the orientation of the scrollbars box (applies best to things such as windows and text areas).

    • The fourth and fifth arguments are the minimum and maximum values for the scrollbar respectively.

{mospagebreak title=More on Scrollbars and Sliders} The following example shows an elegant yet easy applet that displays a scrollbar. The GridLayout object is used with setLayout() method of the applet to provide a layout in which a scrollbar occupies its entire container. Please note no matter what values are supplied for the applet’s height and width, the scrollbar will fill the entire area.

/*
<Applet code “SliderTest.class”
Width = 200
Height = 200>
</applet>
*/

Import java.awt.*;

Public class SliderTest extends java.applet.Applet
{
 Scrollbar sbar = new Scrollbar (Scrollbar.HORIZONTAL, 50,0,1,100);
 GridLayout g = new GridLayout(1,1)

 Public void init ()
 {
   setLayout(g);
   add (sbar);
 }
}


The scrollbar class provides several methods for managing the values within the scrollbar they are as follows:

Method Action
getMaximum() Returns the maximum value.
getMinimum() Returns the minimum value.
getOrientation() Returns the orientation of a scrollbar
getValue() Returns the scrollbar’s current value.
setValue(int) Sets the current value of the scrollbar
setLineIncrement(int inc) Change the increment for how far to scroll when the endpoints of the scrollbar are selected. The default is 1.
getLineIncrement() Returns the increment for how far to scroll when the endpoints of the scrollbar are selected.
getPageIncrement() Returns the increment for how far to scroll when the inside range of the scrollbar is selected.
setPageIncrement(int inc) Change the increment for how far to scroll when the inside range of the scrollbar is selected.


The Following example is about a simple scrollbar that increments a single value. The label to the left of the scrollbar is updated each time the scrollbar’s value changes. The arguments to the Insets constructor provide pixel insets for the top, bottom, left, and right edges of the component, respectively. This particular example provides an inset of 15 pixels on all four sides. The Scrollbar increment events are handled using special handleEvent() method. That object is stored in the event’s target instance variable, and we can use the instanceof operator to find out what kind of UI component sent it. We use getValue() method to return the scrollbar’s current value.

/*
<Applet code “ScrollTest.class”

 Width = 200 Height = 200>
</applet>
*/

Import java.awt.*;

Public class ScrollTest extends java.applet.Applet {
 Label lab;

 Public void init() {
   setLayout(new GridLayout(1,2));
   lab = new Label(“0″, Label.CENTER);
    add(lab);
   add(new Scrollbar(Scrollbar.VERTICAL,0,0,1,100));
 }

 Public Insets insets() {
   return new Insets(15,15,15,15);
 }

 Public boolean handleEvent(Event evnt) {
   if (evnt.target instanceof Scrollbar)
   {
     int i = ((Scrollbar)evnt.target).getValue();
     lab.setText(String.valueOf(i));
     repaint();
     return true;
   }
  else return false;
 }

}
{mospagebreak title=Canvases} Canvases are components that are primarily used as a place on an interface to display images and animation. Although you can draw on most AWT components, such as panels using the graphics methods we’ve learned about earlier, canvases do very little except let us to draw on them. Hence a Canvas is a component that we can draw on. In order to use a canvas, we must create a subclass of the Canvas class. This subclass can handle any drawing that needs to take place on the canvas using the paint () method. Once the Canvas class has been created it can be called in the program by calling its constructor and adding the new Canvas object to the container. If we have a panel that doesn’t need to do much except display images or animation, a canvas would be a preference as it makes a lighter-weight surface than a panel would.

To create a canvas, use the Canvas class and add it to a panel as you would any other component:

Canvas can = new Canvas(); add(can);

The following example is an applet which helps to demonstrate a drawing on a canvas.

/*
<Applet code “CanvasTest.class”
Width = 20 Height = 200>
</applet>
*/

Import java.awt.*;

Public class CanvasTest extends java.applet.Applet
{

 GridLayout gl = new GridLayout(1,1);
 MyCanvas can = new MyCanvas();

 Public void init()
 {
   setLayout(gl);
   add(can);
 }
 Class MyCanvas extends java.awt.Canvas
 {
    public void paint(Graphic g)
   {
     g.setColor(Color.blue);
     g.drawString(“Congratilations! We are seen a string drawn on a canvas”, 20, 20);
   }
 }
}


Now we know how to paint a user interface onto a Java applet’s window and Java applications using the languages standard palette-the components of the Abstract Windowing toolkit. We will see a few more advanced UI components, like menus, popup menus, and dialogs, before we move into learning how to arrange these components together to form a whole interface.
[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort