之前输出的图案都是黑白的,加上彩色以后,漂亮多了。
有一点不明白的是,英文为什么把这种同心圆称为bull's eye(牛眼睛)呢?
我还特意搜索了一些图片,明明牛眼睛和同心圆圈差别很大呀。
代码如下:
//Graphics Exercise 6.1
/*Using method fillOval, draw a bull’s-eye that alternates between two random colors, as in
Fig. 6.13. Use the constructor Color(int r, int g, int b) with random arguments to generate random
colors.*/
//Creating JFrame to display DrawPanel.
import javax.swing.JFrame;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
import java.security.SecureRandom;
public class BullEye extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth(); // total width
int height = getHeight(); // total height
int rR1=0;
int rG1=0;
int rB1=0;
int rR2=0;
int rG2=0;
int rB2=0;
final SecureRandom rn = new SecureRandom();
//Color 1
rR1=rn.nextInt(256);
rG1=rn.nextInt(256);
rB1=rn.nextInt(256);
Color c1=new Color(rR1, rG1, rB1);
//Color 2
rR2=rn.nextInt(256);
rG2=rn.nextInt(256);
rB2=rn.nextInt(256);
Color c2=new Color(rR2, rG2, rB2);
for (int i = 10; i > 0;i--){
if(i%2==0){
g.setColor(c1);
g.fillOval(width/2-(i+1)*10, height/2-(i+1)*10,
10+20*i, 10+20*i);}
else{
g.setColor(c2);
g.fillOval(width/2-(i+1)*10, height/2-(i+1)*10,
10+20*i, 10+20*i);}
}
}
public static void main(String[] args)
{
// create a panel that contains our drawing
BullEye panel = new BullEye();
// create a new frame to hold the panel
JFrame application = new JFrame();
// set the frame to exit when it is closed
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel); // add the panel to the frame
application.setSize(250, 250); // set the size of the frame
application.setVisible(true); // make the frame visible
}
}
运行截屏: