Drawing random points in JApplet - java

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.

Related

Creating a color-changing grid applet in Java

For a school project, I need to create an applet that produces a 10 x 10 grid in which each cell will change color in accordance to what some threads are doing in the background. I have all of the rest figured out, but I don't have the slightest clue as to how to display this grid. This is the only example code we were given:
import java.awt.*;
import java.applet.Applet;
public class Array2 extends Applet {
private final ststic int LIMIT = 9;
private int[][] results;
public void init() {
int count = 1;
results = new int [LIMIT][LIMIT];
for (int i = 0; i < LIMIT; i++) {
for (int j = 0; j < LIMIT; j++) {
results[i][j] = count % 2;
count++;
}
}
}
public void paint (Graphics g) {
int xLoc = 25;
int yLoc = 25;
for (int i = 0; i < LIMIT; i++) {
for (int j = 0; j < LIMIT; j++) {
g.drawString(Integer.toString(results[i][j]), xLoc. yLoc);
xLoc += 20;
}
xLoc = 25;
yLoc += 20;
}
}
}
This ends up printing a blank 2 x 2 grid. This is easy enough to modify into a 10 x 10. However, what I DON'T know how to do is color the squares. Everything I've searched mentions using jPanels or jFrames or something, but this HAS to be an applet. I was just looking for some suggestions as to what I should look into for the coloring process, as this is literally all I have to go on.Thanks!
The applet draws with the class Graphics and passes you an instance in the paint method. You can use Graphics to do many cool things on the screen, so check its methods out! But to draw a colored square, first set the color using g.setColor(color) and then use g.fillRect(xLoc, yLoc, size, size) with xLoc and yLoc being the top-left coordinates of the square.
Albert provided me with the Graphics methods needed to finish this up as an applet. However after reading through the comments and links provided, it looks like I'll just be using Swing instead of AWT.

How to print an object several times in 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;
}
}

Rasterizing a Triangle in Java using 2D array

