While using an ArrayList, I can't seem to figure out how to reset and re-apply the random color for each iteration of the for loop. I am trying to reset and apply my random color every time my XLeft position is changed. This is only a section of one class I am using, and my getMax() was defined by a Scanner input. Any suggestions?
import java.util.ArrayList;
import java.util.Random;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class BarChart {
private int width, height;
private ArrayList<Double> values = new ArrayList<Double>();
private Random generator = new Random();
int red = generator.nextInt(255);
int green = generator.nextInt(255);
int blue = generator.nextInt(255);
private Color randomColor = new Color(red, green, blue);
public BarChart(int aWidth, int aHeight) {
width = aWidth;
height = aHeight;
}
public void add(double inputValues) {
values.add(inputValues);
}
public double getMax() {
double max = values.get(0);
for (int i = 1; i < values.size(); i++) {
if ((values.get(i)) > max)
max = values.get(i);
}
return max;
}
public void draw(Graphics2D g2) {
int xLeft = 0;
double barWidth = width / values.size();
for (int i = 0; i < values.size(); i++) {
double barHeight = (values.get(i) / getMax()) * height;
Rectangle bar = new Rectangle(xLeft, height - ((int) barHeight),
(int) barWidth, (int) barHeight);
g2.setColor(randomColor);
g2.fill(bar);
xLeft = (int) (xLeft + barWidth);
xLeft++;
}
}
}
It sounds like you're defining your random color once, before the loop. This means that when you run the loop, it uses the same "random color" each time through. You need to move the definition of the random color into the loop, so that it runs with each iteration.
EDIT (based on your comments):
public void draw(Graphics2D g2) {
int xLeft = 0;
double barWidth = width / values.size();
for (int i = 0; i < values.size(); i++) {
double barHeight = (values.get(i) / getMax()) * height;
Rectangle bar = new Rectangle(xLeft, height - ((int) barHeight),
(int) barWidth, (int) barHeight);
red = generator.nextInt(255);
green = generator.nextInt(255);
blue = generator.nextInt(255);
randomColor = new Color(red, green, blue);
g2.setColor(randomColor);
g2.fill(bar);
xLeft = (int) (xLeft + barWidth);
xLeft++;
}
Related
i tried to generate bar chart from input
i would like have my code to get out put like this
enter image description here
this is my code but i have some error
i have some error in label that say should make method label and in main
can you guys help me fix this things
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
public class baronly
{
//Establish the placement of the fields for user entry
// get some error in this
Label LabelA = addLabel("A", 1,1,1,1);
IntegerField FieldA = addIntegerField(0,1,2,1,1);
Label LabelB = addLabel("B", 1,3,1,1);
IntegerField FieldB = addIntegerField(0,1,4,1,1);
Label LabelC = addLabel("C", 1,5,1,1);
IntegerField FieldC = addIntegerField(0,1,6,1,1);
Label LabelD = addLabel("D", 1,7,1,1);
IntegerField FieldD = addIntegerField(0,1,8,1,1);
Label LabelF = addLabel("F", 1,9,1,1);
IntegerField FieldF = addIntegerField(0,1,10,1,1);
//Establish a drop down menu for the drawing
//Right now we only have one choice -- Bar
//Establish variables for this program
int numberOfScores = 5;
int Xleft = 100;
int Xright = 300;
int Ytop = 100;
int Ybottom = 250; // y value entries can be up to 150
int BarWidth = 10;
int totalX , totalY;
int[ ] scores;
char graphChoice;
//Constructor to establish the initial values in the program
public baronly()
{
scores = new int[numberOfScores];
for (int i = 0; i < scores.length; i++)
scores[ i ] = 0;
totalX = Xright - Xleft + 1;
totalY = Ybottom - Ytop + 1;
}
//Allow for the menu choices
//Remember, we only have one choice right now
public void paint (Graphics g)
{
getInputData();
g.setColor (Color.red); //set color of the graph
g.drawString("Java Grades",170,290); //title
drawBarGraph(g);
}
//Get input from the screen
public void getInputData()
{
scores[0] = FieldA.getNumber();
scores[1] = FieldB.getNumber();
scores[2] = FieldC.getNumber();
scores[3] = FieldD.getNumber();
scores[4] = FieldF.getNumber();
}
//Draw the bar graph
public void drawBarGraph(Graphics g)
{
drawAxes(g);
int i, x, y, height, largestNumber, xIncrement, yIncrement;
//Compute the x and y increments
largestNumber = findLargest (scores);
xIncrement = totalX /numberOfScores;
if (largestNumber ==0)
yIncrement = 0;
else
yIncrement = totalY / largestNumber;
//Draw the bars
for(i=0; i < numberOfScores; i++)
{
x = getXCoordinate(i+1, xIncrement);
y = getYCoordinate(scores[i], yIncrement);
x = x - BarWidth / 2;
height = Ybottom - y + 1;
g.fillRect(x, y, BarWidth, height);
}
//Label x - axes with grade choices
String [ ] label = {"A", "B", "C", "D", "F"};
for(i=1; i<= numberOfScores; i++)
g.drawString(label[i-1], 100+ i*xIncrement, 270);
//Label y - axes with quantity of each grade
int topy;
if(largestNumber%10==0)
topy=largestNumber;
else
topy=(largestNumber/10+1)*10;
//i=i+5 controls y value label -- adjust for size of data
for (i=0; i<=topy; i=i+5)
{
g.drawString(String.valueOf(i), 70, Ybottom-i*yIncrement+5);
}
}
//Draw the axes for the graph
public void drawAxes (Graphics g)
{
g.drawLine(Xleft, Ytop, Xleft, Ybottom);
g.drawLine(Xleft, Ybottom, Xright, Ybottom);
}
//Determining x coordinate
public int getXCoordinate(int i, int xIncrement)
{
return Xleft + xIncrement *i;
}
//Determining y coordinate
public int getYCoordinate(int numStudents, int yIncrement)
{
return Ybottom - yIncrement * numStudents;
}
//Finding the largest value in the array
public int findLargest(int [ ] a)
{
int i;
int loc = 0;
for(i=1; i<a.length; i++)
if(a[i]>a[loc])
loc = i;
return a[loc];
}
//Main
public static void main(String[ ] args)
{
baronly frm = new baronly();
frm.setSize(400,300);
frm.setVisible(true);
}
}
that error gave says i should give method in label what that suppose to mean
I am having trouble replicating the picture for my assignment. I would appreciate any tips or solutions. I believe I have the general idea down, but I am having a hard time figuring out the math to replicate the image and doing everything in a single loop.
My program needs to meet these criteria:
Match the Image
Generate a random color for each pair of parabolic curve
Work with any width or height
Use a single loop to draw the entire figure.
Here is the image:
This is what I have tried so far
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int LINE_INCREMENT = 5;
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(WIDTH, HEIGHT);
Graphics g = panel.getGraphics();
int d = 0;
int iterations = HEIGHT/LINE_INCREMENT;
Random rand = new Random();
int red = 0, green = 0, blue = 0;
red = rand.nextInt(128) + 128;
green = rand.nextInt(128) + 128;
blue = rand.nextInt(128) + 128;
g.setColor(new Color(red,green,blue));
for(int y = 0; y < iterations; y++) {
g.drawLine(0, d, d, HEIGHT);
g.drawLine(WIDTH, d, d, 0);
d += LINE_INCREMENT;
}
red = rand.nextInt(128) + 128;
green = rand.nextInt(128) + 128;
blue = rand.nextInt(128) + 128;
g.setColor(new Color(red,green,blue));
d = 0;
for (int x = 0; x < iterations/2; x++) {
g.drawLine(WIDTH/4, d + HEIGHT/4, d + WIDTH/4, HEIGHT - HEIGHT/4);
g.drawLine(d + WIDTH/4, WIDTH/4, WIDTH - WIDTH/4, d + WIDTH/4);
d += LINE_INCREMENT;
}
}
The output:
The way to implement it is by overriding paintComponent:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ParabolicCurves extends JFrame {
private static final int SIZE = 600;
private static final int LINE_INCREMENT = 5;
private static final int NUM_OF_PATTERNS = 4;
private Random rand = new Random();
ParabolicCurves() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel panel = new DrawingPanel(SIZE);
add(panel, BorderLayout.CENTER);
pack();
setVisible(true);
}
class DrawingPanel extends JPanel{
public DrawingPanel(int size) {
setPreferredSize(new Dimension(size, size));
setBackground(Color.WHITE);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int red, green, blue, delta , iterations;
int height, width ,startX, startY, endX, endY ;
Rectangle boundingRrectangle = getBounds();
for(int pattern = 0 ; pattern < NUM_OF_PATTERNS; pattern++) {
red = rand.nextInt(128) + 128;
green = rand.nextInt(128) + 128;
blue = rand.nextInt(128) + 128;
g.setColor(new Color(red,green,blue));
height = (int) boundingRrectangle.getHeight();
width = (int) boundingRrectangle.getWidth();
startX = (int) boundingRrectangle.getX();
startY = (int) boundingRrectangle.getY();
endX = startX+width;
endY = startY+ height;
iterations = Math.min(width, height)/LINE_INCREMENT;
delta = 0;
for (int x = 0; x < iterations ; x++) {
g.drawLine(startX, startY+delta, startX+delta, endY);
g.drawLine(endX, startY+delta, startX+delta, startY);
delta += LINE_INCREMENT;
}
//change bounding rectangle
boundingRrectangle = new Rectangle(startX+(width/4),
startY+(width/4), width/2, height/2);
}
}
}
public static void main(String[] args) {
new ParabolicCurves();
}
}
Output:
I'm creating a game that has randomly drawn Asteroids (to give the Asteroids a jagged look). After research I've only found that you can fill primitive shapes. Does anyone know a method I could use to fill these shapes?
package view.game_object;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Asteroid extends BaseGameObject {
public static final int BASE_SIZE = 10;
private final int fragmentCount;
private final int[][] points;
private final int level;
public Asteroid(int level, Random r) {
this.level = level;
this.setBound(level * Asteroid.BASE_SIZE);
int sizeRange = (int) (this.getBound() / 2);
this.fragmentCount = this.level * 6;
// generate random points to draw
this.setPosition(0, 0);
this.points = new int[fragmentCount][2];
ArrayList<Float> angleList = new ArrayList<>();
for (int i = 0; i < fragmentCount; i++) {
angleList.add(r.nextFloat() * (float) (Math.PI * 2));
}
Collections.sort(angleList);
for (int i = 0; i < this.points.length; i++) {
// base point
float x = r.nextInt(sizeRange) + this.getBound() - sizeRange / 3;
// rotate
float[] point = BaseGameObject.rotate(x, 0, this.getPosx(), this.getPosy(),
angleList.get(i));
this.points[i][0] = (int) point[0];
this.points[i][1] = (int) point[1];
}
}
public int getLevel() {
return level;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.gray);
for (int i = 0; i < this.points.length; i++) {
int nextPoint = i + 1;
if (nextPoint >= this.points.length) {
nextPoint = 0;
}
g.drawLine(Math.round(this.getPosx()) + this.points[i][0],
Math.round(this.getPosy()) + this.points[i][1],
Math.round(this.getPosx()) + this.points[nextPoint][0],
Math.round(this.getPosy()) + this.points[nextPoint][1]
);
}
}
}
you can use the Graphics methods to draw a polygon. but you must 'transform' your points into a proper format getXs(), i didn't point that out, i'm pretty sure you can do this as good as i can =)
#Override
public void draw(Graphics g) {
g.setColor(Color.gray); //fillColor
int[] xPoints = getXs(this.points);
int[] yPoints = getYs(this.points);
int nPoints = xPoints.length;
g.fillPolygon(xPoints, yPoints, nPoints);
}
Hey if i have a simple rectangle class, how can i make it so that it creates that rectangle next to each other in a grid like pattern? maybe like 10 rows 10 columns?
public class Vak {
private int posX = 0;
private int posY = 0;
private int width = 50;
private int height = 50;
private Color colour;
public Vak(Color c, int x, int y){
this.colour = c;
this.posX = x;
this.posY = y;
}
public int vakPosY(){
return this.posY;
}
public int vakPosX(){
return this.posX;
}
public void draw (Graphics g){
g.setColor(this.colour);
g.drawRect(posX, posY, width, height);
}
public void move(int numberPixelsX, int numberPixelsY){
this.posX = this.posX + numberPixelsX;
this.posY = this.posY + numberPixelsY;
}
}
this is my code for rectangle "vak"
Is this what you are looking for?
int mapWidth = 10;
int mapHeight = 10;
// tileWidth and tileHeight should probably be public static const fields or static readonly properties of some class, but I put them here for now.
int tileWidth = 50; // Pixels
int tileHeight = 50; // Pixels
// tiles should probably be a field of a Map class (if you have one)
Vak[][] tiles = new Vak[mapWidth][mapHeight];
for(int x = 0; x < mapWidth; x++)
{
for(int y = 0; y < mapHeight; y++)
{
tiles[x][y] = new Vak(Color.white, x*tileWidth, y*tileHeight);
}
}
And then in the drawing part of the main loop:
for(Vak[] row : tiles)
{
for(Vak tile : row)
{
tile.draw(g);
}
}
I am trying to make a bar chart. Everything goes fine; the code compiles and runs successfully. But the frame (window) is not packed perfectly. There is some space at the end of the bar chart. I just want this space removed.
public class BarChart extends JPanel{
int[] percentage;
Color color;
double barOffset;
public BarChart(int[] percentage, Color color) {
this.color = color;
this.percentage = percentage;
}
public BarChart(int[] percentage) {
this.color = Color.black;
this.percentage = percentage;
}
public BarChart() {
this.color = Color.black;
}
int w = 1,h = 1;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
w = getWidth();
h = getHeight();
g.setColor(color);
barOffset = w*0.05;
int barWidth = (int)(w*0.1);
for(int i = 0; i<percentage.length; i++) {
g.fillRect((int)(barOffset),(int)(h*0.95-2*percentage[i]), barWidth, 2*percentage[i]);
if(i < percentage.length-1)
barOffset = (i+2)*w*0.05 + (i+1)*(barWidth);
}
}
}
This was not a packing error, but rather you were drawing off the edge of the component. To check for packing errors, set a background color for the container that is distinct from the component color.
For the set int[] p = new int[]{100, 5, 6, 9, 1, 0, 5, 100};, your bars are being drawn as follows:
component dimensions: width=104 height=10
bar[0]: xLeft=5 yTop=-190 barWidth=10 barHeight=200
bar[1]: xLeft=20 yTop=0 barWidth=10 barHeight=10
bar[2]: xLeft=35 yTop=-2 barWidth=10 barHeight=12
bar[3]: xLeft=50 yTop=-8 barWidth=10 barHeight=18
bar[4]: xLeft=66 yTop=7 barWidth=10 barHeight=2
bar[5]: xLeft=81 yTop=9 barWidth=10 barHeight=0
bar[6]: xLeft=96 yTop=0 barWidth=10 barHeight=10
bar[7]: xLeft=111 yTop=-190 barWidth=10 barHeight=200
I think this produces what you're looking for. Drawing components can be tricky, and the way I mitigate the complexity is to keep track of my screen locations semantically.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BarChart extends JPanel
{
public static void main(String[] args)
{
int[] p = new int[]{100, 5, 6, 9, 1, 0, 5, 100};
JFrame f = new JFrame();
f.setBackground(Color.BLUE);
BarChart chart = new BarChart(p);
chart.setBackground(Color.RED);
f.add(chart);
f.pack();
f.show();
}
private int[] percentage;
private Color color;
private boolean padEnds = true;
public BarChart(int[] percentage, Color color)
{
this.percentage = percentage;
this.color = color;
return;
}
public BarChart(int[] percentage)
{
this(percentage, Color.BLACK);
return;
}
public BarChart()
{
this(new int[0]);
return;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(this.color);
int width = super.getWidth();
int height = super.getHeight();
int topPadding = Math.round(height * 0.05f);
int barCount = this.percentage.length;
int barOffset = Math.round(width * 0.025f); // 2.5% (in pixels) reserved space on both sides of each bar == 5% between bars
int totalOffsetWidth = (barOffset * 2) * barCount;
if (!this.padEnds)
{
totalOffsetWidth -= (barOffset * 2);
}
int availableWidth = width - totalOffsetWidth;
int availableHeight = height - topPadding;
int barWidth = (int) Math.floor((float) availableWidth / (float) barCount);
int xLeft = 0;
for (int i = 0; i < barCount; i++)
{
int percent = this.percentage[i];
if (this.padEnds || (i != 0))
{
xLeft += barOffset; // Add offset here to pad left side of each bar.
}
int barHeight = Math.round(((float) availableHeight) * ((float) percent / 100f));
int yTop = topPadding + (availableHeight - barHeight);
g.fillRect(xLeft, yTop, barWidth, barHeight);
xLeft += barWidth; // advance the next drawing position
if (this.padEnds || (i != (barCount - 1)))
{
xLeft += barOffset; // Add offset here to pad right side of each bar.
}
}
return;
}
}