getting nullPointerException on simple game - java

I am making a simple rpg game and i have been trying to add enemies to the game. It is loading in the enemy find with all it's stats, but when i try to render it, i get Exception in thread "Thread-2" java.lang.NullPointerException
at com.hosfordryan.tileRPG.entities.Enemy.render(Enemy.java:52)
at com.hosfordryan.tileRPG.Game.render(Game.java:134)
at com.hosfordryan.tileRPG.Game.run(Game.java:103)
at java.lang.Thread.run(Unknown Source)
. I have used JOptionPanes to confirm that the enemies are saving in the arrayList, so that can't be it. Code for reading in enemy is:
public static void loadEnemies() {
Scanner qwe;
try {
qwe = new Scanner(new File("enemyStats.txt"));
while (qwe.hasNextLine()) {
String name = qwe.nextLine();
String origin = qwe.nextLine();
String weapon = qwe.nextLine();
String gear = qwe.nextLine();
String spec = qwe.nextLine();
int hp = qwe.nextInt();
int att = qwe.nextInt();
int def = qwe.nextInt();
int randX = (int) (Math.random()*(20*SCALE*TILESIZE)); //Give random x coordinate
int randY = (int) (Math.random()*(20*SCALE*TILESIZE)); //Give random y coordinate
if(qwe.hasNextLine()){
qwe.nextLine();
}
enemies.add(new Enemy(randX,randY,im,name,origin,weapon,gear,spec,hp,att,def)); //adds enemy into arrayList
String temp = "";
temp+=enemies.get(enemies.size()-1).getName()+"\n"+enemies.get(enemies.size()-1).getRx(); //checking if saving into arrayList correctly
JOptionPane.showMessageDialog(null, temp);
}
for(int i = 0; i < enemies.size();i++){ //adds enemy to arrayList to be rendered
enemiestoRend.add( new Enemy(enemies.get(i).getRx(),enemies.get(i).getRy(),im,enemies.get(i).getName(),enemies.get(i).getOrigin(),enemies.get(i).getWeapon(),enemies.get(i).getGear(),enemies.get(i).getSpecialMove(),enemies.get(i).gethp()
,enemies.get(i).getAttack(),enemies.get(i).getDefense()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Code for rendering:
public void render(Graphics g){
g.drawImage(im.enemy, this.x*Game.TILESIZE * Game.SCALE, this.x*Game.TILESIZE * Game.SCALE, Game.TILESIZE * Game.SCALE,
Game.TILESIZE * Game.SCALE, null);
}
Render method in main which renders everything:
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if (bs==null) {
createBufferStrategy(3);
return;
}
Graphics g= bs.getDrawGraphics();
//Render Here
else if(Player.l1){
l1.render(g);
}
for(int i = 0; i < enemies.size();i++){
enemies.get(i).render(g);
}
for(int i = 0; i < enemiestoRend.size();i++){
enemiestoRend.get(i).render(g); //problem here
}
player.render(g);
//End Render
g.dispose();
bs.show();
}

Related

How to pick specific parts of a Shape3D shape (processing)

I am attempting to make a voxel-ish world builder, and I need to be able to stack the different blocks. How can I pick the separate sides of the block with the shapes3d library. Whenever I pick the shape, it renders it as the entire shape, and I am unsure of how to select only the part that I would like, so that I can build upon it.
import peasy.*;
import shapes3d.*;
import shapes3d.utils.*;
Shape3D picked = null;
boolean clicked = true;
PeasyCam cam;
float[] xArr,yArr,zArr;
float x,y,z;
Box[] boxArr;
color[] colArr;
CameraState defaultState;
void setup(){
size(1200,800,P3D);
cam = new PeasyCam(this,width/2,height/2,0,500);
cam.setMinimumDistance(200);
cam.setMaximumDistance(2000);
cam.setWheelScale(.05);
cam.setDistance(1000);
cam.rotateZ(PI/4);
cam.rotateX(-PI/3);
cam.setResetOnDoubleClick(false);
defaultState = cam.getState();
x=width/2;
y=height/2;
z=0;
xArr = new float[200];
yArr = new float[200];
zArr = new float[200];
colArr = new color[200];
boxArr= new Box[200];
for(int i=0;i<boxArr.length;i++){
boxArr[i]=null;
}
xArr[0]=x;
yArr[0]=y;
zArr[0]=z;
boxArr[0]=new Box(this);
colArr[0]=color(255,255,255);
}
final float xrot=-PI/8,yrot=PI/4,zrot=0;
color col = color(255,255,255);
void mouseClicked(){
clicked=true;
}
void draw(){
pushMatrix();
if (keyPressed&&key=='r'){
cam.setState(defaultState);
cam.setDistance(1000);
}
background(213, 243, 245);
ambientLight(200,200,200);
fill(col);
lights();
directionalLight(100,100,100,50,-50,0);
int actuallength=0;
for (int i=0;i<boxArr.length;i++){
if(boxArr[i]!=null){
actuallength++;
}
}
for(int i = 0; i<actuallength; i++){
boxArr[i].fill(colArr[i]);
boxArr[i].strokeWeight(1.75);
boxArr[i].stroke(155);
boxArr[i].moveTo(xArr[i],yArr[i],zArr[i]);
boxArr[i].drawMode(Shape3D.SOLID|Shape3D.WIRE);
boxArr[i].draw();
}
if (clicked){
clicked=false;
picked = Shape3D.pickShape(this, mouseX, mouseY);
int pos=0;
for(int i=0;i<boxArr.length;i++){
if(boxArr[i]==picked){
pos=i;
}
}
if(picked!=null){
println();
boxArr[actuallength]=new Box(this);
xArr[actuallength]=xArr[pos]+(100);
yArr[actuallength]=yArr[pos];
zArr[actuallength]=zArr[pos];
colArr[actuallength]=color(255,255,255);
}
}
popMatrix();
}

Part of Graphics disappears when sent to printer

I am trying to print a table to a piece of paper in a custom style, but only the column headers are printed on the page when I send it to the printer.
When using the same code to print to a JPanel, it works just fine.
I have been debugging like a madman, but all I've found is that a different Graphics is used when writing to a printer, and that it calculates the widths of the strings slightly differently, somehow, though I can't see how that should have an impact on what gets written or not.
I have been able to confirm that all the code is run, though.
The code that draws the headers:
private void drawColumnHeaders(Graphics2D g, PageFormat pf)
{
g.drawLine(columnWidths[0]-1, 0, columnWidths[0]-1, rowHeight);
drawText(g, 1, columnHeader[1]);
drawLineAround(g, 1);
drawText(g, 2, columnHeader[2]);
drawLineAround(g, 2);
etc...
...
g.translate(0, rowHeight);
}
The code that draws the rows:
private void drawRow(Graphics2D g, Konto konto, boolean kunAfstanden)
{
...
drawAccountNo(g, konto, 1);
etc...
...
g.translate(0, rowHeight);
}
...
private void drawAccountNo(Graphics2D g, Account account, int columnNo)
{
switch (account.getType())
{
case SUMACCOUNT:
drawLineBeneath(g, columnNo);
default:
drawText(g, columnNo, "" + account.getAccountNo());
break;
}
}
Utility methods:
private void drawText(Graphics2D g, int columnNo, String text)
{
int startX = calculatePosition(columnNo);
g.drawString(text, startX + lMargin, g.getFontMetrics().getAscent() + aMargin);
}
private void drawLineAround(Graphics2D g, int columnNo)
{
int startX = calculatePosition(columnNo);
drawLineBeneath(g, columnNo);
g.drawLine(startX + columnWidths[columnNo], 0, startX + columnWidths[columnNo], rowHeight);
}
...
private int calculatePosition(int columnNo)
{
int result = 0;
for (int i = 0; i < columnNo; i++)
{
result+= columnWidths[i];
}
return result;
}
Any help is appreciated.
Edit:
The code that controls the printing:
#Override
public int print(Graphics ga, PageFormat pf, int pageIndex) throws PrinterException
{
ga.setFont(normalFont);
Graphics2D g = (Graphics2D) ga;
if (!writeToPrinter)
{
pf = standardPF;
}
int returnMessage = -1;
int noOfRowsOnPage = 0;
calculateColumnWidths(g, pf);
//Calculates how many pages there will be:
calculateNoOfPages(g, pf);
if (pageIndex < noOfPages)
{
//Translates Graphics:
prepareGraphics(g, pf);
//The parts that do show up:
drawHeader(g, pf);
drawStart(g, pf);
drawColumnHeaders(g, pf);
while (returnMessage == -1)
{
try
{
if (accounts.get(iReached).getType().t() != TypeAccount.NEWPAGE.t() && possibleRows > noOfRowsOnPage)
{
//The part that doesn't (even though the code is reached):
drawRow(g, accounts.get(iReached));
noOfRowsOnPage++;
}
else
{
//If the page isn't empty, go to the next page
if (noOfRowsOnPage > 0)
{
returnMessage = PAGE_EXISTS;
}
}
iReached++;
}
catch (IndexOutOfBoundsException e)
{
returnMessage = PAGE_EXISTS;
}
}
drawFooter(g, pf, false);
}
else
{
returnMessage = NO_SUCH_PAGE;
}
return returnMessage;
}
The initialization of the PageFormat used:
standardPF = new PageFormat();
standardPF.setOrientation(PageFormat.PORTRAIT);
Paper paper = new Paper();
paper.setImageableArea(30, 30, 535, 780);
paper.setSize(595.44, 841.68);
standardPF.setPaper(paper);

Java Object values not consistent

I couldn't find any other solutions to my problem because I'm unsure of how to describe it in few enough words.
When I assign activeList, which is a field of currentActiveList a randomly generated Rectangle in the ActiveList class it receives the value just fine.
public class ActiveList {
Rectangle[] activeList = new Rectangle[10];
public ActiveList() {
for(int i = 0; i < activeList.length; i++)
activeList[i] = null;
}
public void addToList(Rectangle x) {
for(int i = 0; i < this.activeList.length; i++) {
if(this.activeList[i] == null) {
this.activeList[i] = x;
i = this.activeList.length+1;
}
else
this.activeList[activeList.length-1] = x;
}
}
public Rectangle[] getActiveList() {
return this.activeList;
}
public int getLength() {
//System.out.print(this.activeList.length);
return this.activeList.length;
}
public void deleteFromList(int x) {
this.activeList[x] = null;
}
public Rectangle getFromList(int x) {
Rectangle retVal = this.activeList[x];
//System.out.println("Returning getFromList(int x): " +retVal);
return retVal;
}
public void genRandomRectangle() {
Random randomNumberGenerator = new Random();
double[] pointVal = new double[4];
double randomInt = randomNumberGenerator.nextInt(400-10);
pointVal[0] = randomInt;
randomInt = randomNumberGenerator.nextInt(400-10);
pointVal[1] = randomInt;
randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[0]));
if(randomInt < 5) {
randomInt = randomInt+pointVal[0]+5;
}
else
pointVal[2] = randomInt+pointVal[0];
randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[1]));
if(randomInt < 5) {
randomInt = randomInt+pointVal[1]+5;
}
else
pointVal[3] = randomInt+pointVal[1];
Rectangle newRandom = new Rectangle(pointVal[0], pointVal[1], pointVal[2], pointVal[3]);
//System.out.println(pointVal[0]);
//System.out.println(pointVal[1]);
//System.out.println(pointVal[2]);
//System.out.println(pointVal[3]);
System.out.println("New Random: " +newRandom);
addToList(newRandom);
}
}
However, when I try to use those values in my main class GraphicGen, the currentActiveList returns null values for all of its indexes.
public class GraphicGen extends JPanel {
ActiveList currentActiveList = new ActiveList();
public static int gridSpaceX = 400;
public static int gridSpaceY = 400;
static JFrame mainFrame = new JFrame();
protected void paintComponent(Graphics g) {
//super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//int w = getWidth();
//int h = getHeight();
// Draw ordinate.
//g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
// Draw abcissa.
//g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
//double xInc = (double)(w - 2*PAD)/(data.length-1);
//double scale = (double)(h - 2*PAD)/maxValue();
// Mark data points.
//g2.setPaint(Color.red);
double[] coords = new double[4];
//g2.fill(new Ellipse2D.Double(coords[0], coords[1], 4, 4));
//g2.fill(new Ellipse2D.Double(coords[2], coords[3], 4, 4));
//g2.fill(new Ellipse2D.Double(100, 100, 4, 4));
System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
System.out.println("Ya drew a new Main GUI!");
System.out.println("currentActiveList.getActiveList(): " +currentActiveList.getActiveList());
for(int i = 0; i < currentActiveList.getLength(); i++) {
//System.out.println("currentActiveList.getFromList(i): "+currentActiveList.getFromList(i));
//System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
//System.out.println(activeList.getFromList(i).getTopLeftX());
if(currentActiveList.getFromList(i) != null) {
coords[0] = currentActiveList.getFromList(i).getTopLeftX();
System.out.println(coords[0]);
coords[1] = currentActiveList.getFromList(i).getTopLeftY();
System.out.println(coords[1]);
coords[2] = currentActiveList.getFromList(i).getBottomRightX();
System.out.println(coords[2]);
coords[3] = currentActiveList.getFromList(i).getBottomRightY();
System.out.println(coords[3]);
g2.draw(new Line2D.Double(coords[0], coords[1], coords[2], coords[1]));
g2.draw(new Line2D.Double(coords[0], coords[1], coords[0], coords[3]));
g2.draw(new Line2D.Double(coords[2], coords[1], coords[2], coords[3]));
g2.draw(new Line2D.Double(coords[0], coords[3], coords[2], coords[3]));
}
}
/*double x = 50;
double y = 50;
g2.fill(new Ellipse2D.Double(x, y, 4, 4));*/
/*for(int i = 0; i < data.length; i++) {
double x = PAD + i*xInc;
double y = h - PAD - scale*data[i];
g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
}*/
}
/*private int maxValue() {
int max = data[0];
for(int i = 0; i < data.length; i++) {
if(data[i] > max)
max = data[i];
}
return max;
}*/
public void callRepaintOnMain() {
mainFrame.repaint();
}
public void callGenRandom() {
currentActiveList.genRandomRectangle();
}
public static void main(String[] args) {
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new GraphicGen());
mainFrame.setSize(gridSpaceX, gridSpaceY);
ButtonPrompt buttonPrompter = new ButtonPrompt();
mainFrame.setLocation(200,200);
mainFrame.setVisible(true);
}
}
The random generator method is called by the action listener.
public class ButtonPrompt extends GraphicGen {
ActionListener actionListenerRandom = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//currentActiveList.genRandomRectangle();
callGenRandom();
callRepaintOnMain();
}
};
JButton randomBtn = new JButton("Add Random Rectangle");
JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
public ButtonPrompt() {
JFrame f = new JFrame("Add Rectangles");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout boxLayout = new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS);
f.setLayout(boxLayout);
randomBtn.addActionListener(actionListenerRandom);
f.setSize(200, 200);
f.setLocation(600, 200);
f.setVisible(true);
f.add(randomBtn);
f.add(inputCoordinates);
f.pack();
}
}
Is this a scoping or referencing problem? I'm really at a loss here.
Here:
public static void main(String[] args) {
...
mainFrame.add(new GraphicGen());
...
ButtonPrompt buttonPrompter = new ButtonPrompt();
}
ButtonPrompt extends GraphicGen, which is a JPanel. In ButtonPrompt's constructor, you created a JFrame and added two JButtons to it.
So when your app starts, there will be two JFrames on the screen, one is mainFrame which contains a GraphicGen, the other is buttonPrompter which contains two buttons.
When you click on the button, the actionPerformed() is called and it's actually calling the callGenRandom() of the buttonPrompter -- if the random generation logic is correct, the generated Rectangles are added to buttonPrompter. But you didn't add this buttonPrompter to any one of the JFrames, you won't see it.
What you may want:
ButtonPrompt doesn't extend GraphicGen, instead, give ButtonPrompt a reference of the GraphicGen you added to the mainFrame.
public class ButtonPrompt extends GraphicGen {
JButton randomBtn = new JButton("Add Random Rectangle");
JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
final GraphicGen gg;
public ButtonPrompt(GraphicGen gg) {
this.gg = gg;
......
ActionListener actionListenerRandom = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
gg.callGenRandom();
gg.callRepaintOnMain();
}
};
randomBtn.addActionListener(actionListenerRandom);
......
}
}
and in your main():
public static void main(String[] args) {
...
GraphicGen gg = new GraphicGen();
mainFrame.add(gg);
...
ButtonPrompt buttonPrompter = new ButtonPrompt(gg);
}
What's more, the code has other problems.
For example, GraphicGen is a JPanel, main class and it has a field of a JFrame which actually contains the GraphicGen instance when app runs -- this looks bad. I don't know much of Swing... Is it a must to call the containing JFrame's repaint() instead of just calling the JPanel's repaint(), if it has?
Your actual problem is quite unclear, but just reading the first two methods is enough to find what, I suppose, is a bug:
public ActiveList() {
for(int i = 0; i < activeList.length; i++)
activeList[i] = null;
}
the above code is completely useless. The default value of an element of an array of objects is null. So the loop assigns null to a variable wich is already null.
public void addToList(Rectangle x) {
for(int i = 0; i < this.activeList.length; i++) {
if(this.activeList[i] == null) {
this.activeList[i] = x;
i = this.activeList.length+1;
}
else
this.activeList[activeList.length-1] = x;
}
}
If your list only contains null, the rectangle will be stored at index 0, and the loop will stop. For all the susequent calls to this method, the loop will find that the element at index 0 is not null, and will thus store x at the last index of the array, and then at the first non-null index.
I don't know exactly what you're trying to achieve, and what the actual problem is, but you should probably forget about implementing your own list based on an array, and use an ArrayList instead.

