How to print an object several times in Java? - java

I am working on a program that should print a pyramid. Base of the pyramid is 14 blocks. Blocks are (30,12) pixels. Dimensions of an applet which pyramid will be printed on is (800,400). Base block starts at (100,380). I figured that if I duplicate that block and move it 30 pixels in x-direction 14 times, I will finish the base. I am having a trouble to do so. I used for loop to duplicate and move the block but doesn`t work.
What am I doing wrong?
import acm.graphics.GRect;
import acm.program.*;
public class Pyramid extends GraphicsProgram
{
public static final int BRICK_WIDTH = 30;
public static final int BRICK_HEIGHT = 12;
public static final int BRICK_IN_BASE = 14;
public void run()
{
setSize(800,400);
GRect rec = new GRect (100,380,BRICK_WIDTH,BRICK_HEIGHT);
for (int i = 0; i<14; i++)
{
rec.move(30,0);
add(rec);
}
}
}

Look at the condition in your for-loop. You're telling the compiler too loop while i is bigger than 14, which is never true.
Change it too i < 14.

There is only one rectangle in your program. The add() method adds the same object multiple times; you will need to create a new one every time.

You need to change your for loop condition, i is never greater than 14, should be less than.
Also you should make a new Grect, and just change the x value for each new one by 30
import acm.graphics.GRect;
import acm.program.*;
public class Pyramid extends GraphicsProgram
{
public static final int BRICK_WIDTH = 30;
public static final int BRICK_HEIGHT = 12;
public static final int BRICK_IN_BASE = 14;
public void run()
{
setSize(800,400);
int x = 100;
int y = 380;
for (int i = 0; i<14; i++)
{
GRect rec = new GRect (x, y,BRICK_WIDTH,BRICK_HEIGHT);
x += BRICK_WIDTH;
add(rec);
}
}
}

You aren't duplicating it, you're simply moving it. Try the following:
public void run() {
setSize(800,400);
int x=100, y=380;
GRect rec;
for (int i = 0; i<BRICK_IN_BASE; i++) {
rec = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(rec);
x += BRICK_WIDTH;
}
}

Related

Coloring Individual Pixels

i'm trying to write a program with Java what generates images by coloring individual pixels with RGB by adding up the value of every RGB-channel by one until it reaches 255 and then adds one on the next RGB channel.
Here an example:
RED is set to 0
GREEN is set to 0
BLUE is set to 0
RED gets added up by one (RED ++)on the first pixel until it reaches 255.
After RED reaches 255 RED gets set to 0 and GREEN gets added up by one (GREEN ++).
The RED channel gets added up again like in step 1 until 255 and then step 2 follows again.
If GREEN is 255 the same method is used for BLUE means that one gets added to BLUE while GREEN and RED will be set to 0 again. Then step 1 again.
After all channels in the first Pixel are 255 the second pixel gets one up on its RED channel. Then it should begin by step 1 again until the second Pixel has a value of 255 on RED, what will set RED back to 0 and GREEN gets one up on the second pixel and so on and so on....
I'm sorry for my bad english and for my limited Java-knowledge.
This is my whole code so far(Stuff in comments is either not important in the project no more, not ready to use or i don't understand how to use it xD):
import javax.swing.JFrame;
//import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
//import java.awt.image.BufferedImage;
public class Quadrat
{
public static void main (String[] args)
{ int x = 100;
int y = 0;
int z = 0;
int Max = 255;
int height = 500;
int width = 500;
if (x < Max){
x ++;
} else {
x = 0;
y ++;
}
if (y > Max){
y = 0;
z ++;
}
if (z > Max){
z = 0;
}
JFrame Bild = new JFrame("Bildergenerator");
Bild.setSize(width,height);
Bild.setVisible(true);
Color Kartoffel = new Color(x, y, z, 255);
BufferedImage Test = new BufferedImage(300, 200,
BufferedImage.TYPE_INT_ARGB);
Graphics graphics = Test.getGraphics();
graphics.setColor(Kartoffel);
graphics.fillRect(100, 100, 100, 100);
graphics.dispose();
Test.setRGB(1, 1, Kartoffel.getRGB());
}
/*System.out.println(x);
System.out.println(y);
System.out.println(z);*/
//img.setRGB(x,y,z);
/* JFrame Test = new JFrame("Jframe1");
JLabel Label = new JLabel("");
Test.add(Label);
Test.setSize(xx,yy);
Test.setVisible(true);
Test.setLocation(x/2-(xx/2), y/2-(yy/2));*/
/* JFrame Hyaeaeae = new JFrame("BurrScurrSWAG");
Hyaeaeae.setSize(1000,1000);
Hyaeaeae.setVisible(true);
Hyaeaeae.getContentPane().setBackground( Color.RED);*/
}
I'll hope you can help me in any way and if so i'm very thankful!
Thank you for your Attention!
Have a nice day! c:
You need to create the timer for this as your code is just changing on the first iteration on startup after this nothing is changed so a timer to make sure increments keep on applied on variables
package javatestapp;
import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
public class JavaTestApp extends TimerTask
{
static int x = 100;
static int y = 0;
static int z = 0;
static int Max = 255;
static int height = 500;
static int width = 500;
static JFrame frame;
public static void main(String[] args)
{
InitFrame();
}
public static void incrementValues()
{
if (x < Max)
{
x ++;
}
else
{
x = 0;
y ++;
}
if (y > Max)
{
y = 0;
z ++;
}
if (z > Max)
{
x = 0;
y = 0;
z = 0;
}
}
public static void genImage()
{
Color color = new Color(x,y,z,255);
frame.getContentPane().setBackground(color);
}
public static void InitFrame()
{
frame = new JFrame("Bildergenerator");
frame.setSize(width,height);
frame.setVisible(true);
Timer timer = new Timer(true);
TimerTask timerTask = new JavaTestApp();
timer.scheduleAtFixedRate(timerTask, 0, 10);
}
#Override
public void run()
{
incrementValues();
genImage();
}
}

Why wont squares show up after repaint()?

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.....

Java: Mac terminal cannot display Java Graphics

I am trying to draw checkerboard using Java.
I am new to Java. So any advices would be helpful.
UPDATE: I added in the main method. I compiled it successfully in the Mac terminal. However, when I did java Checkerboard, there was an ICON appearing at the bottom and then it disappeared and no graphics appeared. What's wrong in here? The code is as follow:
import acm.graphics.*;
import acm.program.*;
/*
* This class draws a checkerboard on the graphics window.
* The size of the chcekerboard is specified by the constants NROWS
* and NCOLUMNS, and the checkerboard fills the vertical space available.
*/
public class Checkerboard extends GraphicsProgram {
public static void main(String[] args){
Checkerboard c = new Checkerboard();
c.run();
}
// Number of rows
private static final int NROWS = 8;
//Number of columns
private static final int NCOLUMNS = 8;
//Runs the program
public void run() {
int sqSize = getHeight() / NROWS;
for(int i = 0; i < NROWS; i++) {
for(int j = 0; j < NCOLUMNS ; j++) {
int x = j * sqSize;
int y = i * sqSize;
GRect sq = new GRect(x,y,sqSize,sqSize);
sq.setFilled( ((i+j) % 2) != 0);
add(sq);
}
}
}
}
Your class needs to have a main method with the signature
public static void main(String[] args)
for you to be able to run it.
After your edit:
Maybe you need a loop in the main method calling the run method? Something like:
boolean exit = false;
while (!exit) {
c.run();
// if something set exit to true
}
You seem to be lacking the main method: public static void main(String[] args) that is run when you start your program.
(removed the edit I did before, which was meant to go in my own post)

Drawing random points in JApplet

Real quick question here. In an attempt to generate 20,000 random points, I wrote the following code:
import javax.swing.JApplet;
import java.awt.*;
public class Points extends JApplet {
int x, y;
public void paint (Graphics page) {
for (int i = 0; i < 20000; i++);
{
x = (int)(Math.random()*200);
y = (int)(Math.random()*200);
page.drawLine(x, y, x, y);
}
}
}
However, this resulted in only one point being (randomly) drawn. Can someone help me identify my mistake? Thank you in advance.
You have a semicolon just after your for. Erase it and your code will work.
for (int i = 0; i < 20000; i++) {
x = (int)(Math.random()*200);
y = (int)(Math.random()*200);
page.drawLine(x, y, x, y);
}
Further Explanation: When you use the semicolon after a for declaration, it will end the for statement, resulting in something like
for(int i = 0; i < 20000; i++) {
}
x = (int)(Math.random()*200);
//rest of the code...
That's why your code display only 1 point.

creating a loop that draw the person three times, moving the person dX dY?

java code. Im confused with this question
6. Now put a loop in your paintComponent method that draws the person three times, moving him (her?)
150 or so pixels each time (you decide how far)
Do i need to create a scanner in Jframe to ask user to how much he or she want to move the person and they can only move the person 3 times?
help
import javax.swing.*;
import java.awt.*;
import java.applet.Applet;
public class DrawPersonPanel extends JPanel {
private final int WIDTH = 600;
private final int HEIGHT = 400;
private int headX = 60;
private int headY = 40;
private int[] hairX = {62,75,84,85,88,90,93,99,104,110};
private int[] hairY = {45,46,37,38,39,30,31,32,33,54};
private int[] shirtX = {60,0,20,60,50,130,120,160,180,120};
private int[] shirtY = {100,150,180,160,250,250,160,180,150,100};
private int[] zigzagX = {70,75,80,85,90,95,100,105,110};
private int[] zigzagY = {135,140,135,140,135,140,135,140,135};
private int[] pantsX = {50,130,150,110,90,70,30};
private int[] pantsY = {250,250,375,375,300,375,375};
//--------------------------------------
// Constructor: Set up the panel.
//--------------------------------------
public DrawPersonPanel()
{
setPreferredSize(new Dimension(WIDTH, HEIGHT));
}
//--------------------------------------
// Draw person
//--------------------------------------
public void paintComponent (Graphics page)
{
page.setColor(Color.blue);
page.fillPolygon(shirtX, shirtY, shirtX.length);
page.setColor(new Color(255, 228, 181));
page.fillOval(headX, headY, 60, 60 - 10);
page.setColor(Color.BLACK);
page.fillPolygon(hairX, hairY, hairX.length);
page.setColor(Color.WHITE);
page.drawPolyline(zigzagX, zigzagY, zigzagX.length);
page.setColor(Color.cyan);
page.fillPolygon(pantsX, pantsY, pantsX.length);
}
private void movePerson(int x, int y){
// Increment head.
headX += x;
headY += y;
for (int i = 0; i < hairX.length; i++)
{hairX[i] += x;}
for (int i = 0; i < hairY.length; i++)
{hairY[i] += y;}
// Increment shirt.
for (int i = 0; i < shirtX.length; i++)
{shirtX[i] += x;}
for (int i = 0; i < shirtY.length; i++)
{shirtY[i] += y;}
// Increment zig-zag on shirt.
for (int i = 0; i < zigzagX.length; i++)
{zigzagX[i] += x;}
for (int i = 0; i < zigzagY.length; i++)
{zigzagY[i] += y;}
// Increment pants.
for (int i = 0; i < pantsX.length; i++)
{pantsX[i] += x;}
for (int i = 0; i < pantsY.length; i++)
{pantsY[i] += y;}
repaint();
}
}
What the question is saying is to create a loop that calls the function movePerson 3 times by a fixed amount. They are just saying it can be any arbitrary amount that you pick (beforehand, while coding).
Create one person where their left and right position depends on a variable, say X, and then make a for loop that increments X by the preset amount every time.
Like this:
for(int i = 0; i < 450; i+= 150){
drawPerson(i, yValue);
}
where drawPerson is a function that draws the person at (i, yValue). This will draw three people, each 150 apart.
You can change how far apart they are by adjusting how much you increment i.
Just play with it until it works. Like Mark Zuckerberg said, "Move fast and break things"

Categories

Resources