Alright so I'm making a game in Java. I'm stuck at an error that is stubborn. It is saying:
[CODE]Multiple markers at this line
- Cannot instantiate the type Graphics2D
- Watchpoint:GPanel [access and [/CODE]
I am using Eclipse. Do not judge as I'm a beginner and I suck at this.
GPanel.java
[CODE]import javax.swing.JPanel;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics2D.*;
public class GPanel extends JPanel implements Runnable {
// Fields
public static int WIDTH = 1920;
public static int HEIGHT = 1080;
private Thread thread;
private boolean running;
private BufferedImage image;
private Graphics2D g2 = new Graphics2D();
//Constructor
public GPanel() {
//super();
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
gameRender();
}
//Functions
public void addNotify() {
super.addNotify();
if(thread == null) {
thread = new Thread();
thread.start();
}
}
public void run() {
running = true;
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
//Loop
while(running) {
gameUpdate();
gameRender();
gameDraw();
}
}
private void gameUpdate() {
}
private void gameRender() {
g.setColor(Color.BLUE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.drawString("TEST STRING", 100, 100);
}
private void gameDraw() {
Graphics g2 = this.getGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
}
}
[/CODE]
Game.java
[CODE]import javax.swing.JFrame;
public class Game{
public static void main(String[] args) {
JFrame window = new JFrame("Into the Void");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(new GPanel());
window.pack();
window.setVisible(true);
}
}
[/CODE]
You don't initialize Graphics2D, you use the paint method that comes with JPanel.
[CODE]
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
//Render code here
}
[/CODE]
You also must call repaint() in your game loop.
[QUOTE=Rayboy1995;46445001]You don't initialize Graphics2D, you use the paint method that comes with JPanel.
[CODE]
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
//Render code here
}
[/CODE]
You also must call repaint() in your game loop.[/QUOTE]
Better to override paintComponent actually, instead of paint.
Also depending on the game loop sometimes repaint gets stuck in the event queue and never gets to rendering. Better to call paintImmediately.
Alright I've updated the code a bit more from then. I am now receiving a toString error:
[CODE]toString cannot be resolved or is not a field[/CODE]
Client.java:
[CODE] System.out.println("Loading textures...");
textureManager = new TextureManager();
String maps = "C:/Users/Aeternal/Desktop/FPSGameServer/cola.map";
// mapname = dis.readUTF();
// System.out.println("Downloading map: "+mapname);
// String map = dis.readUTF();
// System.out.println(map);
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(maps));
char[] buf = new char[1024];
int numRead = 0;
while((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
for(String piece : fileData.toString.split("\n")){ //This is where the error is
Vector3f start = new Vector3f(Float.parseFloat(piece.split(" ")[0].split(",")[0]), Float.parseFloat(piece.split(" ")[0].split(",")[1]), Float.parseFloat(piece.split(" ")[0].split(",")[2]));
Vector3f end = new Vector3f(Float.parseFloat(piece.split(" ")[1].split(",")[0]), Float.parseFloat(piece.split(" ")[1].split(",")[1]), Float.parseFloat(piece.split(" ")[1].split(",")[2]));
collidable.add(new PolyVoxel(start.x, start.y, start.z, end.x, end.y, end.z, Integer.parseInt(piece.split(" ")[2])));
}
File map;
System.out.println("Downloaded \""+mapname+"\" ("+map.length()+" bytes)");
TextureManager.FLOOR = dis.readInt();
System.out.print("Getting texture list...");
String textureFileName = "C:/Users/Aeternal/Desktop/FPSGameServer/res";
System.out.println("Downloaded \""+textureFileName+"\" ("+textureFileName.length()+" bytes)");
String textureManifest = dis.readUTF();
for(String s : textureManifest.split("\n")){
if(!new File("res/"+s.split(":")[1]).exists()){
System.out.println("Downloading texture: "+s.split(":")[1]);
dos.writeBoolean(true);
dos.flush();
dos.writeUTF(s.split(":")[1]);
dos.flush();
ObjectInputStream ois = new ObjectInputStream(dis);
ImageIcon icon = (ImageIcon) ois.readObject();
ImageIO.write(bufferImage(icon.getImage()), "JPG", new File("res/"+s.split(":")[1]));
textureManager.texture[Integer.parseInt(s.split(":")[0])] = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("res/"+s.split(":")[1]));
}else{
textureManager.texture[Integer.parseInt(s.split(":")[0])] = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("res/"+s.split(":")[1]));
}
}
dos.writeBoolean(false);
dos.flush();
}[/CODE]
[QUOTE=killerteacup;46445207]Better to override paintComponent actually, instead of paint.
Also depending on the game loop sometimes repaint gets stuck in the event queue and never gets to rendering. Better to call paintImmediately.[/QUOTE]
Haven't used Swing in ages excuse me. :v:
[editline]9th November 2014[/editline]
[QUOTE=Aeternal;46446859]Alright I've updated the code a bit more from then. I am now receiving a toString error:
[CODE]toString cannot be resolved or is not a field[/CODE]
Client.java:
[CODE] System.out.println("Loading textures...");
textureManager = new TextureManager();
String maps = "C:/Users/Aeternal/Desktop/FPSGameServer/cola.map";
// mapname = dis.readUTF();
// System.out.println("Downloading map: "+mapname);
// String map = dis.readUTF();
// System.out.println(map);
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(maps));
char[] buf = new char[1024];
int numRead = 0;
while((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
for(String piece : fileData.toString.split("\n")){ //This is where the error is
Vector3f start = new Vector3f(Float.parseFloat(piece.split(" ")[0].split(",")[0]), Float.parseFloat(piece.split(" ")[0].split(",")[1]), Float.parseFloat(piece.split(" ")[0].split(",")[2]));
Vector3f end = new Vector3f(Float.parseFloat(piece.split(" ")[1].split(",")[0]), Float.parseFloat(piece.split(" ")[1].split(",")[1]), Float.parseFloat(piece.split(" ")[1].split(",")[2]));
collidable.add(new PolyVoxel(start.x, start.y, start.z, end.x, end.y, end.z, Integer.parseInt(piece.split(" ")[2])));
}
File map;
System.out.println("Downloaded \""+mapname+"\" ("+map.length()+" bytes)");
TextureManager.FLOOR = dis.readInt();
System.out.print("Getting texture list...");
String textureFileName = "C:/Users/Aeternal/Desktop/FPSGameServer/res";
System.out.println("Downloaded \""+textureFileName+"\" ("+textureFileName.length()+" bytes)");
String textureManifest = dis.readUTF();
for(String s : textureManifest.split("\n")){
if(!new File("res/"+s.split(":")[1]).exists()){
System.out.println("Downloading texture: "+s.split(":")[1]);
dos.writeBoolean(true);
dos.flush();
dos.writeUTF(s.split(":")[1]);
dos.flush();
ObjectInputStream ois = new ObjectInputStream(dis);
ImageIcon icon = (ImageIcon) ois.readObject();
ImageIO.write(bufferImage(icon.getImage()), "JPG", new File("res/"+s.split(":")[1]));
textureManager.texture[Integer.parseInt(s.split(":")[0])] = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("res/"+s.split(":")[1]));
}else{
textureManager.texture[Integer.parseInt(s.split(":")[0])] = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("res/"+s.split(":")[1]));
}
}
dos.writeBoolean(false);
dos.flush();
}[/CODE][/QUOTE]
Also you forgot your parentheses there, its a method that returns a string. toString()
What are you using to compile by the way?
I am using Eclipse
Edit: I am now provided with this error (I know I"m asking alot of questions here but I'm learning java and I thought I could fix something up. Sorry.)
[CODE]java.lang.NumberFormatException: For input string: "1
"
Could not start the client!
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Client.load(Client.java:132)
at Client.<init>(Client.java:91)
at Client.main(Client.java:45)
[/CODE]
Client.java:
[CODE]import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;
import org.lwjgl.util.vector.Vector3f;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
public class Client {
static String ip;
static int port;
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
if(args.length == 1){
ip = args[0].split(":")[0];
port = Integer.parseInt(args[0].split(":")[1]);
}else{
/*System.out.print("Enter server address: ");
String address = scanner.nextLine();
ip = address.split(":")[0];
port = Integer.parseInt(address.split(":")[1]);*/
ip = "208.146.35.27";
port = 21;
}
new Client();
}
static Socket socket;
static DataInputStream dis;
static DataOutputStream dos;
static String username, password, mapname;
static String[] messages = {"","","",""};
static TextureManager textureManager;
List<PolyVoxel> collidable = new ArrayList<PolyVoxel>();
List<PolyFace> floor = new ArrayList<PolyFace>();
Camera camera = new Camera(this);
boolean[] keys = new boolean[256];
OnlinePlayer[] players = new OnlinePlayer[8];
public Client(){
System.out.println("Starting client @ "+ip+":"+port);
System.out.print("Enter username: ");
username = scanner.nextLine().replace(" ", "_");
System.out.print("Enter password: ");
password = scanner.nextLine().replace(" ", "_");
System.out.println("Connecting...");
try{
socket = new Socket(ip,port);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dos.writeUTF("USER " + username + "\n");
dos.writeUTF("PASS " + username + "\n");
dos.flush();
boolean connected = dis.readBoolean();
if(connected){
System.out.println("Connected to server!\nInitializing graphics...");
}else{
System.out.println("Server rejected connection: game is full.");
System.exit(0);
return;
}
Display.setDisplayMode(new DisplayMode(512,512));
Display.setTitle("session @ "+ip+":"+port);
Display.create();
load();
init();
}catch (Exception e) {
e.printStackTrace();
System.out.println("Could not start the client!");
System.exit(0);
}
}
public void load() throws Exception{
Mouse.setGrabbed(true);
for(int y=0;y<32;y+=2){
for(int x=0;x<32;x+=2){
floor.add(new PolyFace(x,0,y,x+2,0,y+2));
}
}
System.out.println("Loading textures...");
textureManager = new TextureManager();
String maps = "C:/Users/Aeternal/Desktop/FPSGameServer/cola.map";
// mapname = dis.readUTF();
// System.out.println("Downloading map: "+mapname);
// String map = dis.readUTF();
// System.out.println(map);
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(maps));
char[] buf = new char[1024];
int numRead = 0;
while((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
for(String piece : fileData.toString().split("\n")){
Vector3f start = new Vector3f(Float.parseFloat(piece.split(" ")[0].split(",")[0]), Float.parseFloat(piece.split(" ")[0].split(",")[1]), Float.parseFloat(piece.split(" ")[0].split(",")[2]));
Vector3f end = new Vector3f(Float.parseFloat(piece.split(" ")[1].split(",")[0]), Float.parseFloat(piece.split(" ")[1].split(",")[1]), Float.parseFloat(piece.split(" ")[1].split(",")[2]));
collidable.add(new PolyVoxel(start.x, start.y, start.z, end.x, end.y, end.z, Integer.parseInt(piece.split(" ")[2])));
}
File map = null;
System.out.println("Downloaded \""+mapname+"\" ("+map.length()+" bytes)");
TextureManager.FLOOR = dis.readInt();
System.out.print("Getting texture list...");
String textureFileName = "C:/Users/Aeternal/Desktop/FPSGameServer/res";
System.out.println("Downloaded \""+textureFileName+"\" ("+textureFileName.length()+" bytes)");
String textureManifest = dis.readUTF();
for(String s : textureManifest.split("\n")){
if(!new File("res/"+s.split(":")[1]).exists()){
System.out.println("Downloading texture: "+s.split(":")[1]);
dos.writeBoolean(true);
dos.flush();
dos.writeUTF(s.split(":")[1]);
dos.flush();
ObjectInputStream ois = new ObjectInputStream(dis);
ImageIcon icon = (ImageIcon) ois.readObject();
ImageIO.write(bufferImage(icon.getImage()), "JPG", new File("res/"+s.split(":")[1]));
textureManager.texture[Integer.parseInt(s.split(":")[0])] = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("res/"+s.split(":")[1]));
}else{
textureManager.texture[Integer.parseInt(s.split(":")[0])] = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("res/"+s.split(":")[1]));
}
}
dos.writeBoolean(false);
dos.flush();
}
public void init(){
try{
initNetworking();
while(!Display.isCloseRequested()){
update();
render();
Display.sync(60);
Display.update();
}
System.out.println("Good night!");
try{
System.out.println("sent: "+dos.size()+"b ("+(dos.size()/1024)+"kb)");
dis.close();
dos.close();
socket.close();
}catch (Exception e) {}
Display.destroy();
System.exit(0);
}catch (Exception e) {
e.printStackTrace();
}
}
public void update() throws Exception {
for(int i=0;i<256;i++) keys[i] = Keyboard.isKeyDown(i);
camera.update();
if(keys[Keyboard.KEY_F1]){
Mouse.setGrabbed(false);
}
if(keys[Keyboard.KEY_F2]){
Mouse.setGrabbed(true);
}
}
public void render() throws Exception {
initGL3();
clearGL();
camera.translateCamera();
GL11.glColor3f(1, 1, 1);
textureManager.texture[TextureManager.FLOOR].bind();
for(PolyFace face : floor) face.render();
for(PolyVoxel voxel : collidable) voxel.render();
textureManager.texture[TextureManager.WHITE].bind();
for(Vector3f vector : players){
if(vector == null) continue;
PolyVoxel v = new PolyVoxel(vector.x-0.5f,vector.y,vector.z-0.5f, vector.x+0.5f,vector.y+1.25f,vector.z+0.5f, 0);
GL11.glColor3f(1, 0, 0);
v.render();
}
GL11.glPushMatrix();
initGL2();
GL11.glBegin(GL11.GL_POINTS);
GL11.glColor3f(1, 1, 1);
GL11.glVertex2f(Display.getWidth()/2, Display.getHeight()/2);
GL11.glColor3f(0.5f, 0.5f, 1);
GL11.glVertex2f(Display.getWidth()/2, (Display.getHeight()/2)+8);
GL11.glVertex2f(Display.getWidth()/2, (Display.getHeight()/2)-8);
GL11.glVertex2f((Display.getWidth()/2)+8, Display.getHeight()/2);
GL11.glVertex2f((Display.getWidth()/2)-8, Display.getHeight()/2);
GL11.glEnd();
GL11.glColor3f(1, 1, 0);
SimpleText.drawString("openFPS developers build "+camera.vector.x+" "+camera.vector.y+" "+camera.vector.z, 4, 4);
for(int i=messages.length-1;i>=0;i--){
SimpleText.drawString(messages[i], 4, Display.getHeight()-50+(i*10));
}
if(keys[Keyboard.KEY_TAB]){
SimpleText.drawString("Scoreboard", 100, Display.getHeight()-100);
for(int i=0;i<players.length;i++){
if(players[i] == null) continue;
SimpleText.drawString(players[i].username, 125, Display.getHeight()-120+(i*10));
}
}
}
public static void addMessage(String message){
messages[3] = messages[2];
messages[2] = messages[1];
messages[1] = messages[0];
messages[0] = message;
}
private void initGL3(){
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GLU.gluPerspective((float) 100, Display.getWidth() / Display.getHeight(), 0.001f, 1000);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
GL11.glClearDepth(1.0f);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
}
public void initGL2(){
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glLoadIdentity();
}
private void clearGL(){
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
//GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
GL11.glLoadIdentity();
}
private void initNetworking() {
addMessage("playing "+mapname+" at server "+socket.getInetAddress().getHostAddress());
new Thread(){
public void run(){
try{
while(true) networking();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
public void networking() throws Exception {
if(camera.previous != camera.vector){
dos.writeByte(1);
dos.flush();
dos.writeFloat(camera.vector.x);
dos.writeFloat(camera.vector.y);
dos.writeFloat(camera.vector.z);
dos.flush();
}
dos.writeByte(-1);
dos.flush();
byte packet;
while((packet = dis.readByte()) != -1){
if(packet == 1){
int target = dis.readInt();
if(players[target] == null){
players[target] = new OnlinePlayer(0,0,0);
addMessage("a player has joined the game");
}
players[target].x = dis.readFloat();
players[target].y = dis.readFloat();
players[target].z = dis.readFloat();
}else if(packet == 10){
String playerList = dis.readUTF();
for(int i=0;i<playerList.length();i++){
if(playerList.toCharArray()[i] == '0'){
if(players[i] != null) addMessage("a player has left the game");
players[i] = null;
}
}
}else if(packet == 11){
int id = dis.readInt();
String name = dis.readUTF();
if(players[id] != null)
players[id].username = name;
}
}
}
public static BufferedImage bufferImage(Image image) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, null, null);
return bufferedImage;
}
}
[/CODE]
[QUOTE=Aeternal;46447044]I am using Eclipse
Edit: I am now provided with this error (I know I"m asking alot of questions here but I'm learning java and I thought I could fix something up. Sorry.)
[/QUOTE]
Its fine, though I recommend just googling any errors you get, or trying to figure it out your self. A number format exception is when the string you input isn't recognized as a number for some reason.
Where is it showing the error? That would help a lot.
[QUOTE=Rayboy1995;46446930]Haven't used Swing in ages excuse me. :v:
[/QUOTE]
This is definitely a good decision on your part
Aerternal, the error is coming from your load function. You're parsing an integer using an invalid string. Looks to me like one of the number strings you're parsing in has a trailing newline - you can even see it in the error stacktrace, the apostrophe is on the next line - so there's a trailing newline. Looks like you need to sanitize the strings you're reading in first.
I haven't looked too closely but I can tell you that if you are reading anything in from a file you will get this error at the end of each line. Make sure to clean up what you're reading in by removing trailing new lines before you parse it as an int!
Sorry, you need to Log In to post a reply to this thread.