Creating Round Swing Buttons
THIS TIP Is About Round Swing Buttons. Actually, The Information in
THIS TIP Applies TO A Button of Any Arbitrary Shape But To Keep THE
Discussion Simple, We're Just Going To Use A Round Shape.
The there too.
THE FIRST IS To Override The Appropriate Painting Methods in ORDER
TO Paint The Round Shape. The second is to set things up so what
The Button Responds ONLY WHEN You Click With
(NOT JUST WITHIN The Rectangle That Contains the Round Button).
Here's An Example Program That Implements A Round Button.
Import java.awt. *;
Import java.awt.geom. *;
Import javax.swing. *;
Public Class RoundButton Extends JButton {
Public roundbutton (String label) {
Super (label);
// Thase Statements Enlarge the Button SO That IT
// becomes a circle rather tran.
Dimension size = getpreferredsize ();
Size.width = size.height = math.max (size.width, size.height);
SetPreferredSize (size);
// this call causes the jbutton not to pieint the background.
// this allows us to pieint a round background.
SetContentareAfilled (false);
}
// Paint The Round Background and label.
Protected void PaintComponent (Graphics g) {
IF (getModel (). isarmed ()) {
// you might want to make the highlight color
// a Property of the RoundButton Class.
g.setcolor (color.lightgray);
} else {
G.SetColor (GetBackground ());
}
G.Filloval (0, 0, getSize (). Width-1, getSize (). HEIGHT-1);
// this Call Will Paint The Label and the focus Rectangle.
Super.PaintComponent (g);
}
// Paint The Border of the Button Using A Simple Stroke.
Protected void PaintBorder (graphics g) {
G.SetColor (GetForeground ());
g.drawoval (0, 0, getSize (). width-1, getsize (). HEIGHT-1);
// Hit detection.
Shape shape;
Public Boolean Contains (int X, int y) {
// if The Button Has Changed Size, Make A New Shape Object.
IF (Shape == Null ||! shape.getbounds (). Equals (GetBounds ())) {
Shape = new elipse2d.float (0, 0, getWidth (), getHeight ());
}
Return shape.contains (x, y);
}
// Test Routine.
Public static void main (String [] args) {
// CREATE A Button with the label "jackpot".
JButton Button = New RoundButton ("JackPot");
Button.SetBackground (Color.green);
// Create a Frame in which to show the button.
JFrame frame = new jframe ();
Frame.getContentPane (). setBackground (color.yellow);
Frame.getContentPane (). Add (button);
Frame.getContentPane (). setLayout (New flowLayout ());
Frame.setsize (150, 150);
Frame.setVisible (TRUE);
}
}
The Roundbutton Class Extends JButton Because We Want To Keep Most
Of functionality of a jbutton. in The Roundbutton Constructor, The Roundbutton Constructor, THE
Method setContentareafilled () is caled. this causes the button
Paint the focus rectangle, but not to pieint the background.
Now We need to Paint The Circular Background. That's Done By
Overriding the pointcomponent () Method. That Method Uses
Graphics.Filloval () to Paint A Solid Circle. Then PaintComponent ()
Calls super.paintcomponent () to Paint The lambel on top of the solid
Circle.
This Example Also Overrides PaintBorder () in Order to Paint A Border
Around The Round Button. if you don't want a border, you would not
Override this method. this method calls graphics.drawoval () to
Paint a this border around the circle.
Finally, we want the button to respond Only When a User ClickS on
IT, But Not Respond to Click Outside of It. by Default, A JButtonResponds To Mouse ClickS in A Rectangular Area Around To
Button. a JButton Has No IDEA About The Real Shape of The Button,
And so it just assocangular. to tell
JButton The Real Shape of A Button you need to override the
Contains () Method. The contacts () Method Takes a Coordinate and
Returns True If the Coordinate IS ISIDE The Button and False
Otherwise. The Method Uses a Shape Object (Ellipse2D) To Dermine
WHETER THE COORDINATE IS INSIDE The CIRCLE.
NOTE: IN JDK 1.2.2, There's a small bug in How JButton Behaves When
You Drag the mouse in and out of its perimeter. ideally, if you
Clickon The Circular Button and Then Drag The Mouse Outside of The Mouse Outside of THE
Button's Perimeter, The Button Should Change ITS APPEARANCE. WHEN
You Drag The Mouse Back Into The Circular Button's Perimeter, The Circular Button
Button Should Restore ITS APPEARANCE. Unfortunately, The Code That
Implements this Behavior Does Not Call The Contains () Method.
INSTEAD IT JUST Uses The "Bounds" of the button (this is the
Smallst Rectangular Area Containing The Button. NOTICE THAT IF
You Drag The Mouse Slightly Beyond The Circular Perimeter, That IS,
Outside of the circle but not outside the bounds, the button Won't
Change it's appearance. There is no workaround for this minor bug
Except to Implement All of the functionality yourself.
Formatting BigDecimal Numbers
Floating and Double Precision Variables Are Fine for doing
Statistical or Graphics-Related Calculation. However they area
Recommended Forfinancial Calculation. That's Because The Results
Producting by floating and double precision arithmetic are not always
PRECISE. for Example, The Following Example Subtracts 1.1 from 2using floating point number.
Double f = 2.9 - 1.1;
System.out.println (f);
Rather Than 1.8.
IF this Kind of Result Is Unacceptable in your application, as IS
The Case with Most Financial Applications, You Should Use BigDecimal
Numbers instead of floating point number. here's a quick example
Of Using BigDecimal Numbers.
Import java.math. *;
Class BigDecimaltest {
Public static void main (String [] args) {
BigDecimal a = New BigDecimal ("2.9");
BigDecimal B = New BigDecimal ("1.1");
BigDecimal c = a.subtract (b);
System.out.println (c); // 1.8
}
}
One of the features missing from the bigdecimal class is formatting
Methods. When You Print A BigDecimal Number, All The Digits Are
Printed (E.G. 12.3456000). this isn't what you want if you have to to
Print A Value in Dollar And Cents Format, for Example (12.35).
Formatting Features Might Be Added in a Later Release But in The
Meantime, Here Are Some Quick Routines To Perform The Two Most
Common Operations: stripping trailing Zeroes and Displaying with a
Specified Precision.
Class FormatbigDecimal {
// Returns The BigDecimal Value N with trailing Zeroes Removed.
Static BigDecimal Trim (BigDecimal N) {
Try {
While (true) {
n = n.setscale (n.scale () - 1);
}
} catch (arithmeticException e) {
// no more trailing zeroes so exit.
}
Return n;
}
// Returns The BigDecimal Value N with exactly 'PREC' DECIMAL PLACES.
// Zeroes Are Padded to The Right of the Decimal Point if Necessary.
Static BigDecimal Format (BigDecimal N, INT PREC) {
Return n.setscale (PREC, BIGDECIMAL.ROUND_HALF_UP);
}
// some example.public static void main (String [] args) {
System.out.println (Trim (NEW BIGDECIMAL)))))); // 12.323
System.out.println (New BigDecimal ("12.32534"), 2)); // 12.33
System.out.println (Format (New BigDecimal ("12"), 2)); // 12.00
}
}
THE TOM () Method Attempts to Eliminate The Last Digit from the
Number. if The Digit is Zero, It Attempts to Eliminate Another.
IT Tries to Eliminate a non-zero Digit, setscale () throws an
Exception, and The Method Returns The Result.
THE TRIM () Method Does Not Use Exceptions in a Proper Way. You
SHOULD Only Use Exceptions for Exceptional Cases and NOT for
Breaking out of loops as itever, this technique
Is Currently The MOST Efficient Way TO IMPLEMENT THIS functionality.
(If you do use this method, you have to prosise to correct ithen
a better way comes along!)
THE FORMAT () Method Simply Returns a Version of the BigDecimal
Number with the scale of the number set to the specified precision.
IT ROUNDS The Number Such That 5's or Greater Are Rounded Up and
4'S or Lesser Are Rounded Down.
...........................
- Note
The name on the jdc mailing list is used for Internal Sun
Microsystems (TM) Purposes Only. To remove your name from the list,
See Subscribe / Unsubscribed Below.
- Feedback
Comments? Send Your Feedback on the JDC Tech Tips TO:
JDC-Webmaster
- Subscribe / unsubscribe
The JDC Tech Tips Are Sent to you Because You Electrted to Subscribe
When You Registered As a JDC Member. To unsubscribe from JDC Email,
Go to the Following Address and Enter the Email Address you wish To
REMOVE from the mailing list:
Http://developer.java.sun.com/unsubscribe.htmlto Become a JDC Member and Subscribe to this newsletter Go To:
http://java.sun.com/JDC/
- Archives
You'll Find The JDC Tech Tips Archives At:
Http://developer.java.sun.com/developer/techtips/index.html
- CopyRight
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.
This document is protected by copyright. For more information, see:
Http://developer.java.sun.com/developer/copyright.html
This Issue of the JDC Tech Tips is Written by Patrick Chan,
The Author of The Publication "The Java (TM) Developers Almanac"
(http://java.sun.com/docs/books/almanac/index.html).
JDC TECH TIPS
August 26, 1999