Using Java Random Class - java

Please help. I am trying to use the Java Random class to draw spirals of random locations, size, color, etc. on drawing canvas. I am able to get the Random class to work when I call my drawCurvedSpiral method. However, sometimes it will print some of my spirals partially off the screen. So, how can I prevent this from happening?
Below is what I have...
import java.awt.Graphics;
import java.awt.Color;
import java.util.Random;
public class AbstractArt
{
public static void main(String[] args)
{
DrawingCanvas canvas = new DrawingCanvas();
Graphics g = canvas.getGraphics();
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
int width = 25 + rand.nextInt(76);
int arc = 0 + rand.nextInt(361);
int x = rand.nextInt(canvas.getWidth()-width);
int y = rand.nextInt(canvas.getHeight()-width);
drawCurvedSpiral(g, x, y, width, width, arc, arc, getRandomCOlor());
}
}

Related

Why are two cirles drawn?

I just started to study Java. I am trying to make a program that will show five circles (random color, size and placement). I thought I would try to draw one circle (before I try five). But I draw two circles! What is going on? How is it drawing two circles?
Here is my code:
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import java.util.Random;
public class Rita extends JFrame
{
public Rita()
{
setTitle("Rita");
setSize(960, 960);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
// Initiateea random object
Random rand = new Random();
// loop to draw cicles
//for (int i = 0; i<5; i++);
//Initiate random color
int red = rand.nextInt(256);
int green = rand.nextInt(256);
int blue = rand.nextInt(256);
Color randomColor = new Color (red, green, blue);
// Generate random circle width 20 and X pixels
int width = rand.nextInt(201) + 20;
// Generate random X/Y koordinater
int radius = (int)(Math.random()*49) + 2;
int x = (int)(Math.random()*(960-radius*2) + radius);
int y = (int)(Math.random()*(960-radius*2) + radius);
//int x = rand.nextInt(960);
//int y = rand.nextInt(960);
// set the color
g.setColor(randomColor);
// Draw the circle
g.fillOval(x, y, width, width); // aka rita oval, storlek
}
public static void main(String[] args)
{
Rita rita= new Rita();
rita.paint(null);
}
}
I tried to put this code in to hopefully override the two circles drawn or something. It didn't work (of course I deleted the comment-slashes first). It still draws two circles.
// loop to draw cicles
//for (int i = 0; i<5; i++);

Generating Random Graphics + Questions About Learning Java

Before anything: Is it alright to submit a question to Stack Overflow when you're trying to learn to code? I've really put about 20 hours into this problem and am entirely stuck, but if I should remain stuck for the experience of realizing how to craft my own solutions, please say the word Stack Overlords.
I am attempting to create a function that creates ten circles of a semi-random size and location and a random color.
The size and location are semi-random because the circle's radius must be between 5 - 50 pixels; the location must be within the Jpanel.
The color can be anything. The production of the circles must stop at ten and all the circles must be static in the same Jpanel at once.
I've finished the problem almost entirely asides from being able to get the ten circles to remain static within the Jpanel after they've been generated.
I've tried applying a basic for-loop around various sections of the code I thought could produce the desired result. My for-loop is shown below.
for(int i = 0; i < 10; ++i) {
}
package assignment3;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import javax.swing.JFrame;
public class Random_Circles extends JPanel{
private static final long serialVersionUID = 1L;
// Below is the input for our random size.
public static int RandomSize() {
double randomDouble = Math.random();
randomDouble = randomDouble * 50 + 1;
int randomInt = (int) randomDouble;
return randomInt;
}
// Below is the input for our random X-coordinate.
public static int RandomPosition1() {
double randomDouble = Math.random();
randomDouble = randomDouble * 900 + 1;
int randomInt = (int) randomDouble;
return randomInt;
}
// Below is the input for our random Y-coordinate.
public static int RandomPosition2() {
double randomDouble = Math.random();
randomDouble = randomDouble * 400 + 1;
int randomInt = (int) randomDouble;
return randomInt;
}
// I don't really know what this does, but I've gotta do it apparently.
Random rand = new Random();
// Below is the input for our random color.
public void paintComponent(Graphics RC) {
super.paintComponent(RC);
this.setBackground(Color.white);
// Random Size
int RS;
RS = RandomSize();
// X-coordinate
int RP1;
RP1 = RandomPosition1();
// Y-coordinate
int RP2;
RP2 = RandomPosition2();
// Color inputs
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
// Color function
RC.setColor(randomColor);
// Location and size function
RC.fillOval(RP1, RP2, RS, RS);
}
}
Main function that produces Jpanel, calls previous code.
package assignment3;
import javax.swing.JFrame;
import assignment3.Random_Circles;
public class Random_Circles_Exe {
public static void main(String[] args) {
JFrame f = new JFrame("Random Cirlces");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Random_Circles r = new Random_Circles();
f.add(r);
f.setSize(1000,500);
f.setVisible(true);
}
}
Expected: Ten circles with the required parameters appearing and remaining in the JPanel.
Actual: Ten circles being generated the second the function runs, but with each new circle the old one expires. With re-sizing the JPanel ( just by clicking and dragging its border ), more circles are generated.

Concentric circles using a random center point

