2D arrays in Java not changing properly - java

In a Game Of Life project that I'm working on, I have a 2D array of bytes. The array represents a gameboard. The problem is that when I try to access the array, it returns all zeroes. But, in the function where I set a cell, changes save just fine.
Here's the class:
public class Game {
int boardW;
int boardH;
Board board;
public Game(int bW) {
boardW = bW;
boardH = bW;
this.board = new Board(boardH, boardW);
}
private byte updateCell(int x, int y) {
byte neighbors = 0;
// Loop through 8 neighbors and count them
for (byte offset_y = -1; offset_y < 2; offset_y++) {
for (byte offset_x = -1; offset_x < 2; offset_x++) {
// Make sure we don't check our current cell
if (offset_x != 0 || offset_y != 0) {
byte newY = (byte) (y + offset_y);
byte newX = (byte) (x + offset_x);
// Roll over edge of board
if (y + offset_y < 0) {
newY = (byte) (boardH - 1);
}
else if (y + offset_y >= boardH) {
newY = 0;
}
if (x + offset_x < 0) {
newX = (byte) (boardW - 1);
}
if (x + offset_x >= boardW) {
newX = 0;
}
neighbors += this.board.getState(newX, newY);
}
}
}
if (neighbors < 2) {return 0;}
if (neighbors > 3) {return 0;}
if (neighbors == 3) {return 1;}
return this.board.getState(x, y);
}
public Board gameTick() {
Board nextTick = new Board(boardH, boardW);
// Go through next iteration of cells
for (int h = 0; h < boardH; h++) {
for (int w = 0; w < boardW; w++) {
nextTick.setState(w, h, updateCell(w, h));
}
}
return nextTick;
}
public Board getBoard() {
return this.board;
}
public void toggleCell(int x, int y, byte state) {
this.board.setState(x, y, state);
}
}
class Board {
private final byte[][] board;
final int height;
final int width;
public Board(int h, int w) {
width = w;
height = h;
board = new byte[height][width];
}
public void setState(int x, int y, byte state) {
board[y][x] = state;
}
public byte getState(int x, int y) {
return board[y][x];
}
public byte[][] getData() {
return board;
}
public void setData(byte[][] newBoard) {
for (int x = 0; x<newBoard.length; x++) {
for (int y = 0; y<newBoard.length; y++) {
setState(x, y, newBoard[y][x]);
}
}
}
}
What is going on here?
EDIT: Turns out it was another problem in the code that accessed the board, which I solved. Thanks for all your help guys.

Change the design of your code completely. Have a wrapper class Board which encapsulates (and hides) the two-dimensional array (if it must be an array at all) inside.
public class Board {
private final byte[][] board;
public Board(int height, int width) {
board = new byte[height][width];
}
public void setState(int x, int y, byte state) {
board[y][x] = state;
}
public byte getState(int x, int y) {
return board[y][x];
}
}
Then create an instance of the Board class and access the state only via that one.
Thus you will have safe access to your data and your design is open for modifications in the future. You are e.g. free to start adding useful methods such as
boolean isRowEmpty(int x)
boolean isColumnEmpty(int y)
void resetRow(int x)
void resetColumn(int y)
void reset()
All of them will be nicely called on an instance of the Board class. You will not access the array directly from your business logic code, which is a nasty practice.

I would suggest that you make two different classes one main
and other for calling the function, In this from main class
pass the value you want , and call the method you want this will
surely solve the problem.

Try this:
public class YourClassName {
byte[][] board;
// Setters
public void setCell(int x, int y, byte state) {
System.out.println(board[y][x]);
board[y][x] = state;
}
// Getters
public byte[][] getBoard() {
return board;
}
}

This appears to be a scoping issue, so the solution is to make sure that board is defined in a scope that all your methods have access to. The cleanest way to do this is to define board as a class field (i.e. it is defined outside of any method), and then every time you want to modify or access board, you use this.board.
For example,
public class Board{
private byte[][] board;
public Board(int height, int width){
this.board = new byte[height][width];
}
public byte[][] getBoard(){
return this.board;
}
public void setCell(int x, int y, byte state){
System.out.println(this.board[y][x]);
this.board[y][x] = state;
}
}

Related

RGBimage array and creating ppm file

