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

Tricky Java example: Display Icons without icons.

JavaFAQ Home » Java Code Examples Go to all tips in Java Code Examples


Bookmark and Share

Jazzmsg is a package with a dialog and a label box class, displays messages with text based icons. Icons are built in and different messages are shown every 2 seconds: INFORMATION, CONFIRM, HELP, WARNING, EXCEPTION, ERROR, NONE (no category, nothing to display!).

Since displayed icons are not real images, it is pretty easy to add your own icon. They are painted using text. That's why the package is so light and fast. If look into the code you will easily find a posibility to add more icons.

How to run it:

Compile java files, put four class files into "jazzmsz" directory and run this command:
"java -classpath . jazzmsz/jazztest"


jazzdlg.java
Code:

/*
 * @(#)jazzdlg.java   1.00 20th January 2000
 *
 * Modification Log:
 *
 */

package jazzmsz;

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


/**
 * A dialog box control with in-build icons.
 * Displays a dialog box with different icons and colors depending
 * on the message type. Has customizable buttons.
 *
 * You are free to use this code and to make modifications provided
 * this notice is retained.
 * <p>
 * If you found this useful, please add a note of acknowledgement to my guestbook,
 * or send me a mail at <a href="mailto:tanmaykm@hotmail.com">tanmaykm@hotmail.com</a>.
 * If you would like to report a bug or suggest some improvements,
 * you are most welcome. I will be happy to help you use this piece of code.
 * <p>
 *
 * @author        Tanmay K. Mohapatra
 * @version     1.00, 20th January, 2000
 */


public class jazzdlg extends Dialog implements ActionListener
{
    private GridBagLayout       gridbag             = null;
    private GridBagConstraints  gbConstr            = null;
    private Panel               ButtonPanel         = null;
    private jazzicon            icon                = null;
    private TextArea            txtMsg              = null;

    String                      sResp               = "";
    boolean                     bSelfDestroy        = true;
    boolean                     bFocusSet           = false;
    Component                   cFocusOn            = null;
    Frame                       ParentFrame         = null;
    static boolean              bForceSetFocus;

    public static final int     NONE = jazzicon.NONE;
    public static final int     INFORMATION = jazzicon.INFORMATION;
    public static final int     CONFIRM = jazzicon.CONFIRM;
    public static final int     HELP = jazzicon.HELP;
    public static final int     WARNING = jazzicon.WARNING;
    public static final int     EXCEPTION = jazzicon.EXCEPTION;
    public static final int     ERROR = jazzicon.ERROR;
   
    private static Color        bgCol, fgCol;
    private static Font         fnt;
   
    /**
     * Constructor
     *
     * @param   parent    parent frame, from where it is being called.
     * @param   sTitle    Title of the dialog box. Default title <b>Message</b> is used if it is null.
     * @param   bModal    whether it is modal.
     */
    public jazzdlg(Frame parent, String sTitle, boolean bModal)
    {
        super(parent, (null==sTitle) ? "Message" : sTitle, bModal);
        ParentFrame=parent;
        setJazzLayout();
    }

    /**
     * Constructor
     *
     * @param   parent    parent frame, from where it is being called.
     * @param   bModal    whether it is modal.
     */
    public jazzdlg(Frame parent, boolean bModal)
    {
        super(parent, bModal);
        ParentFrame=parent;
        setJazzLayout();
    }


    public static void setDlgGui(Color bgColIn, Color fgColIn, Font fntIn)
    {
        jazzdlg.bgCol = bgColIn;
        jazzdlg.fgCol = fgColIn;
        jazzdlg.fnt = fntIn;
    }
   
