I'm trying to build a pyramid in Java using GRect. I use getWidth() to position the pyramid in the center of the canvas but it tends to trip the left part of pyramid.
I'm learning programming through CS106A and using Java 1.6 so tried to get some other peoples code and they too showed the same bug. I tried to draw a simple rect and it works fine.
Is it some issue with Java applet as it tends to ignore getWidth() value at all. I used println(); to get getWidth() value and it works.
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
public class Pyramid extends GraphicsProgram {
/**
* eclipse generated SVUID
*/
private static final long serialVersionUID = 5703830460071233096L;
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Width of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
private static final int BRICKS_IN_BASE = 14;
public void run() {
//centering the pyramid
int _canvasWidth = getWidth(); //canvas width
//println(_canvasWidth); //to check if getWidth returns a value
int _brickSpace = BRICKS_IN_BASE * BRICK_WIDTH; //space consumed by the base row
int _freeSpace = _canvasWidth - _brickSpace; //empty base level space
int _xOffset = _freeSpace / 2; //x for left most brick of base row
for(int row=0; row<BRICKS_IN_BASE; row++){ //the row number
int _rowTab = (BRICK_WIDTH/2) * row; //indentaion for each row
int _brickInRow = BRICKS_IN_BASE - row; //bricks as per row
for(int _brickNumber=0; _brickNumber<_brickInRow; _brickNumber++){ //placing bricks till _brickInRow
int x = (_xOffset + _rowTab) + (_brickNumber * BRICK_WIDTH);
int y = (BRICK_HEIGHT * (BRICKS_IN_BASE - row)); //y as per row num
GRect _brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT); //creating brick instance
add(_brick);
}
}
}
}
I tried your code and it draws the pyramid at the centre at first, but the problem comes up when I resize the viewer window.
The point is Java applets have an inherited method called public void paint(Graphics g) that is called whenever the applet has to be painted. Resizing the viewer window is one of the cases that makes the paint method called.
So, to fix this you need to override the paint method, ie. add such a method:
public void paint(Graphics g) {
this.run();
super.paint(g);
}
This method will be called every time the window is resized. But remember you don't need multiple pyramids so add following line to your run method to remove all the previous bricks before adding the new ones.
removeAll();
Related
I am trying to teach myself more about graphics in Java. To do this I'm trying to build a chess game. I've hit my first roadblock at making the board. My thought here is that I would have a extension of JComponent called "Square" that would be my container for both the color of the board square and the piece on that square (if any). To start with I haven't attempted to include any representation of the piece yet, just the square colors. Later on I hope to have an abstract "Pieces" class that is extended by multiple subclasses representing all the different types of pieces, and add those to each Square as applicable.
When I execute the following, I only get one black square in the upper left hand corner.
ChessBoardTest.java
public class ChessBoardTest {
public static void main(String[] args) {
ChessBoard Board = new ChessBoard();
Board.Display();
}
}
ChessBoard.java
public class ChessBoard extends JFrame {
public static final int FRAME_WIDTH = 500;
public static final int FRAME_HEIGHT = 500;
// Declare instance variables
private Square[][] square = new Square[rows][cols];
private final static int rows = 8;
private final static int cols = 8;
public ChessBoard() {
}
public void Display() {
JPanel Board_Layout = new JPanel();
Board_Layout.setLayout(new GridLayout(8,8));
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if((i+j) % 2 == 0) {
square[i][j] = new Square(1);
Board_Layout.add(square[i][j]);
} else {
square[i][j] = new Square(0);
Board_Layout.add(square[i][j]);
}
}
}
setTitle("Chess Mod");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(Board_Layout);
setVisible(true);
}
public void messageBox(String pMessage) {
JOptionPane.showMessageDialog(this, pMessage, "Message", JOptionPane.PLAIN_MESSAGE);
}
}
Square.java
public class Square extends JComponent {
private int color;
public Square(int c) {
this.color=c;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.color == 1) {
g.setColor(new Color(0,0,0));
} else {
g.setColor(new Color(255,255,255));
}
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
}
}
I only get one black square in the upper left hand corner.
That's mainly because of the following call:
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
getX() returns the horizontal pixel offset/location of the Component which is invoked upon, relative to the Container that contains that Component. getY() accordingly returns the vertical pixel offset/location of the Component which is invoked upon, relative to the Container that contains the Component.
getWidth() and getHeight() return the size of the Component.
So imagine that the Component at row with index 2 and column with index 3, will have its coordinates at about x == 3 * w / 8 and y == 2 * h / 8 where w and h is the size (width and height respectively) of the parent Container (ie the Board_Layout panel). Let's assume that Board_Layout has a size of 300x300 when you show the graphical user interface... This means that the Square at the location I mentioned will only paint the region which starts at x == 112 and y == 75 and expands at one 8th of the width (and height) of Board_Layout (because there are 8 rows and 8 columns in the grid). But the size of the Square itself is also at one 8th of the width (and height) of Board_Layout, ie about 37x37. So the painted region which starts and expands from the location 112,75 will not be shown at all (because it lies completely outside the Square's size).
Only the top left Square will have some paint on it because its bounds in the parent happen to intersect the drawn region.
To fix this, the location given at the Graphics object should be relative to each Square and not its parent Board_Layout. For example:
g.fillRect(0, 0, getWidth(), getHeight());
I am attempting to draw a checkerboard pattern in java using nested for loops, but I am having trouble doing it with two different colors. I know this question has been asked before, but it hasn't been asked with two different colors on the board that are not just using a background color. I plan on using the individual squares as an array to hold checker positions, so I do need each individual square made. Would it be better to drop the ice of a nested for loop to create each square, or should i stick with that shortcut? And if I were to stick with it, how would the nested loop be formatted (one for each color)?
When creating checker tiles, I would pass in an int for the x coordinate, and y coordinate such as:
import java.awt.Color;
import java.awt.Graphics;
public class CheckerTile {
public static final int WIDTH = 100; //width of each tile
public static final int HEIGHT = 100; //height of each tile, most likely same as width so its a square
public static int currentId = 0; //variable to reference unique id for each tile
private int id; //current id of tile
private int x; //x coordinate
private int y; //y coordinate
private int width; //width of tile
private int height; //height of tile
//Default constructor to take x and y coordinate
public CheckerTile( int x, int y ) {
this.id = currentId++;
this.x = x;
this.y = y;
width = WIDTH;
height = HEIGHT;
}
public int getId()
{
return id;
}
//draws the tile on the panel.
public void draw(Graphics g)
{
//if the checkerTile's id is divisible by 2, draw it red, otherwise draw it black.
g.setColor( id % 2 == 0 ? Color.RED : Color.black);
g.fillRect(x, y, width, height);
}
}
That way we have a way to draw the tile on the board. Now, when creating each object, we increment a currentId variable so that we can color each one individually using the modulus operator later.
I am assuming you are using Swing so I decided to add a draw(Graphics g) method so when repainting in java it would use that Graphics object. If you are using a different library, then you will have to do some research in to how to draw it on the board.
Now in your JPanel, it would look something like this:
//Creates the JPanel, which needs to be added to JFrame object in main
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CheckerBoard extends JPanel {
CheckerTile[][] checkerTiles; //2-dimension array of checkerTiles
public CheckerBoard() {
super();
this.setSize(800,800);
checkerTiles = new CheckerTile[9][9];
//This creates the checkerTiles.
for(int i = 0; i < 9; i++)
{
for( int j = 0; j < 9; j++)
{
checkerTiles[i][j] = new CheckerTile( j * CheckerTile.WIDTH, i * CheckerTile.HEIGHT );
}
}
this.setVisible(true);
//Repaint right away to show results.
repaint();
}
//We need to override this to paint the tiles on the board.
#Override
public void paintComponent(Graphics g)
{
for(int i = 0; i < checkerTiles.length; i++)
{
for(int j = 0; j < checkerTiles[i].length; j++)
{
//call the draw method on each tile.
checkerTiles[i][j].draw(g);
}
}
}
//A demo of adding the panel to a frame and showing the tiles.
public static void main(String[] args)
{
//Create the JFrame and add the CheckerBoard we made to it.
JFrame frame = new JFrame();
frame.setSize(800,800);
frame.setLayout(new BorderLayout());
frame.add(new CheckerBoard(), BorderLayout.CENTER);
frame.setVisible(true);
}
}
I'm a noob programmer, and I'm working on a little project that involves a 2D grid of 1000 x 1000 boolean values that change based on an instruction pattern. "After x instructions, how many values in the grid are true?" That kind of thing.
I want to put a little spin on it and render the values as a grid of pixels which are black if their corresponding values are false and white if they're true and that animates in real time as instructions are processed, but I'm pretty lost -- I've never dabbled with 2D graphics in Java. I've read through Oracle's tutorial, which helped, but the way I'm doing things is sufficiently different from its demo that I still feel lost.
My most immediate problem is that I can't even seem to initialize a grid of 1000 x 1000 black pixels using a BufferedImage. Running my code yields a very tiny window with nothing (grayness) in it. Can anyone tell me what I'm doing wrong and suggest how to proceed? My code follows:
import java.awt.image.BufferedImage;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PixelGrid extends JPanel {
private BufferedImage grid;
// Ctor initializing a grid of binary (black or white) pixels
public PixelGrid(int width, int height) {
grid = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
}
/**
* Fill an area with a given color
* #param color 0 for black; 1 for white
* #param x1 Starting x coordinate
* #param y1 Starting y coordinate
* #param x2 Ending x coordinate
* #param y2 Ending y coordinate
*/
public void toggleBlock(int color, int x1, int y1, int x2, int y2) {
if (color == 0) {
color = Color.BLACK.getRGB();
}
else {
color = Color.WHITE.getRGB();
}
for (int x = x1; x <= x2; x++) {
for (int y = y1; y <= y2; y++) {
grid.setRGB(x, y, color);
}
}
}
// Clear the grid (set all pixels to black)
public void clear() {
toggleBlock(0, 0, 0, grid.getWidth() - 1, grid.getHeight() - 1);
}
public static void main(String[] args) {
int width = 1000;
int height = 1000;
PixelGrid aGrid = new PixelGrid(width, height);
JFrame window = new JFrame("A Wild Pixel Grid Appears!");
window.add(aGrid); // Incorporates the pixel grid into the window
window.pack(); // Resizes the window to fit its content
window.setVisible(true); // Makes the window visible
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Note that it doesn't yet deal at all with an actual 2D array of booleans or instruction processing; I'm pretty sure I can handle that on my own, but, for now, I'm just trying to understand how to set up the graphical component.
Your code creates a BufferedImage, but then doesn't do anything with it (graphically). A few options:
Option 1: Override paintComponent of the PixelGrid class and draw the image to the JPanel
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(grid, 0, 0, this);
}
Option 2: Use a JLabel and ImageIcon
JLabel label = new JLabel(new ImageIcon(grid));
add(label);
In either case, you will have to call repaint on the Component every time the BufferedImage is changed
//some code
grid.setRGB(x, y, color);
//some more code
repaint();//or label.repaint() if Option 2
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.....
This is not a homework problem. I am only going over a freely available course from Stanford. I am using Ubuntu Linux with Eclipse.
Problem and Question:
I am drawing rectangles by calling add() on a acm.program.GraphicsProgram object. I am drawing certain number of rectangles which have a certain fixed width. However I am seeing that my rectangles are flowing off the visible area. I have tried setting a big enough width and height for both the GraphicsProgram object and the GCanvas object but still my rectangles are falling off the visible area. I always get the same height for GraphicsProgram object no matter what height I set. Any pointers as to what am I doing wrong?
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class Pyramid extends GraphicsProgram {
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Width of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
private static final int BRICKS_IN_BASE = 14;
public void run() {
setWindowSize();
this.createPyramid();
}
private void createPyramid()
{
int centerX = findCenter();
int startingX = centerX - (BRICKS_IN_BASE / 2) * BRICK_WIDTH;
int startingY = BRICK_HEIGHT;
for(int numBricks = BRICKS_IN_BASE; numBricks>= 1; numBricks--)
{
this.layBricks(startingX,startingY , numBricks);
startingX = startingX + BRICK_WIDTH / 2;
startingY = (BRICKS_IN_BASE - numBricks + 2) * BRICK_HEIGHT;
}
}
private void layBricks(int x, int y, int numOfBricks)
{
for(int i = 0; i < numOfBricks; i++)
{
add(new GRect(x,y,this.BRICK_WIDTH, this.BRICK_HEIGHT));
x+=this.BRICK_WIDTH;
}
}
private void setWindowSize()
{
int width = BRICK_WIDTH * BRICKS_IN_BASE * 2;
int height = BRICKS_IN_BASE * BRICK_HEIGHT * 2;
this.setSize(width, height);
//this.setForeground(Color.GREEN);
//this.setBackground(Color.BLUE);
//this.getGCanvas().setBounds(0, 0, width, height);
//this.getGCanvas().add(new GRect(0,0,300,30));
//this.getGCanvas().setBackground(Color.WHITE);
System.out.println(this.getHeight());
System.out.println(this.getWidth());
System.out.println(this.getGCanvas().getHeight());
System.out.println(this.getGCanvas().getWidth());
}
private int findCenter()
{
return this.getWidth() / 2;
}
}
I'm working through the same Stanford course online and ran into the same problem. The setSize method would resize the display but not the values returned by getWidth and getHeight.
You can change the width and height by going to Project > Properties > Run/Debug Settings > Edit > Parameters tab.
I assume there is something more direct or code-based, but this is an easy solution.
Start by not hard coding the brick sizes like this
int brick_width = (getWidth() / BRICKS_IN_BASE) - (getWidth() / 50);
int brick_height = (brick_width / 3);
That way your pyramid will always be drawn within whatever the screen size happens to be.
It should also be centered, once your brick sizes are relative to window size, guaranteeing that the bricks will always be centered becomes easier. The only wrench I have found are weird
window sizes such as 50 x 500, but that doesn't happen too often.
Here is a look at my solution
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class Pyramid1 extends GraphicsProgram {
public void run(){
int brick_width = (getWidth() / BRICKS_IN_BASE) - (getWidth() / 50);
int brick_height = (brick_width / 3);
for(int n = 0; n < BRICKS_IN_BASE; n++ ){
//make a row at level n of bricks that is BRICKS_IN_BASE - n bricks wide.
int bricks_in_level = BRICKS_IN_BASE - n;
int x = ((getWidth() / 2) - ((bricks_in_level * brick_width) / 2)); //find the center then offset to farthest left.
int y = (((getHeight() / 2) + ((BRICKS_IN_BASE / 2) * brick_height )) - ((n + 1) * brick_height)); //start at the 1/2 and move down half max stack height and move up a brick each round.
GRect brick = new GRect(x, y, brick_width, brick_height);
brick.setFilled(true);
brick.setFillColor(Color.RED);
add(brick);
if(bricks_in_level > 1){ //If there are 2 or more bricks needed in this level
for(int needed_bricks = bricks_in_level - 1; needed_bricks > 0; needed_bricks -= 1){
x += brick_width;
GRect needed_brick = new GRect(x, y, brick_width, brick_height);
needed_brick.setFilled(true);
needed_brick.setFillColor(Color.RED);
add(needed_brick);
}
}
}
}
private static final int BRICKS_IN_BASE = 12;
}
The main problem was that I was using open-java-jdk and not sun-java-jdk. After changing the jre my Applet is behaving in a more predictable way.