首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >绘制具有随机设置的同心圆系列

绘制具有随机设置的同心圆系列
EN

Stack Overflow用户
提问于 2013-09-15 05:30:46
回答 1查看 6.4K关注 0票数 2

我真的被困在如何编程的问题上了。需要在以下条件下使用Java drawArc方法绘制一系列8个同心圆

使用导入java.util.Random库

  1. 规定在任意位置开始绘图(即x-y坐标必须随机计算)。
  2. 为每个圆圈提供一个随机颜色
  3. 为每个圆提供一个随机直径

我目前的代码能够得到每个圆圈的随机颜色,但不清楚如何满足其他随机条件。

代码语言:javascript
运行
复制
// 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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-16 16:41:16

有几点是这项工作的关键:

  • 从圆圈数和步长的常量开始;特别是随机数生成器只需要创建一次。 私有静态最终int N= 8;私有静态最终int S= 32;私有静态随机=新随机();
  • 选择坐标在绘图区域内的随机点。 //由point x= random.nextInt(getWidth() -S* 2) +S,int y= random.nextInt(getHeight() -S* 2) +S.
  • 对于每个圆,求出直径作为S的函数,添加一个台阶的随机分数,并在选定的点上用半径表示圆弧。 对于(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()上的List<Color>。 私有最终列表集群=新的ArrayList();…对于(int i= 0;i< N;i++) {clut.add(Color.getHSBColor(浮点)I/ N,1,1);}…Collections.shuffle(clut);…g2d.setColor(clut.get(i));
  • 重写getPreferredSize()以建立绘图面板的大小。 私有静态最终int W=S* 12;私有静态最终int H= W;…@覆盖公共维数getPreferredSize() {返回新维数(W,H);
  • 另见http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18809216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档