    /**
     * Shows a message box with the specified properties.
     * Returns the name of the button pressed if it is modal.
     *
     * @param   sTitle       title of the dialog box.
     * @param   sMsg         message to be displayed.
     * @param   sButtons     array of names of buttons to be shown.
     * @param   iType        type of dialog: NONE, INFORMATION, WARNING, EXCEPTION, ERROR,...
     * @param   bWait        true if dialog is to be modal.
     * @param   calledFrom   container from where this is being called (used to center the dialog).
     *
     * @return     the name of the button pressed if the dialog is modal, empty string otherwise.
     */
    public static String showMsgBox (String sTitle, String sMsg, String [] sButtons, int iType, boolean bWait, Container calledFrom)
    {
        String      sResp = "";
        jazzdlg     msgbox;
        Frame       parentFrame;

        parentFrame = findFrame(calledFrom);
        msgbox = new jazzdlg(parentFrame, sTitle, bWait);
        msgbox.txtMsg.setText(sMsg);
        msgbox.icon.setIconCharacterType(iType);

        try
        {
            for (int iIndex=0; ; iIndex++)
            {
                Button b = new Button(sButtons[iIndex]);
                b.addActionListener(msgbox);
                msgbox.ButtonPanel.add(b);
                if(null == msgbox.cFocusOn) msgbox.cFocusOn = b;
            }
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            // array out of bounds exception. ignore
        }

        msgbox.bSelfDestroy = !bWait;

        if (bWait)
        {
            calledFrom.setEnabled(false);   // parent should not get any events
        }

        msgbox.setVisible(true);
        if (bWait)
        {
            while (msgbox.sResp.equals(""))
            {
                try
                {
                    Thread.yield();
                    Thread.sleep(500);
                }
                catch(InterruptedException ie)
                {
                    // ie
                }
            }
            sResp = msgbox.sResp;
        }

        if (bWait)
        {
            calledFrom.setEnabled(true);
        }

        msgbox = null;
        return sResp;
    }
   
    /**
     * Sets the layout for the message dialog frame. Uses grid bag layout.
     */
    private void setJazzLayout()
    {
        icon        = new jazzicon();
        txtMsg      = new TextArea("", 5, 30, TextArea.SCROLLBARS_NONE);
        ButtonPanel = new Panel();
        gridbag     = new GridBagLayout();
        gbConstr    = new GridBagConstraints();
       
        txtMsg.setEditable(false);
        txtMsg.setEnabled(false);
        icon.setFont(new Font("Courier", Font.BOLD, 30));
       
        if(null != jazzdlg.bgCol) setBackground(jazzdlg.bgCol);
        if(null != jazzdlg.fgCol) setForeground(jazzdlg.fgCol);
        if(null != jazzdlg.fnt)   setFont(jazzdlg.fnt);
        setLayout(gridbag);
       
        gbConstr.ipadx = 0;
        gbConstr.ipady = 0;
        gbConstr.fill = GridBagConstraints.BOTH;
        gbConstr.anchor = GridBagConstraints.NORTHWEST;
        gbConstr.gridheight = GridBagConstraints.REMAINDER;
        gbConstr.gridwidth = GridBagConstraints.RELATIVE;
        gbConstr.weightx = 0;
        gbConstr.weighty = 0;
        gbConstr.gridx = 0;
        gbConstr.gridy = 0;
        gridbag.setConstraints(icon, gbConstr);
        add(icon);
       
        gbConstr.fill = GridBagConstraints.BOTH;
        gbConstr.gridheight = GridBagConstraints.RELATIVE;
        gbConstr.gridwidth = GridBagConstraints.REMAINDER;
        gbConstr.weightx = 1;
        gbConstr.weighty = 1;
        gbConstr.gridx = GridBagConstraints.RELATIVE;
        gbConstr.gridy = 0;
        gridbag.setConstraints(txtMsg, gbConstr);
        add(txtMsg);
       
        gbConstr.fill = GridBagConstraints.NONE;
        gbConstr.anchor = GridBagConstraints.CENTER;
        gbConstr.gridwidth = GridBagConstraints.REMAINDER;
        gbConstr.weightx = 1;
        gbConstr.weighty = 0;
        gbConstr.gridx = GridBagConstraints.RELATIVE;
        gbConstr.gridy = GridBagConstraints.RELATIVE;
        gridbag.setConstraints(ButtonPanel, gbConstr);
        ButtonPanel.setLayout(new GridLayout(1, 0, 5, 25));
        add(ButtonPanel);
    }

    /**
     * Lays out the screen, moves the screen to the center of the parent window,
     * before making the dialog visible.
     */
    public void setVisible(boolean bShow)
    {
        if (true == bShow)
        {
            pack();

            Dimension d = getSize();
            d.width += 100;
            setSize(d);

            try
            {
                if (null != ParentFrame)
                {
                    Rectangle bounds = ParentFrame.getBounds();
                    Rectangle abounds = getBounds();

                    setLocation(bounds.x + (bounds.width - abounds.width) / 2,
                         bounds.y + (bounds.height - abounds.height) / 2);
                }
            }
            catch (Exception e)
            {
                // nothing
            }

            if (bForceSetFocus && (null != cFocusOn))
            {
                cFocusOn.requestFocus();
            }

            super.setVisible(true);
        }
        else
        {
            super.setVisible(false);
        }
    }