This is part of university task
I'm given a class named RGBColor without private access(but with info on what each method/constructor does)
the object is (r,g,b): r for red, g for green, b for blue, each of them represent a number between 0-255
I need to write a new class named RBGImage based on RBGColor, and the class object is a two-dimensional array storing RGBColor objects.
My struggle is to create a ppm file in order to check the program and I have no idea how to do it. This is what I did so far:
public class RGBImage
{
RGBColor[][] _image;
public RGBImage(int rows , int cols){
_image=new RGBColor[rows][cols];
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
_image[i][j]=new RGBColor(_image[i][j]);
}
public RGBImage(RGBColor[][] pixels) {
int hight=pixels.length;
int width=pixels[0].length;
_image=new RGBColor[hight][width];
for(int i=0;i<hight;i++)
for(int j=0;j<width;j++)
_image[i][j] = new RGBColor(pixels[i][j]);
;
}
public RGBImage(RGBImage other)
{
_image = other._image;
}
public int getHeight()
{
int hight = _image.length;
return hight;
}
public int getWidth() {
int width = _image[0].length;
return width;
}
public RGBColor getPixel(int row,int col)
{
int _red = _image[row][col].getRed();
int _green = _image[row][col].getGreen();
int _blue = _image[row][col].getBlue();
return new RGBColor(_red,_green,_blue);
}
public void setPixel(int row,int col,RGBColor pixel)
{
int _red = pixel.getRed();
int _green = pixel.getGreen();
int _blue = pixel.getBlue();
// set if to do nothing
if(row <= _image.length && col <= _image[0].length)
_image[row][col].setRed(_red);
_image[row][col].setGreen(_green);
_image[row][col].setBlue(_blue);
}
public double[][] toGrayscaleArray() {
int width = _image[0].length;
int hight = _image.length;
double[][] grayScale = new double[hight][width];
for(int i=0;i<hight;i++)
for(int j=0;j<width;j++)
grayScale[i][j]=_image[i][j].convertToGrayscale();
return grayScale;
}
public boolean equals (RGBImage other)
{
if(_image == other._image)
return true;
return false;
}
Sorry I couldn't provide any documentation

Printing and comparing array data in java

I recently started learning Java and I'm having some trouble understanding how to make arrays to work the way I want them to.
Here I have an assignment of creating a polygon class with different methods inside.
Basically the class represents a convex polygon in a plane.
The array receives user input that consists of x and y coordinates and places them inside. (max number of vertices is 10).
There are some functions that I have no idea how to do and I would really appreciate some help with.
Point Class - which is used to get coordinates
public class Point {
private double _x;
private double _y;
public Point() {
this._x = 0.0D;
this._y = 0.0D;
}
public Point(double x, double y) {
this._x = x;
this._y = y;
}
public Point(Point other) {
this._x = other._x;
this._y = other._y;
}
public double getX() {
return this._x;
}
public double getY() {
return this._y;
}
public void setX(double x) {
if (x >= 0.0D)
this._x = x;
}
public void setY(double y) {
if (y >= 0.0D)
this._y = y;
}
public boolean isAbove(Point other) {
return (this._y > other._y);
}
public boolean isUnder(Point other) {
return other.isAbove(this);
}
public boolean isLeft(Point other) {
return (this._x < other._x);
}
public boolean isRight(Point other) {
return other.isLeft(this);
}
public double distance(Point other) {
double distance = Math.sqrt(Math.pow(this._x - other._x, 2.0D) + Math.pow(this._y - other._y, 2.0D));
return distance;
}
public void move(double dx, double dy) {
double x = this._x + dx;
double y = this._y + dy;
if (x >= 0.0D && y >= 0.0D) {
this._x = x;
this._y = y;
}
}
public boolean equals(Point other) {
return (this._x == other._x && this._y == other._y);
}
public String toString() {
return "(" + this._x + "," + this._y + ")";
}
}
Polygon Class - main class im working on
/**
* Write a description of class Polygon here.
*
* #author [REDACTED]
* #version (Ver 1.0)
*/
public class Polygon {
private Point[] _vertices;
private int _noOfVertices;
public Polygon() {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
}
public Polygon(Point[] arr) {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
if (arr.length > 10) {
return;
}
// for (Point P : arr)
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
_vertices[i] = arr[i];
_noOfVertices++;
}
}
}
public boolean addVertex(double x, double y) {
if (_noOfVertices >= 10)
return false;
Point p = new Point(x, y);
_vertices[_noOfVertices] = p;
_noOfVertices++;
return true;
}
public Point highestVertex() {
for (int i = 0; i < _noOfVertices; i++) {
}
}
public String toString() {
}
public double calcPerimeter() {
for (int i = 0; i < arr.length; i++) {
}
}
public double caclArea() {
Point ppp = _vertices[zzz]
}
public boolean isBigger(Polygon other) {
}
public int findVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
return i;
}
}
return -1;
}
public Point getNextVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
if (i == _noOfVertices - 1) {
return new Point(_vertices[0]);
}
return new Point(_vertices[i + 1]);
}
}
return null;
}
public Polygon getBoundingBox() {
}
}
I have no idea how to do these functions:
Line 44: public Point highestVertex() {} - returns a copy of the highest point in the polygon. If there is more than one vertice at the same Y - the method will return the first one it encountered (with the said Y) If there are no vertices aka the array is empty it will return null.
Line 52: public String toString() {} - method that returns a string of points representing the polygon. The string should be in the following format:
The polygon has 5 vertices:
((2.0,1.0),(5.0,0.0),(7.0,5.0),(4.0,6.0),(1.0,4,0))
If there are no vertices the method will return a string in the following format:
The polygon has 0 vertices.
English is not my first language so I apologize for any grammar mistakes in advance.
First, it's not really the best to ask homework questions here, this is a concept that you should learn.
In highestVertex(), they outline the 3 cases for you:
1st case: If point-y is equal to another point-y, return the first vertex that has point-y.
2nd case: if arr has no elements return null.
3rd case: in loop, check each element's y value in the array and compare it to the biggest y so far.
Use this line before your loop:
int max = Integer.MIN_VALUE;
Inside loop:
if (arr[i] > max) max = arr[i]
For toString(), again loop throughout the array, and add each point to a tracker string that you will return.
String str = "";
loop
str += arr[i].toString() + ",";
This works except you need to loop until arr's second to last element, as you will have an extraneous comma after the last point.