I am doing a problem I found online for practice and I am having trouble figuring out a step. My goal is to print 6 concentric circles with random colors while using an array as the diameter.
I have managed to get everything working except my circles are not concentric and seem to just draw away from each other.
Any ideas?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.awt.*;
import java.util.Random;
public class E3 {
public static int [] diameters = new int[6];
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(new File("Practice47.txt"));
int panelX = 400, panelY = 400;
DrawingPanel panel = new DrawingPanel(panelX, panelY);
panel.setBackground(Color.WHITE);
Graphics g = panel.getGraphics();
Random r = new Random();
int xCenter = r.nextInt(400);
int yCenter = r.nextInt(400);
for (int i = 0; i < diameters.length; i++) {
diameters[i]=console.nextInt();
g.setColor(new Color(r.nextInt(256),r.nextInt(256), r.nextInt(256)));
g.fillOval(xCenter, yCenter, diameters[i], diameters[i]);
}
for (int i=0;i<diameters.length;i++)
System.out.println("diameters["+i+"] = "+ diameters[i]);
}
}
Here's what my output looks like:
Your fixpoint is the top left corner initially created instead of the middle of the circles. This happens because you specify the rectangle in which to draw an oval inside with fillOval(leftOffset, topOffset, width, height) and not like in your program.
To correct this:
calculate a fixpoint (x0|y0) in your case (xCenter|yCenter), so this step is already done
use fillOval(x0 - d/2, y0 - d/2, d, d) where d is the diameter

Java - I want to draw multiple 2D Ellipses using a timer, but it's not working

Already tried searching, but couldn't find anything.
I'm trying to draw multiple 2D Ellipses using an array, and a for loop, I'm repainting the frame every second. The thing is, I only get one Ellipse everytime I repaint, can somebody tell me what's wrong with me code, please?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class MovingDot extends JFrame{
static int posX = (int)Math.round(Math.random()*780);
static int posY = (int)Math.round(Math.random()*780);
static int width = (int)Math.round(Math.random()*780);
static int height = (int)Math.round(Math.random()*780);
static int dots = 0;
public static Timer timer;
public MovingDot(){
super("Moving Dot");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 800);
Dot2 dot = new Dot2();
add(dot);
setVisible(true);
timer = new Timer((int)Math.round((1000)), timerAction);
timer.start();
}
private ActionListener timerAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae){
posX = (int)Math.round(Math.random()*780);
posY = (int)Math.round(Math.random()*780);
width = (int)Math.round(Math.random()*780);
height = (int)Math.round(Math.random()*780);
float r = (float)Math.random();
float g = (float)Math.random();
float b = (float)Math.random();
Color col = new Color(r,g,b);
setBackground(col);
dots++;
repaint();
}
};
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run()
{
new MovingDot();
}
});
}
}
class Dot2 extends JPanel{
#Override
public void paintComponent(Graphics c2){
int x = MovingDot.posX;
int y = MovingDot.posY;
int w = MovingDot.width;
int h = MovingDot.height;
float r,g,b;
Color col;
Graphics2D c = (Graphics2D) c2;
c.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Ellipse2D.Float[] e = new Ellipse2D.Float[10];
for (int i = 0; i < 10; i++) {
if (i == 0)
r = (float)Math.random();
else
r = 0.163F;
g = (float)Math.random();
b = (float)Math.random();
col = new Color(r,g,b);
c.setColor(col);
e[i] = new Ellipse2D.Float(x, y, w, h);
c.fill(e[i]);
}
}
}
Found out what was wrong myself, I had to make x, y, w and h random in my paintComponent. And no, this is not for a school assignment, I'm trying to teach myself Java using a book.
And about making my methods static, I was planning on using them in my JPanel, but I realised I don't need them, so I'm going to delete them. Thanks for your advice!
You shouldn't be creating your Ellipse array inside of paintComponent, makes no sense.
Instead create the array in the class.
Your JPanel's paintComponent method should not have any program logic in it. It should only have code that paints the ellipses. That is, it should iterate through your array with a for loop, and if the item in the array is not null draw it.
You'd be even better off using an ArrayList<Ellipse2D> and not an array. That way you wouldn't have to check for nulls.
In the Timer's ActionListener, if your counter is < 10, you'd add an Ellipse2D to the array and call repaint.
If the counter >= 10 you'd stop the Timer
Also, none of your static variables should be static, and having them as static suggests that the program design is off. If this is for a school assignment, that could lead to deduction of your grade.

Painting pixels images in Java

Which method is the best way to create a pixel image with java.
Say, I want to create a pixel image with the dimensions 200x200 which are 40.000 pixels in total. How can I create a pixel from a random color and render it at a given position on a JFrame.
I tried to create a own component which just creates pixel but it seems that this is not very performant if I create such a pixel a 250.000 times with a for-loop and add each instance to a JPanels layout.
class Pixel extends JComponent {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getRandomColor());
g.fillRect(0, 0, 1, 1);
}
}
You do not need to create a class for this. Java already has the excellent BufferedImage class that does exactly what you need. Here is some pseudo-code:
int w = 10;
int h = 10;
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(w, h, type);
int color = 255; // RGBA value, each component in a byte
for(int x = 0; x < w; x++) {
for(int y = 0; y < h; y++) {
image.setRGB(x, y, color);
}
}
// Do something with image
The key here is the Canvas class. It is the standard Component that allows arbitrary draw operations. In order to use it, you must subclass the Canvas class and override the paint(Graphics g) method, then loop through each pixel and draw your random color. The following code should work:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
public class PixelCanvas extends Canvas {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final Random random = new Random();
#Override
public void paint(Graphics g) {
super.paint(g);
for(int x = 0; x < WIDTH; x++) {
for(int y = 0; y < HEIGHT; y++) {
g.setColor(randomColor());
g.drawLine(x, y, x, y);
}
}
}
private Color randomColor() {
return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new PixelCanvas());
frame.setVisible(true);
}
}
The generated image looks like this:
You'll probably want to create a BufferedImage of the size you want, and use img.setRGB(x, y, getRandomColor()) to create a bunch of random pixels. Then you could render the whole image wherever you want it.

Categories