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...
 

Swing Chapter 5. (The basics) Labels and Buttons. Easy for reading, Click here!

Custom Search
Swing Chapter 5. (The basics) Labels and Buttons. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 2/4 



Previous Page Previous Page (1/4) - Next Page (3/4) Next Page
Subpages: 1. Labels and buttons overview
2. Custom buttons: part I - Transparent buttons
3. Custom buttons: part II - Polygonal buttons
4. Custom buttons: part III - Tooltip management

5.2    Custom buttons: part I - Transparent buttons

Buttons in Swing can adopt almost any presentation we can think of. Of course some presentations are tougher to implement than others. In the remainder of this chapter we will deal directly with these issues. The example in this section shows how to construct invisible buttons which only appear when the user moves the mouse cursor over them. Specifically, a border will be painted, and tooltip text will be activated in the default mannar.

Such button's can be useful in applets for pre-defined hyperlink navigation, and we will design our invisible button class with this in mind. Thus, we will show how to create an applet that reads a set of parameters from the HTML page it is embedded in, and loads a corresponding set of invisible buttons. For each button, the designer of the HTML page must provide three parameters: the desired hyperlink URL, the button's bounds (positions and size), and the button's tooltip text. Additionaly our sample applet will require a background image parameter. Our button's bounds are intended to directly correspond to an 'active' region of this background image--much like the venerable HTML image mapping functionality.

Figure 5.8 Transparent rectangular buttons in an applet

<<file figure5-8.gif>>

The Code: ButtonApplet.java

see \Chapter5\4

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.util.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.event.*;

public class ButtonApplet extends JApplet

{

  public ButtonApplet() {}

  public synchronized void init() {

    String imageName = getParameter("image");

    if (imageName == null) {

      System.err.println("Need \"image\" parameter");

      return;

    }

    URL imageUrl = null;

    try {

      imageUrl = new URL(getDocumentBase(), imageName);

    }

    catch (MalformedURLException ex) {

      ex.printStackTrace();

      return;

    }

    ImageIcon bigImage = new ImageIcon(imageUrl);

    JLabel bigLabel = new JLabel(bigImage);

    bigLabel.setLayout(null);

    int index = 1;

    int[] q = new int[4];

    while(true) {

      String paramSize = getParameter("button"+index);

      String paramName = getParameter("name"+index);

      String paramUrl = getParameter("url"+index);

      if (paramSize==null || paramName==null || paramUrl==null)

        break;

      try {

        StringTokenizer tokenizer = new StringTokenizer(

          paramSize, ",");

        for (int k=0; k<4; k++) {

          String str = tokenizer.nextToken().trim();

          q[k] = Integer.parseInt(str);

        }

      }

      catch (Exception ex) { break; }

      NavigateButton btn = new NavigateButton(this,

        paramName, paramUrl);

      bigLabel.add(btn);

      btn.setBounds(q[0], q[1], q[2], q[3]);

      index++;

    }

    getContentPane().setLayout(null);

    getContentPane().add(bigLabel);

    bigLabel.setBounds(0, 0, bigImage.getIconWidth(),

      bigImage.getIconHeight());

  }

  public String getAppletInfo() {

    return "Sample applet with NavigateButtons";

  }

  public String[][] getParameterInfo() {

    String pinfo[][] = {

      {"image",  "string",  "base image file name"},

      {"buttonX","x,y,w,h", "button's bounds"},

      {"nameX",  "string",  "tooltip text"},

      {"urlX",   "url",     "link URL"} };

    return pinfo;

  }

}

class NavigateButton extends JButton implements ActionListener

{

  protected Border m_activeBorder;

  protected Border m_inactiveBorder;

  protected Applet m_parent;

  protected String m_text;

  protected String m_sUrl;

  protected URL    m_url;

  public NavigateButton(Applet parent, String text, String sUrl) {

    m_parent = parent;

    setText(text);

    m_sUrl = sUrl;

    try {

      m_url = new URL(sUrl);

    }

    catch(Exception ex) { m_url = null; }

    setOpaque(false);

    enableEvents(AWTEvent.MOUSE_EVENT_MASK);

    m_activeBorder = new MatteBorder(1, 1, 1, 1, Color.yellow);

    m_inactiveBorder = new EmptyBorder(1, 1, 1, 1);

    setBorder(m_inactiveBorder);

    addActionListener(this);

  }