I am creating a 3D renderer in Java but I have a problem when trying to render the polygons with a solid color fill. It works perfectly fine but every so often it's tearing but I'm not sure whether it is because the algorithm is inefficient or if it's something else because it's only at the vertices's it is tearing. Here is a picture:
Wireframe:
You can see that near the vertices's or rather points of the polygons it tears. I'm storing the color of the pixels in a 2 dimensional array and then cycling through it and rendering them. It still tears even when I make the polygon's really small so I don't think it's a performance problem. I use the Bresham algorithm and store the pixels in a 2 dimensional array then in the polygon I get the pixels and make them into one big array which I cycle through down the y and then across the x until I hit a pixel. That is set as beginLine and then the last one is set as endLine. I then draw a line between the points.
public void render()
{
int tempPixels[][] = new int[(int) Math.max(vertex_1.getX(), Math.max(vertex_2.getX(), vertex_3.getX())) + 30][(int) Math.max(vertex_1.getY(), Math.max(vertex_2.getY(), vertex_3.getY())) + 30];
for (int x = 0; x < vector_1.getWidth(); x++)
{
for (int y = 0; y < vector_1.getHeight(); y++)
{
if (vector_1.getPixels()[x][y] == 1)
{
tempPixels[(int) (x + Math.min(vertex_1.getX(), vertex_2.getX()))][(int) (y + Math.min(vertex_1.getY(), vertex_2.getY()))] = 1;
}
}
}
for (int x = 0; x < vector_2.getWidth(); x++)
{
for (int y = 0; y < vector_2.getHeight(); y++)
{
if (vector_2.getPixels()[x][y] == 1)
{
tempPixels[(int) (x + Math.min(vertex_2.getX(), vertex_3.getX()))][(int) (y + Math.min(vertex_2.getY(), vertex_3.getY()))] = 1;
}
}
}
for (int x = 0; x < vector_3.getWidth(); x++)
{
for (int y = 0; y < vector_3.getHeight(); y++)
{
if (vector_3.getPixels()[x][y] == 1)
{
tempPixels[(int) (x + Math.min(vertex_3.getX(), vertex_1.getX()))][(int) (y + Math.min(vertex_3.getY(), vertex_1.getY()))] = 1;
}
}
}
for (int y = 0; y < (int) Math.max(vertex_1.getY(), Math.max(vertex_2.getY(), vertex_3.getY())) + 4; y++)
{
int beginLine = -1;
int endLine = -1;
for (int x = 0; x < (int) Math.max(vertex_1.getX(), Math.max(vertex_2.getX(), vertex_3.getX())) + 4; x++)
{
if (tempPixels[x][y] == 1)
{
if (beginLine == -1)
{
beginLine = x;
}
else
{
endLine = x;
}
}
}
for (int i = beginLine; i < endLine; i++)
{
pixels[i][y] = 1;
colors[i][y] = Color.PINK;
}
}
vector_1.render();
vector_2.render();
vector_3.render();
vertex_1.render();
vertex_2.render();
vertex_3.render();
}
So basically my questions are:
Is this algorithm inefficient, if so what would be a better way?
Why is it tearing near the vertices's only?
Out of the problem description one cannot conclude that the attached image does not show what you want. Technically, the pink zone could depict a set of triangles you have 'correctly' painted (i.e. exactly the way you intended to) :p You could mark the triangles that you intended to be in the image, as an update. I suspect there are 4 triangles, though there are more such possible combinations.
First of all, since the part that, for each y, determines the beginLine and endLine seems to be correct, you should probably iterate till endLine when drawing the associated vertical segment (and not till endLine-1).
But that is probably not the real problem. Try drawing one triangle at a time. If some triangles still render incorrectly also try to see what happens when you eliminate the last part (the one rendering the vectors and the vertices). Why this?! Considering your implementation, you expect just a segment on each y. The image you provided indicates that your implementation sometimes renders more than one segment. So the rendering of the vectors and the vertices might be incorrect, though rendering multiple 'not perfectly aligned' triangles could also cause it.
If this does not solve it either, there might be some small offset in between your triangles. Try to see why that is.
Related to efficiency, that is not at fault. Generally, efficiency and correctness are not related in this way.
EDIT
You should add endLine = x after beginLine = x. With your implementation if you only have one pixel on a vertical line you do not draw it (since endLine will stay -1). This is one way to correct this issue. Also check that beginLine is greater than -1 before starting drawing. And do not forget to iterate from beginLine to exactly endLine.
You can use the method fillPolygon.
Syntax
g.setColor(Color.*color you want*)
g.fillPolygon (new int[]{width Dimensions}, new int [] {Height Dimensions}, no. of co-ordinates);
Note: - The 1st Value is of right Co-Ordinate, 2nd is of mid point and the 3rd is of Left Co-Ordinate.
The final programming with class, variables and methods.
/*Import the following files: -*/
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
import java.awt.Font;
public class Shapes extends JPanel
{
public Shapes()
{
this.addComponentListener(new ComponentListener(){
public void componentShown(ComponentEvent arg0) {
}
public void componentResized(ComponentEvent arg0) {
paintComponent(getGraphics());
}
public void componentMoved(ComponentEvent arg0) {
}
public void componentHidden(ComponentEvent arg0) {
// TODO Auto-generated method stub
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.MAGENTA);
g.setColor(Color.BLUE);
g.fillPolygon (new int[]{250,135,10}, new int [] {160,15,160}, 3);
g.setFont(new Font("TimesRoman", Font.PLAIN, 35));
g.setColor(Color.GREEN);
g.drawString("Triangle", 75, 120);
}
public static void main(String[] args)
{
Shapes obj = new Shapes();
JFrame frame = new JFrame("Shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(obj);
frame.setSize(600, 500);
frame.setVisible(true);
}
}

Java null pointer error

Hello and thank you for reading this. I am coding in java/LWJGL. My problem is that I keep getting a null pointer error with some code if I don't include this one thing. Basically there are 4 classes
A block class.
A blockGrid class
A blocktype class
And a boot class.
The boot class creates a display and in the game loop it runs the draw method that is inside the blockgrid class. To set where a block goes i would use the renderat(x,y) method inside the blockgrid method. The block class just creates a quad at a certain x,y.
Sorry if I'm not explaining good. Here is my code: This is where the error happens just read my comments to see where the error is.
// BlockGrid.java
package minecraft2d;
import java.io.File;
public class BlockGrid {
private Block[][] blocks = new Block[100][100];
public BlockGrid() {
for (int x = 0; x < 25 - 1; x++) {
for (int y = 0; y < 16 - 1; y++) {
blocks[x][y] = new Block(BlockType.AIR, -100, -100); //This is where my error happens! If I don't include this line i get a null pointer. Anything will help. I am really stuck and don't know whats happening
}
}
}
public void setAt(int x, int y, BlockType b) {
blocks[x][y] = new Block(b, x * 32, y * 32);
}
public void draw() {
for (int x = 0; x < 25 - 1; x++) {
for (int y = 0; y < 16 - 1; y++) {
blocks[x][y].draw();
}
}
}
}
The reason you get a NullPointerException when you don't have that line is that blocks[x][y] will be null for all x,y when draw() is called. draw() assumes you have valid Block objects because it's calling Block#draw.

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