Rectangle overlapping in Java

I'm trying to make a random map generator. It should create a random sized rooms at random coordinates, and remove the room it it overlaps with other rooms. However, the overlap checking isn't working. Here are the relevant parts of code:
public static void generateMap() {
rooms[0] = new Room(0,10,10,5); // For some reason doesn't work without this?
for (int i=0;i<ROOMS;i++) {
int x = randomWithRange(0,WIDTH);
int y = randomWithRange(0,HEIGHT);
int height = randomWithRange(MINROOMSIZE,MAXROOMSIZE);
int width = randomWithRange(MINROOMSIZE,MAXROOMSIZE);
while (x+width > WIDTH) {
x--;
}
while (y+height > HEIGHT) {
y--;
}
Room room = new Room(x,y,width,height);
if (room.overlaps(rooms) == false) {
rooms[i] = room;
}
}
}
And then the Room class:
import java.awt.*;
public class Room {
int x;
int y;
int height;
int width;
public Room(int rx, int ry, int rwidth, int rheight) {
x = rx;
y = ry;
height = rheight;
width = rwidth;
}
boolean overlaps(Room[] roomlist) {
boolean overlap = true;
Rectangle r1 = new Rectangle(x,y,width,height);
if (roomlist != null) {
for (int i=0;i<roomlist.length;i++) {
if (roomlist[i] != null) {
Rectangle r2 = new Rectangle(roomlist[i].x,roomlist[i].y,roomlist[i].width,roomlist[i].height);
if (!r2.intersects(r1) && !r1.intersects(r2)) {
overlap = false;
}
else {
overlap = true;
}
}
}
}
return overlap;
}
}
So I've been testing this, and it removes a few rooms each time, but there's always some that are overlapping depending on the number of rooms of course. There must be some stupid easy solution I just can't see right now... Also, why doesn't it generate any rooms unless I manually add the first one? Thanks
Your problem is this part of overlaps function:
overlap = false;
What is happening in your code is that you keep checking rooms if they overlap or not, but if you find one which overlaps, you keep going. And then when you find a room which does not overlap, you reset the flag. Effectively the code is equivalent with just checking the last room.
Remove the overlap flag completely. Instead of overlap = true; statement put return true; (because at this point we know that at least one room is overlapping). Don't do anything when you find out that the room is not overlapping with other room (in the for cycle). At the end, after the for cycle just return false; Fact that code execution got to that point means there is no overlapping room (otherwise it would have just returned already)
Note: I believe that condition !r2.intersects(r1) && !r1.intersects(r2) is redundant. .intersects(r) should be commutative, meaning that that r1.intersects(r2) and r2.intersects(r1) give the same results.
For your first issue where you have initialized first room, you don't have to do that.
rooms[0] = new Room(0,10,10,5); // For some reason doesn't work without this?
You just need to check for first room and no need to check for overlap as it is the first room.
For the second issue, you can return true at the first time you find an intersect otherwise return false at the end of the loop.
Code for your reference.
class Room {
int x;
int y;
int height;
int width;
public Room(int rx, int ry, int rwidth, int rheight) {
x = rx;
y = ry;
height = rheight;
width = rwidth;
}
boolean overlaps(Room[] roomlist) {
Rectangle r1 = new Rectangle(x, y, width, height);
if (roomlist != null) {
for (int i = 0; i < roomlist.length; i++) {
if (roomlist[i] != null) {
Rectangle r2 = new Rectangle(roomlist[i].x, roomlist[i].y, roomlist[i].width, roomlist[i].height);
if (r2.intersects(r1)) {
return true;
}
}
}
}
return false;
}
}
public class RoomGenerator {
private static final int ROOMS = 10;
private static final int WIDTH = 1200;
private static final int HEIGHT = 1000;
private static final int MINROOMSIZE = 10;
private static final int MAXROOMSIZE = 120;
public static void main(String[] args) {
generateMap();
}
public static void generateMap() {
Room rooms[] = new Room[10];
for (int i = 0; i < ROOMS; i++) {
int x = randomWithRange(0, WIDTH);
int y = randomWithRange(0, HEIGHT);
int height = randomWithRange(MINROOMSIZE, MAXROOMSIZE);
int width = randomWithRange(MINROOMSIZE, MAXROOMSIZE);
while (x + width > WIDTH) {
x--;
}
while (y + height > HEIGHT) {
y--;
}
Room room = new Room(x, y, width, height);
if( i ==0)
{
rooms[0] = room;
}else if (room.overlaps(rooms) == false) {
rooms[i] = room;
}
}
}
private static int randomWithRange(int min, int max) {
// TODO Auto-generated method stub
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
}

Why does this Java grid not function correctly?

I am trying to make a grid (with minimal code) that blocks can snap to. What I want is when the mouse is in the grid square, the block moves to that square. What I have written essentially says that if the X or Y are beyond the grid block times the size of the block, move to the next grid block. Currently, this code creates a 3x3 grid, though the code SHOULD generate infinite gridspaces. I cannot move the block outside of this 3x3 grid.
public class Player extends Entity {
public Player(double entSize, boolean collideA, boolean collideB, double x, double y) {
super(entSize, collideA, collideB, x, y);
}
public void init() {
Texture texFile = loadTexture("stone");
texture(false, true);
texFile.bind();
render();
}
void input() {
int gridPosX = 1;
int gridPosY = 1;
if(getX() > gridPosX*entSize) {
gridPosX += 1;
} if(getX() < gridPosX*entSize) {
gridPosX -= 1;
} if(getY() > gridPosY*entSize) {
gridPosY += 1;
} if(getY() < gridPosY*entSize) {
gridPosY -= 1;
}
this.x = gridPosX*entSize;
this.y = gridPosY*entSize;
}
}
The X and Y values are what define the blocks position and shape parameters.
Fixed by using for loops for the positive grid increments!
NEW CODE:
public class Player extends Entity {
public Player(double entSize, boolean collideA, boolean collideB, double x, double y) {
super(entSize, collideA, collideB, x, y);
}
public void init() {
Texture texFile = loadTexture("stone");
texture(false, true);
texFile.bind();
render();
}
void input() {
int gridPosX = 0;
int gridPosY = 0;
for(gridPosX = 0; getX() > gridPosX*entSize; gridPosX++) {
gridPosX += 0;
} if(getX() < gridPosX*entSize) {
gridPosX -= 1;
} for(gridPosY = 0; getY() > gridPosY*entSize; gridPosY++) {
gridPosY += 0;
} if(getY() < gridPosY*entSize) {
gridPosY -= 1;
}
this.x = gridPosX*entSize;
this.y = gridPosY*entSize;
}
}

Exception in thread "main" java.lang.NullPointerException on developing games in java

I'm trying make fonts for a game but whenever I load it I get this error:
Exception in thread "main" java.lang.NullPointerException
at image.ImageFont.load(ImageFont.java:78)
at image.ImageFont.<init>(ImageFont.java:47)
at image.ImageFontTest.init(ImageFontTest.java:26)
at image.GameCore.run(GameCore.java:65)
at image.ImageFontTest.main(ImageFontTest.java:11)
I also have the files for it:
ImageFontTest
public class ImageFontTest extends GameCore {
public static void main(String[] args) {
new ImageFontTest().run();
}
private static final long TOTAL_TIME = 6500;
private ImageFont bigFont;
private ImageFont medFont;
private long remainingTime;
private CharMovement[] charMovement;
public void init() {
super.init();
remainingTime = TOTAL_TIME;
// load image fonts
bigFont = new ImageFont("fonts/big");
medFont = new ImageFont("fonts/medium");
String message = "Good Times!";
int stringWidth = medFont.stringWidth(message);
charMovement = new CharMovement[message.length()];
for (int i=0; i<message.length(); i++) {
charMovement[i] = new CharMovement(message, i,
(screen.getWidth() - stringWidth) / 2,
screen.getHeight() / 2);
}
}
public void update(long elapsedTime) {
remainingTime -= elapsedTime;
if (remainingTime <= 0) {
stop();
}
}
public void draw(Graphics2D g) {
// erase background
g.setColor(Color.BLACK);
g.fillRect(0,0,screen.getWidth(), screen.getHeight());
// draw some aligned text
medFont.drawString(g, "Left", 0, 0,
ImageFont.LEFT | ImageFont.TOP);
medFont.drawString(g, "Center", screen.getWidth()/2, 0,
ImageFont.HCENTER | ImageFont.TOP);
medFont.drawString(g, "Right", screen.getWidth(), 0,
ImageFont.RIGHT | ImageFont.TOP);
// draw seconds remaining
String timeLeft = "" + (remainingTime / 1000);
bigFont.drawString(g, timeLeft, 0, screen.getHeight());
// draw moving characters
double p = (double)(TOTAL_TIME - remainingTime) / TOTAL_TIME;
for (int i=0; i<charMovement.length; i++) {
charMovement[i].draw(g, p);
}
}
/**
Simple animation class to animate a character along a
path.
*/
public class CharMovement {
char ch;
Point[] path;
public CharMovement(String s, int charIndex, int x, int y) {
int stringWidth = medFont.stringWidth(s);
for (int i=0; i<charIndex; i++) {
x+=medFont.charWidth(s.charAt(i));
}
ch = s.charAt(charIndex);
path = new Point[4];
// start offscreen
path[0] = new Point(x-2000, y);
// move to the center of the screen and pause there
path[1] = new Point(x, y);
path[2] = path[1];
// "explode" at a random angle far away
double angle = Math.random() * 2 * Math.PI;
double distance = 1000 + 1000*Math.random();
path[3] = new Point(
(int)Math.round(x + Math.cos(angle) * distance),
(int)Math.round(y + Math.sin(angle) * distance));
}
/**
Draws this character in the path, where p is the
location in the path from 0 to 1.
*/
public void draw(Graphics g, double p) {
int points = path.length - 1;
int index = (int)(p*points);
p = p * points - index;
Point start = path[index % path.length];
Point goal = path[(index + 1) % path.length];
int x = (int)Math.round(goal.x * p + start.x * (1-p));
int y = (int)Math.round(goal.y * p + start.y * (1-p));
medFont.drawChar(g, ch, x, y);
}
}
}
ImageFont
/**
The ImageFont class allows loading and drawing of text
using images for the characters.
Reads all the png images in a directory in the form
"charXX.png" where "XX" is a decimal unicode value.
Characters can have different widths and heights.
*/
public class ImageFont {
public static final int HCENTER = 1;
public static final int VCENTER = 2;
public static final int LEFT = 4;
public static final int RIGHT = 8;
public static final int TOP = 16;
public static final int BOTTOM = 32;
private char firstChar;
private Image[] characters;
private Image invalidCharacter;
/**
Creates a new ImageFont with no characters.
*/
public ImageFont() {
this(null);
firstChar = 0;
characters = new Image[0];
}
/**
Creates a new ImageFont and loads character images from
the specified path.
*/
public ImageFont(String path) {
if (path != null) {
load(path);
}
// make the character used for invalid characters
invalidCharacter =
new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
Graphics g = invalidCharacter.getGraphics();
g.setColor(Color.RED);
g.fillRect(0,0,10,10);
g.dispose();
}
/**
Loads the image files for each character from the
specified path. For example, if "../fonts/large"
is the path, this method searches for all the images
names "charXX.png" in that path, where "XX" is a
decimal unicode value. Not every character image needs
to exist; you can only do numbers or uppercase letters,
for example.
*/
public void load(String path) throws NumberFormatException {
// in this directory:
// load every png file that starts with 'char'
File dir = new File(path);
File[] files = dir.listFiles();
// find min and max chars
char minChar = Character.MAX_VALUE;
char maxChar = Character.MIN_VALUE;
for (int i=0; i<files.length; i++) {
int unicodeValue = getUnicodeValue(files[i]);
if (unicodeValue != -1) {
minChar = (char)Math.min(minChar, unicodeValue);
maxChar = (char)Math.max(maxChar, unicodeValue);
}
}
// load the images
if (minChar < maxChar) {
firstChar = minChar;
characters = new Image[maxChar - minChar + 1];
for (int i=0; i<files.length; i++) {
int unicodeValue = getUnicodeValue(files[i]);
if (unicodeValue != -1) {
int index = unicodeValue - firstChar;
characters[index] = new ImageIcon(
files[i].getAbsolutePath()).getImage();
}
}
}
}
private int getUnicodeValue(File file)
throws NumberFormatException
{
String name = file.getName().toLowerCase();
if (name.startsWith("char") && name.endsWith(".png")) {
String unicodeString =
name.substring(4, name.length() - 4);
return Integer.parseInt(unicodeString);
}
return -1;
}
/**
Gets the image for a specific character. If no image for
the character exists, a special "invalid" character image
is returned.
*/
public Image getImage(char ch) {
int index = ch - firstChar;
if (index < 0 || index >= characters.length ||
characters[index] == null)
{
return invalidCharacter;
}
else {
return characters[index];
}
}
/**
Gets the string width, in pixels, for the specified string.
*/
public int stringWidth(String s) {
int width = 0;
for (int i=0; i<s.length(); i++) {
width += charWidth(s.charAt(i));
}
return width;
}
/**
Gets the char width, in pixels, for the specified char.
*/
public int charWidth(char ch) {
return getImage(ch).getWidth(null);
}
/**
Gets the char height, in pixels, for the specified char.
*/
public int charHeight(char ch) {
return getImage(ch).getHeight(null);
}
/**
Draws the specified string at the (x, y) location.
*/
public void drawString(Graphics g, String s, int x, int y) {
drawString(g, s, x, y, LEFT | BOTTOM);
}
/**
Draws the specified string at the (x, y) location.
*/
public void drawString(Graphics g, String s, int x, int y,
int anchor)
{
if ((anchor & HCENTER) != 0) {
x-=stringWidth(s) / 2;
}
else if ((anchor & RIGHT) != 0) {
x-=stringWidth(s);
}
// clear horizontal flags for char drawing
anchor &= ~HCENTER;
anchor &= ~RIGHT;
// draw the characters
for (int i=0; i<s.length(); i++) {
drawChar(g, s.charAt(i), x, y, anchor);
x+=charWidth(s.charAt(i));
}
}
/**
Draws the specified character at the (x, y) location.
*/
public void drawChar(Graphics g, char ch, int x, int y) {
drawChar(g, ch, x, y, LEFT | BOTTOM);
}
/**
Draws the specified character at the (x, y) location.
*/
public void drawChar(Graphics g, char ch, int x, int y,
int anchor)
{
if ((anchor & HCENTER) != 0) {
x-=charWidth(ch) / 2;
}
else if ((anchor & RIGHT) != 0) {
x-=charWidth(ch);
}
if ((anchor & VCENTER) != 0) {
y-=charHeight(ch) / 2;
}
else if ((anchor & BOTTOM) != 0) {
y-=charHeight(ch);
}
g.drawImage(getImage(ch), x, y, null);
}
}
I see it says the problem is at load in ImageFont but I dont know how to fix it.
Exception in thread "main" java.lang.NullPointerException
at image.ImageFont.load(ImageFont.java:78)
You have a NPE (Null Pointer Exception): this means that you have used a variable or an object which has not been initialized yet.
Example:
Button b;
b.setText("Text in my button"); // NULL POINTER EXCEPTION: b is a button but which button?!?
Solution
Button b = new Button();
b.setText("Text in my button"); // b now is a brand new button and it can be used.
You sir have this kind of problem :)

Categories