随机形状和颜色在框架的中心

时间:2013-11-24 11:22:16

标签: java swing colors shape

有兴趣知道如何编写一个输出随机颜色随机颜色的程序,但每次运行程序时它必须位于框架的中心。 下面是我的编码开始...

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RandomShape
{
    JFrame frame;

    public static void main (String[] args)
    {
        RandomShape test = new RandomShape();
        test.go();
    }

    public void go()
    {
        frame = new JFrame();
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

// A Custom panel to draw in.
static class QPanel extends JPanel {
  enum QShape {
    CIRCLE, SQUARE;
    public void draw(Graphics2D g, Color c) {
      g.setColor(c);
      Rectangle2D bounds = g.getClipBounds();

      if (this == CIRCLE) {
        Shape circle = new Ellipse2D.Float(
          (float) bounds.getMinX(),
          (float) bounds.getMinY(),
          (float) (bounds.getMaxX() - bounds
              .getMinX()),
          (float) (bounds.getMaxY() - bounds
              .getMinY()));
        g.draw(circle);
      } else {
        g.drawRect(
          (int) bounds.getMinX() + 10,
          (int) bounds.getMinY() + 10,
          (int) (bounds.getMaxX()
              - bounds.getMinX() - 20),
          (int) (bounds.getMaxY() - bounds
              .getMinY()) - 20);
      }
    }
  }

  private Color shapeColor;
  private QShape shape;

  public Color getShapeColor() {
    return shapeColor;
  }

  public void setShapeColor(Color shapeColor) {
    this.shapeColor = shapeColor;
  }

  public QShape getShape() {
    return shape;
  }

  public void setShape(QShape shape) {
    this.shape = shape;
  }

  /**
   * @see javax.swing.JComponent#paint(java.awt.Graphics)
   */
  @Override
  public void paint(Graphics g) {
    super.paint(g);
    shape.draw((Graphics2D) g, shapeColor);
  }
}

public static void main(String args[]) {
  SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      QPanel panel = new QPanel();
      // Chosen by random dice roll...
      panel.setShape(QPanel.QShape.SQUARE);
      // Chosen by throwing a dart at a color wheel -
      // given my aim, that should be aproximately random.
      panel.setShapeColor(Color.blue);
      frame.add(panel, BorderLayout.CENTER);
      frame.setPreferredSize(new Dimension(400, 400));
      frame.pack();
      frame.setVisible(true);
    }
  });
}