Java 框架中心的随机形状和颜色
我很想知道如何编写一个程序,该程序输出随机形状和随机颜色,但每次运行该程序时,它必须位于帧的中心。 下面是我的编码开始Java 框架中心的随机形状和颜色,java,swing,colors,shape,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 =
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);
}
}
试试这样的
// 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);
}
});
}
显示您尝试过的代码。生成随机点数并填充形状。请列举您想要支持的形状、颜色集(或整个光谱中真正随机的)、您尝试过的代码以及您遇到的错误(或问题)。