Generating Random Graphics + Questions About Learning Java - 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.

Related

Using Java Random Class

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());
}
}

Why doesn't my GUI show squares after repaint()? [duplicate]

I posted this question a bit earlier and was told to make it SSCCE so here goes (if I can make any improvements feel free to let me know):
I'm wondering why when my button "confirm" is clicked the old squares disappear and the redrawn squares do not appear on my GUI (made with swing). The Squares class draws 200 spaced out squares with an ID (0, 1, 2, or 3 as String) inside obtained from a different class (for the purpose of this question, let's assume it is always 0 and not include that class). For clarification: Squares draws everything perfectly the first time (also retrieves the correct IDs), but I want it to redraw everything once the button is clicked with new IDs.
Code for Squares:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Squares extends JPanel{
private ArrayList<Rectangle> squares = new ArrayList<Rectangle>();
private String stringID = "0";
public void addSquare(int x, int y, int width, int height, int ID) {
Rectangle rect = new Rectangle(x, y, width, height);
squares.add(rect);
stringID = Integer.toString(ID);
if(ID == 0){
stringID = "";
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontMetrics fm = g2.getFontMetrics();
int fontAscent = fm.getAscent();
g2.setClip(new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE));
for (Rectangle rect : squares) {
g2.drawString(stringID, rect.x + 7, rect.y + 2 + fontAscent);
g2.draw(rect);
}
}
}
Code for GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIReserver extends JFrame implements Runnable{
private int myID;
private JButton confirm = new JButton("Check Availability and Confirm Reservation");
private JFrame GUI = new JFrame();
private Squares square;
public GUIReserver(int i) {
this.myID = i;
}
#Override
public void run() {
int rows = 50;
int seatsInRow = 4;
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
GUI.getContentPane().remove(square);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this does not show up at all (could be that it wasn't drawn, could be that it is out of view etc...)
GUI.repaint(); //the line in question
}
});
GUI.setLayout(new FlowLayout());
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setLocation(0,0);
GUI.setExtendedState(JFrame.MAXIMIZED_BOTH);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this shows up the way I wish
GUI.add(confirm);
GUI.pack();
GUI.setVisible(true);
}
}
Code for main:
public class AircraftSeatReservation {
static AircraftSeatReservation me = new AircraftSeatReservation();
private final int rows = 50;
private final int seatsInRow = 4;
private int seatsAvailable = rows * seatsInRow;
private Thread t3;
public static void main(String[] args) {
GUIReserver GR1 = new GUIReserver(3);
me.t3 = new Thread(GR1);
me.t3.start();
}
}
One major problem: Your Squares JPanels preferred size is only 20 by 20, and will likely actually be that size since it seems to be added to a FlowLayout-using container. Next you seem to be drawing at locations that are well beyond the bounds of this component, and so the drawings likely will never be seen. Consider allowing your Squares objects to be larger, and make sure to only draw within the bounds of this component.
Note also there is code that doesn't make sense, including:
private int myID;
private JTextField row, column, instru draft saved // ???
package question2;ction1, instruction2, seatLabel, rowLabel; // ???
I'm guessing that it's
private int myID;
private JTextField row, column, instruction1, instruction2, seatLabel, rowLabel;
And this won't compile for us:
int rows = AircraftSeatReservation.getRows();
int seatsInRow = AircraftSeatReservation.getSeatsInRow(); // and shouldn't this take an int row parameter?
since we don't have your AircraftSeatReservation class (hopefully you don't really have static methods in that class).
And we can't compile or run your current code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. So as Andrew Thompson recommends, for better help, please create and post your Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
I would try to OOP-ify your problem as much as possible, to allow you to divide and conquer. This could involve:
Creating a SeatClass enum, one with possibly two elements, FIRST and COACH.
Creating a non-GUI Seat class, one with several fields including possibly: int row, char seat ( such as A, B, C, D, E, F), a SeatClass field to see if it is a first class seat or coach, and a boolean reserved field that is only true if the seat is reserved.
This class would also have a getId() method that returns a String concatenation of the row number and the seat char.
Creating a non-GUI Airplane class, one that holds two arrays of Seats, one for SeatClass.FIRST or first-class seats, and one for SeatClass.COACH.
It would also have a row count field and a seat count (column count) field.
After creating all these, then work on your GUI classes.
I'd create a GUI class for Seats, perhaps GuiSeat, have it contain a Seat object, perhaps have it extend JPanel, allow it to display its own id String that it gets from its contained Seat object, have it override getBackground(...) so that it's color will depend on whether the seat is reserved or not.
etc.....

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

Draw series of concentric circles with random settings