  public void setText(String text) {

    m_text = text;

    setToolTipText(text);

  }

  public String getText() {

    return m_text;

  }

  protected void processMouseEvent(MouseEvent evt) {

    switch (evt.getID()) {

      case MouseEvent.MOUSE_ENTERED:

        setBorder(m_activeBorder);

        setCursor(Cursor.getPredefinedCursor(

          Cursor.HAND_CURSOR));

        m_parent.showStatus(m_sUrl);

        break;

      case MouseEvent.MOUSE_EXITED:

        setBorder(m_inactiveBorder);

        setCursor(Cursor.getPredefinedCursor(

          Cursor.DEFAULT_CURSOR));

        m_parent.showStatus("");

        break;

    }

    super.processMouseEvent(evt);

  }

  public void actionPerformed(ActionEvent e) {

    if (m_url != null) {

      AppletContext context = m_parent.getAppletContext();

      if (context != null)

        context.showDocument(m_url);

    }

  }

  public void paintComponent(Graphics g) {

    paintBorder(g);

  }

}

Understanding the Code

Class ButtonApplet

This class extends JApplet to provide web page functionality. The init() method creates and initializes all GUI components. It starts by reading the applet's "image" parameter which is then used along with the applet's codebase to construct a URL:

      imageUrl = new URL(getDocumentBase(), imageName);

This URL points to the image file which is used to create our bigLabel label which is used as the applet's background image.

The applet can be configured to hold several invisible buttons for navigating to pre-defined URLs. For each button, three applet parameters must be provided:

buttonN: holds four comma-delimited numbers for x, y, width, and height of button N.

nameN: tooltip text for button N.

urlN: URL to re-direct the browser when the user clicks mouse over button N.

As soon as these parameters can be read and parsed for a given N, a new button is created and added to bigLabel:

      NavigateButton btn = new NavigateButton(this,

        paramName, paramUrl);

      bigLabel.add(btn);

      btn.setBounds(q[0], q[1], q[2], q[3]);

Finally the bigLabel component is added to the applet's content pane. It receives a fixed size to avoid any repositioning if the applet's pane is somehow resized.

The getAppletInfo() method returns a String description of this applet. The getParameterInfo() method returns a 2-dimensional String array describing the parameters accepted by this applet. Both are strongly recommended constituents of any applet, but are not required for raw functionality.

Class NavigateButton

This class extends JButton to provide our custom implementation of an invisible button. It implements the ActionListener interface, eliminating the need to add an external listener, and shows how we can enable mouse events without implementing the MouseListener interface.

Several parameters are declared in this class:

Border m_activeBorder: the border which will be used when the button is active (when the mouse cursor is moved over the button).

Border m_inactiveBorder: the border which will be used when the button is inactive (when no mouse cursor is over the button). Usually this will not be visible.

Applet m_parent: a reference to the parent applet.

String m_text: tooltip text for this button.

