Reputation: 19
I am trying to build a program where at least 10 shapes are created randomly and are given random places. So far I have this:
import javax.swing.JFrame;
public class RandomShapeViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("RandomShapeViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RandomShapesComponent component = new RandomShapesComponent();
frame.add(component);
frame.setVisible(true);
}
}
and
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class RandomShapesComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
RandomShapeGenerator r = new RandomShapeGenerator(getWidth(), getHeight());
for (int i = 1; i <= 10; i++)
g2.draw(r.Graphics());
}
}
and
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
public class RandomShapeGenerator {
int width, height;
Random ran = new Random();
public RandomShapeGenerator(int i, int j)
{
int width = i;
int height = j;
}
public void paintComponent(Graphics g)
{
switch(ran.nextInt(10)) {
default:
case 0: g.drawOval(10, 20, 10, 20);
case 1: g.drawLine(100, 100, 150, 150);
case 2: g.drawRect(30,40,30,40);
}
}
}
Now I have a couple of questions:
Upvotes: 1
Views: 5766
Reputation: 8960
is it possible to draw multiple lines in one case (and thus creating a triangle)
Of course. Just call drawLine
3 times, with the coordinates of a triangle. Don't forget the break
statement in each of your case
s.
I also get this error message 1 error found
You don't have all of your necessary imports, or you have a typo in the source code. Are you sure Graphics()
is spelled with an upper-case letter?
how would i be able to fill in the Oval and Rectangle etc with a solid color.
Use fillRectangle
and/or fillOval
APIs.
Upvotes: 1