I'm really stuck on how to go about programming this. Need to draw a series of 8 concentric circles using Java drawArc method with following conditions
using import java.util.Random library
Provide for starting the drawings at random location (i.e., the x-y
cooridinate must be calculated randomly).
Provide a random color for each circle
Provide a random diameter for each circle
My current code is able to get random random color for each circle but not clear how to meet other random conditions
// Exercise 12.6 Solution: CirclesJPanel.java
// This program draws concentric circles
import java.awt.Graphics;
import javax.swing.JPanel;
public class ConcentricCircles extends JPanel
{
// draw eight Circles separated by 10 pixels
public void paintComponent( Graphics g )
{
Random random = new Random();
super.paintComponent( g );
// create 8 concentric circles
for ( int topLeft = 0; topLeft < 80; topLeft += 10 )
{
int radius = 160 - ( topLeft * 2 );
int r = random.nextInt(255);
int gr = random.nextInt(255);
int b = random.nextInt(255);
Color c = new Color(r,gr,b);
g.setColor(c);
g.drawArc( topLeft + 10, topLeft + 25, radius, radius, 0, 360 );
} // end for
}
}
// This program draws concentric circles
import javax.swing.JFrame;
public class ConcentricCirclesTest extends JFrame {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame=new JFrame("Concentric Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ConcentricCircles cCirclesJPanel = new ConcentricCircles();
frame.add(cCirclesJPanel);
frame.setSize(200,250);
frame.setVisible(true);
}//end main
}
Several points are key to such an exercise:
Start with constants for the number of circles and step size; the random number generator in particular only needs to be created once.
private static final int N = 8;
private static final int S = 32;
private static Random random = new Random();
Choose a random point whose coordinates fall within the drawing area.
// a random point inset by S
int x = random.nextInt(getWidth() - S * 2) + S;
int y = random.nextInt(getHeight() - S * 2) + S;
For each circle, find the diameter as a function of S, adding a random fraction of a step, and render the arc at the chosen point offset by the radius.
for (int i = 0; i < N; i++) {
g2d.setColor(…);
int d = (i + 1) * S + random.nextInt(S / 2);
int r = d / 2;
g2d.drawArc(x - r, y - r, d, d, 0, 360);
}
Resize the enclosing frame, which forces a repaint(), to see the effect.
As random colors are not always appealing, consider Collections.shuffle() on a List<Color>.
private final List<Color> clut = new ArrayList<Color>();
…
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor((float) i / N, 1, 1));
}
…
Collections.shuffle(clut);
…
g2d.setColor(clut.get(i));
Override getPreferredSize() to establsh the drawing panel's size.
private static final int W = S * 12;
private static final int H = W;
…
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
See also Initial Threads.

Diffusing a color in java Draw

I am trying to diffuse a color in java Draw (which doesn't have the capability to diffuse normally) but I ran into an error and I can't seem to spot it.
The way I went about diffusing was by writing a small script that would draw my shape hundreds of times, each time smaller and slightly varying in color. This is my snippet:
import javax.swing.*;
import java.awt.*;
public class DiffuseDraw extends JFrame
{
//set size of window here
final int length = 350;
final int height = 370;
public DiffuseDraw()
{
super("Graphics Project Window");
Container container = getContentPane();
setBackground(new Color(0,0,0));
setSize(length, height);
setVisible(true);
}
// my problem comes here:
public void paint(Graphics g)
{
Draw.fillRectangle(g,0,0,length,height,new Color(19,24,32));
int rad = 325; // size of the biggest circle
float floatGreen = 0; // Color components for black
float floatBlue = 0;
float floatRed = 0;
int counter = 0; // the counter
while (counter < 290) {
rad = rad - 1; // Here we shrink the by a small incriment
floatRed = floatRed + 87/290; //red component slowly goes brighter
floatBlue = floatBlue + 178/290; // blue component slowly goes brighter
floatGreen = floatGreen + 211/290; // green component slowly goes brighter
int intRed = (int)Math.round(floatRed);
int intBlue = (int)Math.round(floatBlue);
int intGreen = (int)Math.round(floatGreen);
Draw.fillCircle(g,173,307,rad,new Color(intRed,intBlue,intGreen));
counter = counter + 1;
}
}
public static void main(String args[]) {
DiffuseDraw prog = new DiffuseDraw();
prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When I compile and run, I only get a black screen. I am guessing that the problem is coming from the colors not changing. The number I am adding the float red blue and green by came from me wanting to diffuse a type of blue, so I took the the brightest color of blue that would appear and divided it by 290, the number of times the loop would run.
Instead of
87/290, 178/290, and 211/290,
try using
(float)87/290, (float)178/290, and (float)211/290.
That will, at least, add some color to the window- the problem is that by default, a number like 87/290 will be evaluated to 0; casting it to a float will give the desired result of 0.3 instead.

Categories