String m_sUrl: string representation of the URL (for display in the browser's status bar).

URL m_url: the actual URL to redirect the browser to when a mouse click occurs.

The constructor of the NavigateButton class takes three parameters: a reference to the parent applet, tooltip text, and a String representation of a URL. It assigns all instance variables and creates a URL from the given String. Note that if the URL address cannot be resolved, it is set to null (this will disable navigation). The Opaque property is set to false because this component is supposed to be transparent. Note also that this component  processes its own MouseEvents, enabled with the enableEvents() method. This button will also receive ActionEvents by virtue of implementing ActionListener and adding itself as a listener.

The setText() and getText() methods manage the m_text (tooltip text) property. They also serve to override the corresponding methods inherited from the JButton class.

The processMouseEvent() method will be called for notification about mouse events on this component. We want to process only two kinds of events: MOUSE_ENTERED and MOUSE_EXITED. When the mouse enters the button's bounds, we set the border to m_activeBorder, change the mouse cursor to the hand cursor, display the String description of the URL in the browser's status bar. When the mouse exits the button's bounds we perform the opposite actions: set the border to m_inactiveBorder, set the mouse cursor to the default cursor, and clear the browser's status bar.

The actionPerformed() method will be called when the user presses this button (note that we use the inherited JButton processing for both mouse clicks and the keyboard mnemonic). If both the URL and AppletContext instances are not null, the showDocument() method is called to redirect the browser to the button's URL.

Note: Do not confuse AppletContext with the AppContext class we discussed in section 2.5. AppletContext is an interface for describing an applet's environment, including information about the document it is contained in, as well as information about other appets that might also be contained in that document.

The paintComponent() method used for this button has a very simple implementation. We just draw the button's border by calling the paintBorder(). Because this component does not have a UI delegate we do not need to call super.paintComponent() from this method.

Running the Code

To run it in the web browser we have constructed the following HTML file:

<html>

<head>

<title></title>

</head>

<body>

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"

WIDTH = 563 HEIGHT = 275  codebase="http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab#Version=1,2,0,0">

<PARAM NAME = "CODE" VALUE = "ButtonApplet.class" >

<PARAM NAME = "type" VALUE ="application/x-java-applet;version=1.2">

  <param name="button1" value="49, 134, 161, 22">

  <param name="button2" value="49, 156, 161, 22">

  <param name="button3" value="16, 178, 194, 22">

  <param name="button4" value="85, 200, 125, 22">

  <param name="button5" value="85, 222, 125, 22">

  <param name="image" value="nasa.gif">

  <param name="name1" value="What is Earth Science?">

  <param name="name2" value="Earth Science Missions">

  <param name="name3" value="Science of the Earth System">

  <param name="name4" value="Image Galery">

  <param name="name5" value="For Kids Only">

  <param name="url1"

   value="http://www.earth.nasa.gov/whatis/index.html">

  <param name="url2"

   value="http://www.earth.nasa.gov/missions/index.html">

  <param name="url3"

   value="http://www.earth.nasa.gov/science/index.html">

  <param name="url4"

   value="http://www.earth.nasa.gov/gallery/index.html">

  <param name="url5"

   value="http://kids.mtpe.hq.nasa.gov/">

<COMMENT>

<EMBED type="application/x-java-applet;version=1.2" CODE = "ButtonApplet.class"

  WIDTH = "563" HEIGHT = "275"

  codebase="./"

  button1="49, 134, 161, 22"

  button2="49, 156, 161, 22"

  button3="16, 178, 194, 22"

  button4="85, 200, 125, 22"

  button5="85, 222, 125, 22"

  image="nasa.gif"

  name1="What is Earth Science?"

  name2="Earth Science Missions"

  name3="Science of the Earth System"

  name4="Image Galery"

  name5="For Kids Only"

  url1="http://www.earth.nasa.gov/whatis/index.html"

  url2="http://www.earth.nasa.gov/missions/index.html"

  url3="http://www.earth.nasa.gov/science/index.html"

  url4="http://www.earth.nasa.gov/gallery/index.html"

  url5="http://kids.mtpe.hq.nasa.gov/"

  pluginspage=

    "http://java.sun.com/products/plugin/1.2/plugin-install.html">

<NOEMBED>

</COMMENT>

alt="Your browser understands the &lt;APPLET&gt; tag but isn't

running the applet, for some reason."

Your browser is completely ignoring the &lt;APPLET&gt; tag!

</NOEMBED>

</EMBED>

</OBJECT>

</p>

<p>&nbsp;</p>

</body>

</html>

Note: The HTML file above works with appletviewer, Netscape Navigator 4.0 and Microsoft Internet Explorer 4.0. This compatibility is achieved due to Java Plug-in technology. See http://www.javasoft.com/products/plugin/1.2/docs/tags.html for more details on how to write Plug-in compatible HTML files. The downside is that we need to include all applet parameters two times for each web browser.

Reference: For additional information about the Java Plug-in and Plug-in HTML converter (a convenient utility to generate Plug-in compliant HTML), see Swing Connection's "Swinging on the Web" article at: http://java.sun.com/products/jfc/tsc/java_plug-in/java_plug-in.html.

Figure 5.8 shows ButtonApplet running in Netscape Navigator 4.05 using the Java Plug-in. Note how invisible buttons react when the mouse cursor moves over them. Click a button and navigate to one of the NASA sites.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


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