我真的很困惑如何进行编程。需要使用Java的drawArc方法绘制一系列8个同心圆,条件如下
使用导入 java.util.Random 库
- 提供在随机位置(即 x-y
坐标必须随机计算)。
- 为每个圆圈提供随机颜色
- 为每个圆提供随机直径
我当前的代码能够为每个圆圈获取随机颜色,但不清楚如何满足其他随机条件
// Exercise 12.6 Solution: CirclesJPanel.java
// This program draws concentric circles
import java.awt.Graphics;
import javax.swing.JPanel;
public class ConcentricCircles extends JPanel
{
// draw eight Circles separated by 10 pixels
public void paintComponent( Graphics g )
{
Random random = new Random();
super.paintComponent( g );
// create 8 concentric circles
for ( int topLeft = 0; topLeft < 80; topLeft += 10 )
{
int radius = 160 - ( topLeft * 2 );
int r = random.nextInt(255);
int gr = random.nextInt(255);
int b = random.nextInt(255);
Color c = new Color(r,gr,b);
g.setColor(c);
g.drawArc( topLeft + 10, topLeft + 25, radius, radius, 0, 360 );
} // end for
}
}
// This program draws concentric circles
import javax.swing.JFrame;
public class ConcentricCirclesTest extends JFrame {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame=new JFrame("Concentric Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ConcentricCircles cCirclesJPanel = new ConcentricCircles();
frame.add(cCirclesJPanel);
frame.setSize(200,250);
frame.setVisible(true);
}//end main
}
进行此类练习的关键有几点:
-
从圈数和步长的常数开始;特别是随机数生成器只需要创建一次。
private static final int N = 8;
private static final int S = 32;
private static Random random = new Random();
-
选择坐标落在绘图区域内的随机点。
// a random point inset by S
int x = random.nextInt(getWidth() - S * 2) + S;
int y = random.nextInt(getHeight() - S * 2) + S;
-
对于每个圆,找到直径作为以下函数的函数S
,添加一个步骤的随机分数,并在所选点处渲染按半径偏移的圆弧。
for (int i = 0; i < N; i++) {
g2d.setColor(…);
int d = (i + 1) * S + random.nextInt(S / 2);
int r = d / 2;
g2d.drawArc(x - r, y - r, d, d, 0, 360);
}
调整封闭框架的大小,这会强制repaint()
,看看效果。
-
由于随机颜色并不总是有吸引力,请考虑Collections.shuffle()
on a List<Color>
.
private final List<Color> clut = new ArrayList<Color>();
…
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor((float) i / N, 1, 1));
}
…
Collections.shuffle(clut);
…
g2d.setColor(clut.get(i));
-
覆盖getPreferredSize() https://stackoverflow.com/q/7229226/230513确定绘图面板尺寸。
private static final int W = S * 12;
private static final int H = W;
…
@Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
也可以看看初始线程 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)