    /**
     * Hides the dialog if any button is pressed.
     */
    public void actionPerformed(ActionEvent event)
    {
        sResp = event.getActionCommand();
        setVisible(false);
        dispose();
    }
   
    /**
     * Finds the parent frame of the specified component.
     *
     * @param   calledFrom  container whoose parent to find. <br>
     *                      In this context, the container from where
     *                      showMsgBox was called.
     * @return              the parent frame if found, null otherwise.
     */
    private static Frame findFrame(Container calledFrom)
    {
        if (null != calledFrom)
        {
            Container frameContainer;

            frameContainer = calledFrom;
            do
            {
                if (frameContainer instanceof Frame)
                {
                    return (Frame)frameContainer;
                }
            } while (null != (frameContainer = frameContainer.getParent()));
        }
        return null;
    }
}



jazzicon.java
Code:

/*
 * @(#)jazzicon.java   1.00 20th January 2000
 *
 * Modification Log:
 *
 */

package jazzmsz;

import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * A icon control with in-build icons.
 * Displays different icons depending on the message type.
 * Has customizable buttons.
 *
 * You are free to use this code and to make modifications provided
 * this notice is retained.
 * <p>
 * If you found this useful, please add a note of acknowledgement to my guestbook,
 * or send me a mail at <a href="mailto:tanmaykm@hotmail.com">tanmaykm@hotmail.com</a>.
 * If you would like to report a bug or suggest some improvements,
 * you are most welcome. I will be happy to help you use this piece of code.
 * <p>
 *
 * @author        Tanmay K. Mohapatra
 * @version     1.00, 20th January, 2000
 */

public class jazzicon extends Canvas
{
    private Image       image;
    private Character   charIcon;
    private String      sIcon;

    public static final int     NONE = 0;
    public static final int     INFORMATION = 1;
    public static final int     CONFIRM = 2;
    public static final int     HELP = 3;
    public static final int     WARNING = 4;
    public static final int     EXCEPTION = 5;
    public static final int     ERROR = 6;
   
    public boolean setIconImage(String sResource)
    {
        if (null != (image = getImageFromResource(sResource)))
        {
            sIcon = null;
            charIcon = null;
            return true;
        }
        return false;
    }
   
    public void setIconCharacter(Character charIn)
    {
        if(null != (charIcon = charIn))
        {
            sIcon = charIcon.toString();
            image = null;
        }
    }
   
    public void setIconCharacterType(int iType)
    {
        switch(iType)
        {
            case INFORMATION:
                setIconCharacter(new Character('i'));
                setForeground(Color.blue);
                setBackground(Color.white);
                break;
            case HELP:
                setIconCharacter(new Character('h'));
                setForeground(Color.blue);
                setBackground(Color.white);
                break;
            case CONFIRM:
                setIconCharacter(new Character('?'));
                setForeground(Color.blue);
                setBackground(Color.white);
                break;
            case WARNING:
                setIconCharacter(new Character('!'));
                setForeground(Color.black);
                setBackground(Color.yellow);
                break;
            case EXCEPTION:
                setIconCharacter(new Character('e'));
                setForeground(Color.black);
                setBackground(Color.orange);
                break;
            case ERROR:
                setIconCharacter(new Character('E'));
                setForeground(Color.white);
                setBackground(Color.red);
                break;
            default:
                setIconCharacter(new Character(' '));
                Component c = getParent();
                if(null != c)
                {
                    setForeground(c.getForeground());
                    setBackground(c.getBackground());
                }
                break;
        }
        repaint();
    }
   
    /**
     * Paints the image on the canvas. Draws a border around it if has focus.
     */
    public void paint(Graphics g)
    {
        Dimension dim = getSize();

        if (null != image)
        {
            g.drawImage (image, 1, 1, dim.width-2, dim.height-2, this);
        }
        else
        {
            g.setColor(getBackground());
            g.fill3DRect(-1, -1, dim.width+2, dim.height+2, true);
            if(null != sIcon)
            {
                FontMetrics fm;
                g.setColor(getForeground());
                int iX, iY;
                iX = dim.width/2;
                iY = dim.height/2;
                fm = g.getFontMetrics();
                iX -= fm.stringWidth(sIcon)/2;
                iY += fm.getDescent();
                g.drawString(sIcon, iX, iY);
                if(!Character.isWhitespace(sIcon.charAt(0))) g.drawRect(0, 0, dim.width, dim.height);
            }
        }
    }

    /**
     * The preferred size of the image.
     */
    public Dimension getPreferredSize()
    {
        if (null == image)
        {
            Font f = getFont();
            if (null == f) f = Font.decode("Courier-bold-30");
            FontMetrics fm = getFontMetrics(f);
            int i = Math.max(fm.getHeight()+4, fm.stringWidth((null == sIcon) ? "X" : sIcon)+4);
            return new Dimension(i, i);
        }
        else
        {
            return new Dimension(image.getWidth(this), image.getHeight(this));
        }
    }

    /**
     * The minimum size of the image.
     */ 
    public Dimension getMinimumSize()
    {
        if (null == image)
        {
            Font f = getFont();
            if (null == f) f = Font.decode("Courier-bold-30");
            FontMetrics fm = getFontMetrics(f);
            int i = Math.max(fm.getHeight()+4, fm.stringWidth((null == sIcon) ? "X" : sIcon)+4);
            return new Dimension(i, i);
        }
        else
        {
            return new Dimension(image.getWidth(this), image.getHeight(this));
        }
    }
   
    /**
     * Obtains the image specified from the resources.
     */
    private Image getImageFromResource(String sResource)
    {
        InputStream  is = getClass().getResourceAsStream(sResource);
        Image        img = null;
        MediaTracker tracker = new MediaTracker(this);

        if (null != is)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int iRead;

            try
            {
                while(-1 != (iRead = is.read()))
                {
                    baos.write(iRead);
                }
                img = Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
                tracker.addImage(img, 1);
                try
                {
                    tracker.waitForAll();
                }
                catch(InterruptedException ie)
                {
                    // System.out.println("MediaTracker interrupted");
                }
            }
            catch (IOException ioe)
            {
                img = null;
            }
        }

        return img;
    }
}


jazzlabel.java
Code:

/*
 * @(#)jazzlabel.java   1.00 20th January 2000
 *
 * Modification Log:
 *
 */

package jazzmsz;

import java.awt.*;

/**
 * A label control with in-build icons.
 * Displays different icons depending on the message type.
 *
 * You are free to use this code and to make modifications provided
 * this notice is retained.
 * <p>
 * If you found this useful, please add a note of acknowledgement to my guestbook,
 * or send me a mail at <a href="mailto:tanmaykm@hotmail.com">tanmaykm@hotmail.com</a>.
 * If you would like to report a bug or suggest some improvements,
 * you are most welcome. I will be happy to help you use this piece of code.
 * <p>
 *
 * @author        Tanmay K. Mohapatra
 * @version     1.00, 20th January, 2000
 */

public class jazzlabel extends Panel
{
    Label               lblMsg;
    jazzicon            icon;
    GridBagLayout       gbLayout;
    GridBagConstraints  gbConstr;
   
    public static final int     NONE = jazzicon.NONE;
    public static final int     INFORMATION = jazzicon.INFORMATION;
    public static final int     CONFIRM = jazzicon.CONFIRM;
    public static final int     HELP = jazzicon.HELP;
    public static final int     WARNING = jazzicon.WARNING;
    public static final int     EXCEPTION = jazzicon.EXCEPTION;
    public static final int     ERROR = jazzicon.ERROR;

    public jazzlabel()
    {
        icon = new jazzicon();
        lblMsg = new Label();
        gbLayout = new GridBagLayout();
        gbConstr = new GridBagConstraints();
       
        setLayout(gbLayout);
       
        gbConstr.gridheight = GridBagConstraints.REMAINDER;
        gbConstr.gridwidth = GridBagConstraints.RELATIVE;
        gbConstr.weightx = 0;
        gbConstr.weighty = 1;
        gbConstr.gridx = 0;
        gbConstr.gridy = 0;
        gbConstr.fill = GridBagConstraints.BOTH;
        gbConstr.anchor = GridBagConstraints.WEST;
       
        gbLayout.setConstraints(icon, gbConstr);
        add(icon);
       
        gbConstr.gridwidth = GridBagConstraints.REMAINDER;
        gbConstr.weightx = 1;
        gbConstr.gridx = GridBagConstraints.RELATIVE;
        gbConstr.gridy = GridBagConstraints.RELATIVE;
       
        gbLayout.setConstraints(lblMsg, gbConstr);
        add(lblMsg);
    }
   
