我正在尝试创建一个打印 10 个随机图形(椭圆形、矩形等)的代码。我希望通过在 ArrayList 中添加我的随机椭圆等来做到这一点,然后让 Java 从这个 ArrayList 中随机选择一个形状 10 次并打印这些选择的项目。
现在我不知道这是否可能以及我将如何去做。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Cara extends JPanel implements ActionListener {
Random random = new Random();
//...s
public Cara() {
setPreferredSize(new Dimension(400,300)); // make panel 400 by 300 pixels.
// ...
this.setBackground(Color.WHITE);
}
protected class RandomShapesComponent extends JComponent{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // clears the background
// ...
}
}
/**
* redraws the Cara JPanel, when the button is pressed. *
*/
@Override
public void actionPerformed(ActionEvent e) {
regenerate();
repaint();
}
private void regenerate() {
// clear the shapes list
//...
// create random shapes
// ...
}
public static void main(String[] arg) {
final Cara cara = new Cara();
// create the GUI on the event thread.
// this is better than
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame("Computer Assisted Random Artist");
frame.add(cara, BorderLayout.CENTER);
JButton button = new JButton("redraw");
button.addActionListener(cara);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
cara.regenerate(); // can be done here if cara has a size!
frame.setVisible(true);
}
});
}
}
下面是我绘制三角形的一种方式(这是我想放入数组并随机选择的形状之一):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tri extends Cara{
public void paintComponent (Graphics g){
// create random variables for collor and shape of triangle
int x;
int y;
int x2;
int y2;
x = (int) Math.random()*100;
y = (int) Math.random()*100;
x2 = (int) Math.random()*100;
y2 = (int) Math.random()*100;
int r1;
int g1;
int b1;
r1 = (int) Math.random()*255;
g1 = (int) Math.random()*255;
b1 = (int) Math.random()*255;
Color color = new Color(r1,g1,b1);
//draw triangle
g.setColor(color);
g.drawLine(x,y,y2,y);
g.setColor(color);
g.drawLine(x,y,y2,y2);
g.setColor(color);
g.drawLine(y2,y,y2,y2);
}
}