原创 2001年10月23日 15:33:00

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.

There are two things you need to do when creating a round button. 
The first is to override the appropriate painting methods in order
to paint the round shape. The second is to set things up so that
the button responds only when you click within the round button
(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) {

        // These statements enlarge the button so that it
        // becomes a circle rather than an oval.
        Dimension size = getPreferredSize();
        size.width = size.height = Math.max(size.width, size.height);

        // This call causes the JButton not to paint the background.
        // This allows us to paint a round background.

    // 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.
        } else {
g.fillOval(0, 0, getSize().width-1, getSize().height-1);

        // This call will paint the label and the focus rectangle.

    // Paint the border of the button using a simple stroke.
    protected void paintBorder(Graphics g) {
        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 Ellipse2D.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");

        // Create a frame in which to show the button.
        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new FlowLayout());
        frame.setSize(150, 150);

The RoundButton class extends JButton because we want to keep most
of functionality of a JButton. In the RoundButton constructor, the
method setContentAreaFilled() is called. This causes the button to
paint the focus rectangle, but not to paint the background.

Now we need to paint the circular background. That's done by
overriding the paintComponent() method. That method uses
Graphics.fillOval() to paint a solid circle. Then paintComponent()
calls super.paintComponent() to paint the label on top of the solid

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 thin border around the circle.

Finally, we want the button to respond only when the user clicks on
it, but not respond to clicks outside of it. By default, a JButton
responds to mouse clicks in a rectangular area around the
button. A JButton has no idea about the real shape of the button,
and so it just assumes that the button is rectangular. To tell
JButton the real shape of a button you need to override the
contains() method. The contains() method takes a coordinate and
returns true if the coordinate is inside the button and false
otherwise. The method uses a Shape object (Ellipse2D) to determine
whether 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
button's perimeter, the button should change its appearance. When
you drag the mouse back into the circular button's perimeter, the
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
smallest 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.


Floating and double precision variables are fine for doing
statistical or graphics-related calculations. However they are not
recommended forfinancial calculations. That's because the results
produced by floating and double precision arithmetic are not always
precise.  For example, the following example subtracts 1.1 from 2
using floating point numbers.

        double f = 2.9 - 1.1;
        System.out.println( f );

It produces the result 1.7999999999999998 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 numbers.  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
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 examples.
    public static void main(String[] args) {
        System.out.println(trim(new BigDecimal("12.3230000")));    // 12.323
        System.out.println(format(new BigDecimal("12.32534"), 2)); // 12.33
        System.out.println(format(new BigDecimal("12"), 2));       // 12.00

The trim() method attempts to eliminate the last digit from the
number. If the digit is zero, it attempts to eliminate another.
If 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 it is done here. However, this technique
is currently the most efficient way to implement this functionality.
(If you do use this method, you have to promise to correct it when
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.

.  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .

The names on the JDC mailing list are used for internal Sun
Microsystems(tm) purposes only.  To remove your name from the list,
see Subscribe/Unsubscribe below.

Comments?  Send your feedback on the JDC Tech Tips to:


The JDC Tech Tips are sent to you because you elected 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:

To become a JDC member and subscribe to this newsletter go to:

You'll find the JDC Tech Tips archives at:

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:

This issue of the JDC Tech Tips is written by Patrick Chan,
the author of the publication "The Java(tm) Developers Almanac"

JDC Tech Tips
August 26, 1999

Creating Round SysMenu Buttons

I have seen a lot of code on the Internet about round buttons but none on Round SysMenu buttons, so ...
  • f00tz
  • f00tz
  • 2006年05月15日 15:11
  • 697

Creating CSS Buttons

Creating CSS ButtonsWorking Demo:a.but:link, a.but:visited{ float: left; margin: 2px 5px 2px 5px; ...
  • xuehouniao
  • xuehouniao
  • 2005年02月15日 01:51
  • 669

Codeforces Round #258 (Div. 2)-(A,B,C,D,E)

A:Game With Sticks 水题。。。每次操作,都会拿走一个横行,一个竖行。 所以一共会操作min(横行,竖行)次。 #include #include #include #include ...
  • rowanhaoa
  • rowanhaoa
  • 2014年07月25日 14:39
  • 1538

【解题报告】Codeforces Round #401 (Div. 2)

  • TRiddle
  • TRiddle
  • 2017年02月25日 17:55
  • 437

Codeforces Round #444 (Div. 2)-贪心&尺取-Ratings and Reality Shows 一个模特有两种活动。 ① 拍照片,挣钱 a。 ②开演唱会,花费b 给定模特这两种工作的时间表。 模特可以...
  • qq_35781950
  • qq_35781950
  • 2017年11月11日 20:11
  • 158

解题报告:Codeforces Round #433 (Div. 2) E. Boredom ( 离线处理+树状数组)

题目链接 题意: n*n的矩阵,有n个不同行列的格子染色,染色的格子两两之间组成的矩阵定义为beautiful。 q组询问,每次给出一个矩阵,询问与它相交的beautiful的矩阵的数目 ...
  • qq_32570675
  • qq_32570675
  • 2017年09月07日 09:56
  • 371

Codeforces Round #460 (Div. 2) D. Substring

题目链接:D. Substring 题目大意 一张有向图,每个结点上有一个字母,定义一条路径的权值为路径中出现次数最多的字母的出现次数,求图中权值最大的路径的权值,如果权值可以无限大,输出-1...
  • litmxs
  • litmxs
  • 2018年01月31日 23:25
  • 97

Codeforces Round #378 (Div. 2) E. Sleep in Class

链接: 题意:给一个只含'U'和'D'的字符串,U表示向右走,D表示向左走。每个格子踩一次之后翻转(U变D,D变...
  • Fsss_7
  • Fsss_7
  • 2016年11月15日 13:48
  • 378

Codeforces Round #401 (div. 2)解题报告

Problem A-Shell Game 找规律 6个一组 //Author: Lixiang #include struct Shell_Game{ int N,X; void init()...
  • lixiang99410
  • lixiang99410
  • 2017年02月25日 16:17
  • 286

【CodeForces】CodeForces Round #464 (Div. 2) 题解

【比赛链接】点击打开链接【题解链接】点击打开链接【A】Love Triangle【思路要点】按照题意寻找三角形即可。即若存在一个点\(i\)使得\(f[f[f[i]]]==i\),答案为Yes,否则为...
  • qq_39972971
  • qq_39972971
  • 2018年02月18日 11:05
  • 150