Java 2d game finding correct enemy for fighting

I am making a simple 2d game in java and i am trying to get fighting to work. I am going to do pokemon-style fighting, so what i am doing is when i press the spacebar, it checks if i am colliding with an enemy, finds that enemy in an arrayList, and then executes the fight method using that enemy. This works most of the time, but sometimes it can't seem to find the enemy in the ArrayList. My code for checking this is:
if (space) {
for (Rectangle collideable : Enemy.ens) {
if (intersects(playerR, collideable)) {
System.out.println("Colliding with Enemy!");
x = locx;
y = locy;
playerR.setLocation(x, y);
for (int i = 0; i < Game.enemies.size(); i++) {
if (Enemy.ens.get(i).equals(collideable)) {
System.out.println("Can't find enemy to fight");
System.out.println(Game.enemies.get(i).getName());
fightQuestion(Game.enemies.get(i), i);
break;
}
}
break;
}
}
}
Enemy.ens is created when i render each enemy. Game.enemies is created when I read in all of the enemy stats, and then i add each enemy to that ArrayList. For every enemy i try to fight, it is getting to the point where it prints out that it is colliding, but not always to the fight part. Any ideas as to why this is happening would be fantastic!
EDIT
Code for when Game.Enemies is filled:
public static void loadEnemies() {
im = getImageManager();
Scanner qwe;
try {
qwe = new Scanner(new File("enemyStats.txt"));
while (qwe.hasNextLine()) {
String name = qwe.nextLine();
String origin = qwe.nextLine();
String weapon = qwe.nextLine();
String gear = qwe.nextLine();
String spec = qwe.nextLine();
int hp = qwe.nextInt();
int att = qwe.nextInt();
int def = qwe.nextInt();
int randX = (int) (Math.random()*(18*SCALE*TILESIZE)); //Give random x coordinate
int randY = (int) (Math.random()*(18*SCALE*TILESIZE)); //Give random y coordinate
if(qwe.hasNextLine()){
qwe.nextLine();
}
enemies.add(new Enemy(randX,randY,im,name,origin,weapon,gear,spec,hp,att,def)); //adds enemy into arrayList
int randI = (int) (Math.random()*enemies.size());
for(int i = 0; i < 4;i++){ //adds enemy to arrayList to be rendered
enemiestoRend.add(enemies.get(randI) );
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Why do you execute the statement:
System.out.println("Can't find enemy to fight");
for each iteration in the second loop, regardless of checking a condition first? And why does the second loop check:
i < Game.enemies.size();
instead of:
i < Enemy.ens.size();

Java: Moving arrays to different methods in regards to text

I need help tweaking my code. I need to write a program that outputs the count of individual ascii characters in a txt file that the user uploads, but I'm having a lot of problems trying to get the array that I count into the GUI portion of the program that "draws" the data on the screen.
I have the output looking how I want, but I can't figure out how to get the character count up there
I want to put the number of times a character/punction/number is used in a file that the user uploads on a graphic display. For instance, 33 or ! there are 3 instances. Or 65 A there are 4354 instances in the file. However I'm having a large problem with getting the counter to count the characters in the word correctly, and even more trouble getting the stored array of numbers of characters to the GUI (g.draw) section of the program.
Instead of a number, I just get a blank output column.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileReader; // both needed
import java.io.BufferedReader;
import java.io.IOException;
public class textreader extends Frame implements ActionListener
{
String dataFilePath = null;
String dataFileName = null;
int[] counter = new int[256];
String command = "";
public static void main(String[] args)
{
Frame frame = new textreader();
frame.setResizable(true);
frame.setSize(1000,850);
frame.setVisible(true);
}
public textreader()
{
setTitle("Text File Processing");
// Menu Creation
MenuBar mn = new MenuBar();
setMenuBar(mn);
// Create "File" and add it
Menu fileMenu = new Menu("File");
mn.add(fileMenu);
// Create Menu Items, Add action Listener, Add to "File" Menu Group
// Open file
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
fileMenu.add(miOpen);
// Process file
MenuItem miProcess = new MenuItem("Process");
miProcess.addActionListener(this);
fileMenu.add(miProcess);
// Exit program
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
fileMenu.add(miExit);
// To Terminate
WindowListener d = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// listener registry
this.addWindowListener(d);
this.addComponentListener(k);
}
public void actionPerformed (ActionEvent ev)
{
// which command was issued?
command = ev.getActionCommand();
// act
if("Open".equals(command))
{
dataFilePath = null;
dataFileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
dataFilePath = chooser.getSelectedFile().getPath();
dataFileName = chooser.getSelectedFile().getName();
}
repaint();
}
else
if("Process".equals(command))
{
try
{
// Initialize
int[] aCount = new int[256];
// "Instantiate" streams
BufferedReader inputStream = new BufferedReader(new FileReader(dataFilePath));
// read the file line by line and count the characters read
String line = null;
char c = 0;
int lineLength = 0;
int charValue = 0;
while ((line = inputStream.readLine()) != null)
{
// ********* process line
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (ch >= 0 && ch <= 255)
{
counter[(int)ch]++;
}
else
{ // silently ignore non-ASCII characters
}
// count newline at the end
counter['\n']++;
}
}
}
catch(IOException ioe)
{
System.out.print("You want to run that by me again?");
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
}
//********************************************************
//called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (dataFileName != null)
{
g.drawString("File -- "+dataFileName+" -- was successfully opened", 400, 400);
}
else
{
g.drawString("NO File is Open", 400, 400);
}
return;
}
else
if("Process".equals(command))
{
for(int i = 0; i < 256; i++)
{
int x = 100;
int y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 30;
int line = 0;
for(int j = 0; j < 256; j++)
{
line++;
g.drawString(Integer.toString(j), x, y);
g.drawString(Character.toString((char)j), x + 50, y);
// Converts the # to a char, then to a String
// This part of the code adds a new column when the flag reaches 43
if(line == 45)
{
x = x + 150;
y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 15;
line = 0;
}
y = y+15;
}
}
return;
}
}
}
just add this to your code:
g.drawString(Integer.toString(counter[j]), x + 120, y);
right here (int the paint method):
g.drawString(Integer.toString(j), x, y);
g.drawString(Character.toString((char)j), x + 50, y);
g.drawString(Integer.toString(counter[j]), x + 120, y);

Categories

Resources