分享
 
 
 

CREATING ROUND SWING BUTTONS 2

王朝java/jsp·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

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.

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) {

super(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);

setPreferredSize(size);

// This call causes the JButton not to paint the background.

// This allows us to paint 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 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");

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

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

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

FORMATTING BIGDECIMAL NUMBERS

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.

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

- NOTE

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.

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

http://developer.java.sun.com/unsubscribe.html

To 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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有