    public void setMessage(String sMessage, int iType)
    {
        lblMsg.setText(sMessage);
        icon.setIconCharacterType(iType);
        Font fnt = getFont();
        if (null == fnt) fnt = new Font("Courier", Font.BOLD, 16);
        icon.setFont(new Font("Courier", Font.BOLD, fnt.getSize()+2));
        doLayout();
        icon.repaint();
    }
}


jazztest.java
Code:

/*
 * @(#)jazztest.java   1.00 20th January 2000
 *
 * Modification Log:
 *
 */

package jazzmsz;

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

/**
 * Test routine for testing and demonstrating jazzmsg classes.
 *
 * You are free to use this code and to make modifications provided
 * this notice is retained.
 * <p>
 * If you found this useful, please add a note of acknowledgement to my guestbook,
 * or send me a mail at <a href="mailto:tanmaykm@hotmail.com">tanmaykm@hotmail.com</a>.
 * If you would like to report a bug or suggest some improvements,
 * you are most welcome. I will be happy to help you use this piece of code.
 * <p>
 *
 * @author        Tanmay K. Mohapatra
 * @version     1.00, 20th January, 2000
 */

public class jazztest
{
   public static void main(String[] args)
   {
        boolean bPacked = false;
        Frame f = new Frame();
        jazzlabel jl = new jazzlabel();
        jl.setBackground(Color.decode("0xccffcc"));
        jl.setForeground(Color.decode("0x000000"));
        jl.setFont(Font.decode("Dialog-bold-12"));
        jazzdlg.setDlgGui(Color.decode("0xccffcc"), Color.decode("0x000000"), Font.decode("Dialog-bold-12"));
           
        f.add(jl);
        f.setVisible(true);
        f.pack();
        f.setLocation(100, 100);

        String [] btns = new String[2];
        btns[0] = "Ok";
        btns[1] = "Cancel";
       
        try
        {
            while(true)
            {
                jl.setMessage("Hello! You will get new messages every 2 seconds from now...", jl.NONE);
                if(!bPacked)
                {
                    f.pack();
                    bPacked = true;
                }
               
                jazzdlg.showMsgBox("",
                                   "Hello! You will get new messages every 2 seconds from now...",
                                   btns,
                                   jazzdlg.NONE,
                                   true,
                                   f);
                Thread.sleep(2000);
                jl.setMessage("This is FYI.", jl.INFORMATION);
                jazzdlg.showMsgBox("Information",
                                   "This is FYI.",
                                   btns,
                                   jazzdlg.INFORMATION,
                                   true,
                                   f);
                Thread.sleep(2000);
                jl.setMessage("Help wanted?", jl.HELP);
                jazzdlg.showMsgBox("Help",
                                   "Help wanted?",
                                   btns,
                                   jazzdlg.HELP,
                                   true,
                                   f);
                Thread.sleep(2000);
                jl.setMessage("To be or not to be...", jl.CONFIRM);
                jazzdlg.showMsgBox("Confirm",
                                   "To be or not to be...",
                                   btns,
                                   jazzdlg.CONFIRM,
                                   true,
                                   f);
                Thread.sleep(2000);
                jl.setMessage("Relax, it's a warning only.", jl.WARNING);
                jazzdlg.showMsgBox("Warning",
                                   "Relax, it's a warning only.",
                                   btns,
                                   jazzdlg.WARNING,
                                   true,
                                   f);
                Thread.sleep(2000);
                jl.setMessage("It's an exception. What did ya do?", jl.EXCEPTION);
                jazzdlg.showMsgBox("Exception",
                                   "It's an exception. What did ya do?",
                                   btns,
                                   jazzdlg.EXCEPTION,
                                   true,
                                   f);
                Thread.sleep(2000);
                jl.setMessage("Some error happened.", jl.ERROR);
                jazzdlg.showMsgBox("Error",
                                   "Some error happened.",
                                   btns,
                                   jazzdlg.ERROR,
                                   true,
                                   f);
                Thread.sleep(2000);
            }
        }
        catch(InterruptedException ie)
        {
            ie.printStackTrace();
        }
   }
}


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



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