I am learning how to use Java and I want to make a text scroller for my website.
I have found a similar scroller that I want to add but I want to look at the code to see how it was done.
The applet can be found here: http://www.javascriptkit.com/java/java20.shtml
The problem is when I try to open the class file within notepad the encoding or text shows up with strange characters instead of showing me the code.
Please can someone let me know if there is any possible way of me seeing the code for this class.
Thanks
That is a class file meaning it is compiled code so you can not see it's source.
In order to see the source, you need the .java file which is the file which you compile to get the byte code.
It seems the site is just providing the compiled class, and you never know using it they might have some hidden functionality in the class as well e.g to send information to the owner servers etc.
EDIT:
So here is the de-compiled code of applet written by ProScroll version 2.3 by Slava Pestov
import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
public class ProScroll extends Applet
implements Runnable
{
private Thread thread;
private Image image;
private int scrollLength;
private int scrolled;
private int speed = 10;
private int imgsWidth;
private URL url;
private String target;
private Color bgColor;
public void init()
{
int i = 12; int j = 0;
String str2 = getParameter("TEXT");
String str3 = getParameter("TEXTURL");
if ((str2 == null) && (str3 == null)) {
str2 = "No TEXT or TEXTURL parameter specified";
}
if (str3 != null)
{
localObject = new StringBuffer();
try
{
InputStream localInputStream = new URL(str3)
.openConnection().getInputStream();
while (true)
{
int k = localInputStream.read();
if (k == -1) break;
if (k != 10) {
if (k == 9) { ((StringBuffer)localObject).append(' '); continue; }
((StringBuffer)localObject).append((char)k);
}
}
localInputStream.close();
str2 = ((StringBuffer)localObject).toString();
}
catch (Exception localException1)
{
if (str2 == null) {
str2 = "Error loading text from URL: " + localException1;
}
}
}
String str1 = getParameter("FONT");
if (str1 == null) str1 = "TimesRoman";
this.target = getParameter("TARGET");
if (this.target == null) this.target = "_self";
try
{
i = Integer.parseInt(getParameter("SIZE"));
}
catch (Exception localException2)
{
}
Object localObject = getParameter("STYLE");
if ("bold".equals(localObject)) j = 1;
else if ("italic".equals(localObject)) j = 2;
else if ("bolditalic".equals(localObject)) j = 3;
String str4 = getParameter("SPEED");
if ("slow".equals(str4)) this.speed = 20;
else if ("medium".equals(str4)) this.speed = 15; else {
this.speed = 10;
}
try
{
this.url = new URL(getDocumentBase(), getParameter("URL"));
}
catch (Exception localException3)
{
}
this.bgColor = parseColorName(getParameter("BGCOLOR"), Color.black);
Enumeration localEnumeration = parseAndLoadImages(getParameter("IMAGES"));
Font localFont = new Font(str1, j, i);
FontMetrics localFontMetrics = getToolkit().getFontMetrics(localFont);
this.image = createImage(localFontMetrics.stringWidth(str2) + this.imgsWidth + size().width, size().height);
this.scrolled = (-size().width);
parseAndDrawText(this.image.getGraphics(), str2, localFontMetrics, localFont, localEnumeration);
}
private void parseAndDrawText(Graphics paramGraphics, String paramString, FontMetrics paramFontMetrics, Font paramFont, Enumeration paramEnumeration)
{
paramGraphics.setFont(paramFont);
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, this.image.getWidth(this), this.image.getHeight(this));
paramGraphics.setColor(Color.white);
StringBuffer localStringBuffer = new StringBuffer();
int i = 0; int j = 0;
for (int k = 0; k < paramString.length(); k++)
{
char c = paramString.charAt(k);
if ((c == '#') && (j == 0))
{
if (i != 0)
{
paramGraphics.setColor(parseColorName(localStringBuffer.toString(), Color.white));
localStringBuffer.setLength(0);
i = 0;
}
else
{
i = 1;
}
}
else if ((c == '$') && (i == 0) && (j == 0))
{
try
{
Image localImage = (Image)paramEnumeration.nextElement();
paramGraphics.drawImage(localImage, this.scrollLength, 0, this);
this.scrollLength += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
else if ((c == '/') && (j == 0))
{
j = 1;
}
else if (i != 0)
{
localStringBuffer.append(c);
}
else
{
if (j == 1) j = 0;
paramGraphics.drawString(String.valueOf(c), this.scrollLength, paramFontMetrics.getAscent());
this.scrollLength += paramFontMetrics.charWidth(c);
}
}
}
private Color parseColorName(String paramString, Color paramColor)
{
if ("red".equals(paramString)) return Color.red;
if ("green".equals(paramString)) return Color.green;
if ("blue".equals(paramString)) return Color.blue;
if ("yellow".equals(paramString)) return Color.yellow;
if ("orange".equals(paramString)) return Color.orange;
if ("white".equals(paramString)) return Color.white;
if ("lightGray".equals(paramString)) return Color.lightGray;
if ("gray".equals(paramString)) return Color.gray;
if ("darkGray".equals(paramString)) return Color.darkGray;
if ("black".equals(paramString)) return Color.black;
if ("cyan".equals(paramString)) return Color.cyan;
if ("magenta".equals(paramString)) return Color.magenta;
if ("pink".equals(paramString)) return Color.pink;
return paramColor;
}
private Enumeration parseAndLoadImages(String paramString)
{
if (paramString == null) return null;
int i = 0;
Vector localVector = new Vector();
StringTokenizer localStringTokenizer = new StringTokenizer(paramString);
MediaTracker localMediaTracker = new MediaTracker(this);
while (localStringTokenizer.hasMoreTokens())
{
try
{
Image localImage = getImage(new URL(getDocumentBase(), localStringTokenizer.nextToken()));
localVector.addElement(localImage);
localMediaTracker.addImage(localImage, i);
localMediaTracker.waitForID(i++);
this.imgsWidth += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
return localVector.elements();
}
public void start()
{
this.thread = new Thread(this);
this.thread.start();
}
public void stop()
{
this.thread = null;
this.scrolled = (-size().width);
}
public void run()
{
while (Thread.currentThread() == this.thread)
{
long l = System.currentTimeMillis();
if (++this.scrolled > this.scrollLength) this.scrolled = (-size().width);
repaint();
try
{
Thread.sleep(Math.max(this.speed - (System.currentTimeMillis() - l), 0L));
}
catch (InterruptedException localInterruptedException)
{
}
}
}
public boolean mouseEnter(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("Link: " + this.url.toString());
return true;
}
public boolean mouseExit(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("");
return true;
}
public boolean mouseUp(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showDocument(this.url, this.target);
return true;
}
public void update(Graphics paramGraphics)
{
paramGraphics.setColor(this.bgColor);
if (this.scrolled < 0)
{
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, -this.scrolled, size().height);
}
paramGraphics.drawImage(this.image, -this.scrolled, 0, this);
}
public void paint(Graphics paramGraphics)
{
update(paramGraphics);
}
public String getAppletInfo()
{
return "ProScroll version 2.3 by Slava Pestov";
}
}
a java .class file is a compiled file that you cannot read with notepad.
if you want the source code you should try to ask it to the author of the article or you could decompile it.
Related
Im supposed to create a Snake game using a Queue in Java.
I'm supposed to only use the three classes down below, however I do not know how I should modify my move() function in order to move the snake, since it is a Queue and I cannot access the tail of the snake.
I came up with the following:
Snake.java
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Snake extends JFrame implements Runnable, KeyListener {
int length=40, width = 30;
int time;
int factor=10;
Specialqueue q;
int direction = 6;
Thread t;
int[][] food;
private boolean started;
public Snake() {
super("Snake");
setSize(length*factor+30, width*factor+60);
setVisible(true);
addKeyListener(this);
started = false;
time = 0;
}
public void paint(Graphics g){
if (g == null) return;
g.clearRect(0,0,getWidth(),getHeight());
if (!gestartet){
g.drawString("start the game by pressing 5",10,50);
g.drawString("Controll the snake with W,A,S,D",10,80);
return;
}
g.setColor(Color.blue);
for (int k = 0; k < length; k++)
for (int j = 0; j < breite; j++)
if (food[k][j]==1)
g.fillOval(k*10,20+j*10,10,10);
}
public void run() {
time = 0;
while (started){
try {Thread.sleep(300);}
catch (Exception e){};
move();
time++;
Graphics g = this.getGraphics();
}
}
public void stop() {
started=false;
t = null;
}
public void initFood() {
food = new int[length][breite];
for (int k = 0; k < length; k++) {
for (int j = 0; j < breite; j++) {
if (Math.random() < 0.01) futter[k][j] = 1;
else food[k][j] = 0;
}
}
}
public void initSnake(){
q = new Specialqueue();
direction = 6;
q.append(new Point(20,20));
q.append(new Point(19,20));
q.append(new Point(18,20));
q.append(new Point(17,20));
Graphics g = this.getGraphics();
repaint();
g.setColor(Color.red);
g.fillOval(20*10,20+20*10,10,10);
g.fillOval(19*10,20+20*10,10,10);
g.fillOval(18*10,20+20*10,10,10);
g.fillOval(17*10,20+20*10,10,10);
g.setColor(Color.black);
}
public void move()
{
Graphics g = this.getGraphics();
Point p = (Point)q.tail();
Point newPoint = null;
int size = 4;
if (direction == 6) {
for(int i=0;i<3;i++) {
q.remove();
}
for(int q=0;q<3;q++) {
newPoint = new Point(p.x+1, p.y);
}
if (newPoint.x >= length) {stoppe(); return;}
}
else if (direction == 4) {
newPoint = new Point(p.x-1, p.y);
if (newPoint.x < 0) {stoppe(); return;}
}
else if (direction == 8)
{
newPoint = new Point(p.x, p.y-1);
if (newPoint.y < 0) {stoppe(); return;}
}
else if (direction == 2)
{
newPoint = new Point(p.x, p.y+1);
if (newPoint.y >= width) {stoppe(); return;}
}
q.append(newPoint);
p = (Point)q.tail();
g.setColor(Color.red);
g.fillOval(p.x*10,20+p.y*10,10,10);
if(food[newPoint.x][newPoint.y] == 0){
p = (Point)q.first();
g.setColor(Color.white);
g.fillOval(p.x*10,20+p.y*10,10,10);
q.remove();
}
else {
food[newPoint.x][newPoint.y]=0;
}
}
public void keyPressed(KeyEvent ke)
{
char c = ke.getKeyChar();
if (c=='5' && started) {started = false; t = null; repaint(); return; }
if (c=='5' && !started){
gestartet=true;
initSnake();
initFutter();
t = new Thread(this);
try {Thread.sleep(150);} catch (Exception e){};
t.start();
return;
}
if ((c =='6' || c=='d') && direction != 4) direction = 6;
else if ((c =='2' || c=='s') && direction != 8) direction = 2;
else if ((c =='4' || c=='a') && direction != 6) direction = 4;
else if ((c =='8' || c=='w') && direction != 2) direction = 8;
}
}
SpecialQueue.java
public class Specialqueue <ContentType> {
Queue<ContentType> s;
public Specialqueue()
{
s = new Queue<ContentType>();
}
public ContentType tail(){
if (s.isEmpty()) return null;
return s.front();
}
public boolean isEmpty(){
return s.isEmpty();
}
public void append(ContentType pContent)
{
s.enqueue(pContent);
}
public void remove()
{
if(!s.isEmpty()) {
s.dequeue();
}
}
public ContentType first(){
if (this.isEmpty())
{
return null;
}
else{
return s.front();
}
}
}
**Queue.java**
public class Queue {
protected class QueueNode {
protected ContentType content = null;
protected QueueNode nextNode = null;
public QueueNode(ContentType pContent) {
content = pContent;
nextNode = null;
}
public void setNext(QueueNode pNext) {
nextNode = pNext;
}
public QueueNode getNext() {
return nextNode;
}
public ContentType getContent() {
return content;
}
}
protected QueueNode head;
protected QueueNode tail;
public Queue() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void enqueue(ContentType pContent) {
if (pContent != null) {
QueueNode newNode = new QueueNode(pContent);
if (this.isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.setNext(newNode);
tail = newNode;
}
}
}
public void dequeue() {
if (!this.isEmpty()) {
head = head.getNext();
if (this.isEmpty()) {
head = null;
tail = null;
}
}
}
public ContentType front() {
if (this.isEmpty()) {
return null;
} else {
return head.getContent();
}
}
}
I'm working on an assignment where I have to solve a maze through backtracking (using a stack!) and the logic of the code is basically done, but the main problem is whenever I call pop() on my stack, it does not pop.So for now I have manually added (hardcoded) the parts in the maze where it is supposed to pop(). I am using my own stack that is using Linked Nodes and have ran JUnit and Main tests and it does indeed work (doubting myself here now). I have also used the Java stack and I get the same result.
Here is my code logic: As you can see in the method mazeSolver, at the bottom, I have a few if statements that check if i (operations performed) is at a certain point and it will "backtrack", but I am manually setting the position. The very last else statement is the part where I pop(). Any help would very much be appreciated.
public class MazeSolver {
private char[][] printMaze;
private char[][] solveMaze;
public MazeSolver() {
super();
}
private class Position {
private int x;
private int y;
Position(int y, int x) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
public boolean solve(boolean printUpdates) {
char space = ' ';
Stack<Position> stack = new Stack<Position>();
//Stack stack = new Stack();
Position cp = new Position(1, 0);
boolean done = true;
char c = 'C';
char x = 'X';
int i = 0;
while (done) {
// check right
if (printMaze[cp.getY()][cp.getX() + 1] == space && printMaze[cp.getY()][cp.getX() + 1] != x) {
cp.setX(cp.getX() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check bottom
else if (printMaze[cp.getY() + 1][cp.getX()] == space && printMaze[cp.getY() + 1][cp.getX()] != x
&& printMaze[cp.getY() + 1][cp.getX()] != x) {
cp.setY(cp.getY() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check top
else if (printMaze[cp.getY() - 1][cp.getX()] == space && printMaze[cp.getY() - 1][cp.getX()] != x) {
cp.setY(cp.getY() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check left
else if (printMaze[cp.getY()][cp.getX() - 1] == space && printMaze[cp.getY()][cp.getX() - 1] != x) {
cp.setX(cp.getX() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
//else {
/*
if (i == 6) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(5);
} else if (i == 27) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(20);
}
else if (i == 37) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(2);
cp.setX(18);
}
else if (i == 68) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(13);
cp.setX(22);
} else if (i == 69) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(14);
cp.setX(22);
}
else if (i == 70) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(15);
cp.setX(22);
} else if (i == 71) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(16);
cp.setX(22);
} else if (i == 72) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(17);
cp.setX(22);
} else if (i == 103) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(21);
cp.setX(31);
} */else {
printMaze[cp.getY()][cp.getX()] = 'X';
stack.pop();
cp.setY(((Position) stack.top()).getY());
cp.setX(((Position) stack.top()).getX());
}
//}
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println(stack.top().getX() + ", " + stack.top().getY());
System.out.println(cp.getY() + ", " + cp.getX() + " i = " + i);
printMaze();
}
System.out.println("success");
return false;
}
public void printMaze() {
for (int i = 0; i < printMaze.length; i++) {
for (int j = 0; j < printMaze[i].length; j++) {
System.out.print(printMaze[i][j]);
}
System.out.println("");
}
}
public boolean loadMaze(String filename) {
BufferedReader br = null;
FileReader fr = null;
ArrayList<String> lines = new ArrayList<String>();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
lines.add(line);
}
printMaze = new char[lines.size()][];
solveMaze = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
printMaze[i] = new char[lines.get(i).length()];
solveMaze[i] = new char[lines.get(i).length()];
for (int j = 0; j < lines.get(i).length(); j++) {
solveMaze[i][j] = lines.get(i).charAt(j);
printMaze[i][j] = lines.get(i).charAt(j);
if (solveMaze[i][j] == 'S') {
// hint you need to do this but you do not have the
// instance variable yet
// start = new Position(i, j);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
return false;
}
}
return true;
}
Here is my stack implementation if interested.
public class Stack<Item> implements StackInterface<Item> {
private int size;
private class Link {
private Item data;
public Link next;
public Link(Item data, Link next) {
this.data = data;
this.next = next;
}
public Item getData() {
return data;
}
}
private Link topStackLink = null;
public Stack() {
this.size = 0;
}
#Override
public void push(Item item) {
if (topStackLink == null) {
topStackLink = new Link(item, null);
} else {
topStackLink = new Link(item, topStackLink);
}
this.size++;
}
#Override
public void pop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
topStackLink = topStackLink.next;
this.size--;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item top() {
if (topStackLink != null) {
return topStackLink.data;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item topAndPop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
Item item = topStackLink.data;
pop();
return item;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public boolean isEmpty() {
if (topStackLink == null) {
return true;
} else {
return false;
}
}
#Override
public void makeEmpty() {
// TODO Auto-generated method stub
topStackLink = null;
this.size = 0;
}
#Override
public int size() {
return this.size;
}
i am trying to update a 1.7 class to 1.12.2. i fixed some errors but i dont know how to fix the other errors. if anyone have a suggestion, i would be very very happy...
The Class:
package de.beastsoup.utils.spigot.bo2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import de.beastsoup.utils.spigot.BeastUtils;
import net.minecraft.server.v1_12_R1.TileEntity;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import org.bukkit.scheduler.BukkitRunnable;
public class BO2 {
private Arena arena;
public BO2() {
this.arena = new Arena(this);
}
public Arena getArena() {
return arena;
}
private static HashSet<Location> blocksForUpdate = new HashSet<>();
public void addBlockUpdate(Location location) {
blocksForUpdate.add(location);
}
public void startUpdate() {
new BukkitRunnable() {
#Override
public void run() {
if (!blocksForUpdate.isEmpty()) {
net.minecraft.server.v1_12_R1.World world = ((CraftWorld) Bukkit.getWorlds().get(0)).getHandle();
for (Location location : blocksForUpdate) {
world.notify(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
blocksForUpdate.clear();
}
}
}.runTaskTimer(BeastUtils.getPlugin(BeastUtils.class), 1, 1);
}
/* Spawn BO2 */
public List<Block> spawn(Location location, File file) {
long time = System.currentTimeMillis();
BufferedReader reader;
ArrayList<Block> blocks = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains(",") || !line.contains(":")) {
continue;
}
String[] parts = line.split(":");
String[] coordinates = parts[0].split(",");
String[] blockData = parts[1].split("\\.");
setBlockFast(location.getWorld(), location.getBlockX() + Integer.valueOf(coordinates[0]), location.getBlockY() + Integer.valueOf(coordinates[2]), location.getBlockZ() + Integer.valueOf(coordinates[1]), Integer.valueOf(blockData[0]), blockData.length > 1 ? Byte.valueOf(blockData[1]) : 0);
blocks.add(location.getWorld().getBlockAt(location.getBlockX() + Integer.valueOf(coordinates[0]), location.getBlockY() + Integer.valueOf(coordinates[2]), location.getBlockZ() + Integer.valueOf(coordinates[1])));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("BO2 spawnada em " + (time - System.currentTimeMillis()) + "ms");
return blocks;
}
/* Load BO2 file */
public List<FutureBlock> load(Location location, File file) {
BufferedReader reader;
ArrayList<FutureBlock> blocks = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains(",") || !line.contains(":")) {
continue;
}
String[] parts = line.split(":");
String[] coordinates = parts[0].split(",");
String[] blockData = parts[1].split("\\.");
blocks.add(new FutureBlock(location.clone().add(Integer.valueOf(coordinates[0]), Integer.valueOf(coordinates[2]), Integer.valueOf(coordinates[1])), Integer.valueOf(blockData[0]), blockData.length > 1 ? Byte.valueOf(blockData[1]) : 0));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return blocks;
}
/* Set methods */
public boolean setBlockFast(World world, int x, int y, int z, int blockId, byte data) {
if (y >= 255 || y < 0) {
return false;
}
net.minecraft.server.v1_12_R1.World w = ((CraftWorld) world).getHandle();
net.minecraft.server.v1_12_R1.Chunk chunk = w.getChunkAt(x >> 4, z >> 4);
boolean b = data(chunk, x & 0x0f, y, z & 0x0f, net.minecraft.server.v1_12_R1.Block.getById(blockId), data);
addBlockUpdate(new Location(Bukkit.getWorlds().get(0), x, y, z));
return b;
}
#SuppressWarnings("deprecation")
public boolean setBlockFast(Location location, Material material, byte data) {
return setBlockFast(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), material.getId(), data);
}
private boolean data(net.minecraft.server.v1_12_R1.Chunk that, int i, int j, int k, net.minecraft.server.v1_12_R1.Block block, int l) {
int i1 = k << 4 | i;
if (j >= that.b[i1] - 1) {
that.b[i1] = -999;
}
int j1 = that.heightMap[i1];
net.minecraft.server.v1_12_R1.Block block1 = that.getType(i, j, k);
int k1 = that.getData(i, j, k);
if (block1 == block && k1 == l) {
return false;
} else {
boolean flag = false;
net.minecraft.server.v1_12_R1.ChunkSection chunksection = that.getSections()[j >> 4];
if (chunksection == null) {
if (block == net.minecraft.server.v1_12_R1.Blocks.AIR) {
return false;
}
chunksection = that.getSections()[j >> 4] = new net.minecraft.server.v1_12_R1.ChunkSection(j >> 4 << 4, !that.world.worldProvider.g);
flag = j >= j1;
}
int l1 = that.locX * 16 + i;
int i2 = that.locZ * 16 + k;
if (!that.world.isStatic) {
block1.f(that.world, l1, j, i2, k1);
}
if (!(block1 instanceof IContainer)) {
chunksection.setTypeId(i, j & 15, k, block);
}
if (!that.world.isStatic) {
block1.remove(that.world, l1, j, i2, block1, k1);
} else if (block1 instanceof IContainer && block1 != block) {
that.world.p(l1, j, i2);
}
if (block1 instanceof IContainer) {
chunksection.setTypeId(i, j & 15, k, block);
}
if (chunksection.getTypeId(i, j & 15, k) != block) {
return false;
} else {
chunksection.setData(i, j & 15, k, l);
if (flag) {
that.initLighting();
}
TileEntity tileentity;
if (block1 instanceof IContainer) {
tileentity = that.e(i, j, k);
if (tileentity != null) {
tileentity.u();
}
}
if (!that.world.isStatic && (!that.world.captureBlockStates || (block instanceof net.minecraft.server.v1_7_R4.BlockContainer))) {
block.onPlace(that.world, l1, j, i2);
}
if (block instanceof IContainer) {
if (that.getType(i, j, k) != block) {
return false;
}
tileentity = that.e(i, j, k);
if (tileentity == null) {
tileentity = ((IContainer) block).a(that.world, l);
that.world.setTileEntity(l1, j, i2, tileentity);
}
if (tileentity != null) {
tileentity.u();
}
}
that.n = true;
return true;
}
}
}
/* FutureBlock Utils */
public class FutureBlock {
private Location location;
private int id;
private byte data;
public FutureBlock(Location location, int id, byte data) {
this.location = location;
this.id = id;
this.data = data;
}
public byte getData() {
return data;
}
public Location getLocation() {
return location;
}
public int getId() {
return id;
}
#SuppressWarnings("deprecation")
public void place() {
location.getBlock().setTypeIdAndData(id, data, true);
}
}
}
This Error i need fix now: https://gyazo.com/cb3176c9d879532adddfc5ce1edad2eb , https://gyazo.com/014047f5103fd1eaace121bc121fa8dc , https://gyazo.com/6b546cd147037a9deffad42e3b1ce1ef
if anyone know nms spigot 1.12.2 or something i would be happy
I'm not sure about that third image (I don't see an error in it), and you're going to look at the Spigot docs for specific information on how to fix these, but I can tell you that they're related to vanilla moving from an X,Y,Z position (specified as 3 separate ints) to a BlockPos system (specified as a single class instance containing the 3 ints, along with various helper methods, such as up() and east()).
Both of the first two images/errors are that the method you're calling needs a BlockPos passed and you're giving it three ints.
I don't know where the ints are coming from in the second, and for the first, I don't know what Spigot's Location object is or where those values are coming from and how they're constructed.
But this should give you enough information to resolve these types of errors on your own now.
I'm trying to create a textbox effect for my RPG game, but I keep getting nullpointers because my variables are null, but I'm setting them in a method. I also need to be able to update the variables in the method, which isn't working. That's why the NPE is occurring. Here is my code:
package me.loafayyy.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Timer;
import java.util.TimerTask;
import me.loafayyy.main.RPG;
import me.loafayyy.main.RPGPane;
import me.loafayyy.main.RPGState;
public class GuiManager {
public int opacity = 0;
public int step = 0;
public static boolean transitioning = false;
public static boolean dialogue = false;
public String textlines1;
public String textlines2;
public String textlines3;
public boolean rect = false;
public Timer timer = new Timer();
public void createTransition() {
transitioning = true;
rect = true;
}
public void setOpacity(int op) {
opacity = op;
}
public int getOpacity() {
return opacity;
}
public void createDialogue(String line1, String line2, String line3, int dur) { // my method which I'm setting the variables.
if (!dialogue) {
dialogue = true;
this.textlines1 = line1;
this.textlines2 = line2;
this.textlines3 = line3;
timer.schedule(new TimerTask() {
#Override
public void run() {
dialogue = false;
}
}, dur);
} else {
System.out
.println("ERROR: Could not create dialogue, one is already displaying!");
}
}
public void render(Graphics g) {
for (int i = 0; i < 4; i++) {
if (transitioning) {
rect = false;
if (step == 0) {
if (opacity < 255) {
setOpacity(getOpacity() + 1);
} else if (opacity == 255) {
step = 1;
}
} else if (step == 1) {
if (opacity < 256 && opacity != 0) {
setOpacity(getOpacity() - 1);
} else if (opacity == 0) {
transitioning = false;
step = 0;
}
}
}
}
Graphics2D g2 = (Graphics2D) g.create();
if (transitioning) {
if (RPG.state == RPGState.MAIN) {
RPGPane.main.render(g);
} else if (RPG.state == RPGState.PAUSED) {
RPGPane.paused.render(g);
} else if (RPG.state == RPGState.INGAME) {
RPGPane.ingame.render(g);
}
g2.setColor(new Color(0, 0, 0, getOpacity()));
g2.fillRect(0, 0, RPG.getWidth(), RPG.getHeight());
}
if (RPG.state == RPGState.INGAME) {
if (dialogue) {
g2.drawString(textlines1, 300, 300); // <--- null right here
// do other textlines
}
}
}
}
New code:
package me.loafayyy.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Timer;
import java.util.TimerTask;
import me.loafayyy.main.RPG;
import me.loafayyy.main.RPGPane;
import me.loafayyy.main.RPGState;
public class GuiManager {
public int opacity = 0;
public int step = 0;
public static boolean transitioning = false;
public static boolean dialogue = false;
public String textlines1;
public String textlines2;
public String textlines3;
public boolean rect = false;
public Timer timer = new Timer();
public GuiManager () {
textlines1 = "";
}
public void createTransition() {
transitioning = true;
rect = true;
}
public void setOpacity(int op) {
opacity = op;
}
public int getOpacity() {
return opacity;
}
public void render(Graphics g) {
for (int i = 0; i < 4; i++) {
if (transitioning) {
rect = false;
if (step == 0) {
if (opacity < 255) {
setOpacity(getOpacity() + 1);
} else if (opacity == 255) {
step = 1;
}
} else if (step == 1) {
if (opacity < 256 && opacity != 0) {
setOpacity(getOpacity() - 1);
} else if (opacity == 0) {
transitioning = false;
step = 0;
}
}
}
}
Graphics2D g2 = (Graphics2D) g.create();
if (transitioning) {
if (RPG.state == RPGState.MAIN) {
RPGPane.main.render(g);
} else if (RPG.state == RPGState.PAUSED) {
RPGPane.paused.render(g);
} else if (RPG.state == RPGState.INGAME) {
RPGPane.ingame.render(g);
}
g2.setColor(new Color(0, 0, 0, getOpacity()));
g2.fillRect(0, 0, RPG.getWidth(), RPG.getHeight());
}
if (RPG.state == RPGState.INGAME) {
if (dialogue) {
g2.drawString(textlines1, 300, 300);
// do other textlines
}
}
}
public void createDialogue(String line1, String line2, String line3, int dur) {
if (!dialogue) {
dialogue = true;
this.textlines1 = line1;
this.textlines2 = line2;
this.textlines3 = line3;
timer.schedule(new TimerTask() {
#Override
public void run() {
dialogue = false;
}
}, dur);
} else {
System.out
.println("ERROR: Could not create dialogue, one is already displaying!");
}
}
}
I'm calling this from another class using this:
mng.createDialogue("test1", "test2", "test3", 1000);
Stacktrace:
Exception in thread "Thread-10" java.lang.NullPointerException: String is null
at sun.java2d.SunGraphics2D.drawString(Unknown Source)
at me.loafayyy.gui.GuiManager.render(GuiManager.java:98)
at me.loafayyy.main.RPGPane.render(RPGPane.java:107)
at me.loafayyy.main.RPGPane.run(RPGPane.java:82)
at java.lang.Thread.run(Unknown Source)
RPGPane is my JPanel.
I think the problem is your render method can be called before your createDialogue method. As a result, textlines1 can be unassigned/null.
One way to solve this is to take #Takendarkk's advice and initialize the variable to "". Another way is to ask yourself, "Does it make sense for this class to exist without textlines1 being set? If not, perhaps set this in the GuiManager's constructor.
I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.