Running Game in a Java Applet - java

I have written a small 2d scroller with the assistance of different snippets of code I have found on-line. The original package run as a JFrame application but I am trying to convert it into an applet. When I Run the program in Eclipse I do not receive any debugging errors just a blank applet viewer... I don't think I am missing anything from what I have read from different applet creation sources but maybe it is something very simple.
Frame class
package OurGame;
import java.awt.*;
import javax.swing.*;
public class Frame extends JApplet {
public Frame() {
JPanel frame = new JPanel();
frame.add(new Board());
// frame.setTitle("2D PLATFORMER");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,365);
frame.setVisible(true);
//frame.setLocationRelativeTo(null);
//setContentPane(frame);
}
// public static void main(String[] args){
public void init() {
new Frame();
}
}
Ive commented out the containers that were only workable in Jframe.
Dude class
package OurGame;
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Dude {
int x, dx, y,nx,nx2,left, dy;
Image still,jump,reverse;
ImageIcon s = new ImageIcon("redirect.png");
ImageIcon j= new ImageIcon("redirect.png");
ImageIcon l = new ImageIcon("redirect.png");
public Dude() {
x = 75;
left = 150;
nx = 0;
nx2= 685;
y = 172;
still = s.getImage();
}
public void move() {
if (dx != -1){
if (left + dx <= 150)
left+=dx;
else{
x = x + dx;
nx2= nx2+dx;
nx = nx + dx;
}}
else
{
if (left+dx >0)
left = left + dx;
}
}
public int getX() {
return x;
}
public int getnX() {
return nx;
}
public int getnX2() {
return nx2;
}
public int getdx() {
return dx;
}
public Image getImage() {
return still;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{ dx = -1;
still = l.getImage(); }
if (key == KeyEvent.VK_RIGHT)
{dx = 1;
still = s.getImage();
}
if (key == KeyEvent.VK_UP)
{dy = 1;
still = j.getImage();
} }
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
dx = 0;
if (key == KeyEvent.VK_RIGHT)
dx = 0;
if (key == KeyEvent.VK_UP)
{dy = 0;
still = s.getImage();}
}
}
Board Class
package OurGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener, Runnable {
Dude p;
public Image img;
Timer time;
int v = 172;
Thread animator;
boolean a = false;
boolean done2 = false;
public Board() {
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon("redirect.jpg");
img = i.getImage();
time = new Timer(5, this);
time.start();
}
public void actionPerformed(ActionEvent e) {
p.move();
repaint();
}
public void paint(Graphics g) {
if (p.dy == 1 && done2 == false) {
done2 = true;
animator = new Thread(this);
animator.start();
}
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if ((p.getX() - 590) % 2400 == 0)// p.getX() == 590 || p.getX() == 2990)
p.nx = 0;
if ((p.getX() - 1790) % 2400 == 0)// p.getX() == 1790 || p.getX() == 4190)
p.nx2 = 0;
g2d.drawImage(img, 685 - p.getnX2(), 0, null);
if (p.getX() > 590) {
g2d.drawImage(img, 685 - p.getnX(), 0, null);
}
g2d.drawImage(p.getImage(), p.left, v, null);
if (p.getdx() == -1) {
g2d.drawImage(img, 685 - p.getnX2(), 0, null);
g2d.drawImage(p.getImage(), p.left, v, null);
}
}
private class AL extends KeyAdapter {
public void keyReleased(KeyEvent e) {
p.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
p.keyPressed(e);
}
}
boolean h = false;
boolean done = false;
public void cycle() {
if (h == false)
v--;
if (v == 125)
h = true;
if (h == true && v <= 172) {
v++;
if (v == 172) {
done = true;
}
}
}
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (done == false) {
cycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = 10 - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
done = false;
h = false;
done2 = false;
}
}
I am a little stumbled after doing a fair amount of research. I am thinking Eclipse might not recognise that I have multiple class files but I kind of proved that theory wrong by writing a html page to display my applet that runs fine but is completely empty.

why is the applet viewer even in eclipse blank when running it..
At no point is anything added to the applet container. To add something to the applet would require overriding the applet init() method and calling add(new Board());. (That could also be done in the constructor, but it is more common to build an applet GUI within the init() method.)
Other Notes
paint(Graphics)
Since Board is a Swing class that is not a top-level container, custom painting should be done in the paintComponent(Graphics) method, rather than paint(Graphics).
Nomenclature
JPanel frame = new JPanel();
Wow! Poorly chosen attribute name. What do you call your JFrame instances, panel?
Application resources
ImageIcon s = new ImageIcon("redirect.png");
This will not work for an applet, and would not work for a deployed app. It is necessary to access images by URL. The Applet class has a specific method for loading images.
Remaining lines of constructor
JPanel frame = new JPanel();
frame.add(new Board());
frame.setSize(700,365);
frame.setVisible(true);
The first line of the constructor is not needed, the Board created in the next line can be added directly to the applet. That leaves two more lines not commented out.
frame.setSize(700,365);
The size of an applet should be set by the HTML.
frame.setVisible(true);
Anything added to a component that is visible will itself become visible. As such, this is also redundant.
Swing Timer
Since I pointed out so many faults in the code, just thought I should add that the animation seems to be done correctly - using a Swing Timer. :)

Related

Previous instances of characters are not erased

It's like if you were in a mirror maze, you might have trouble finding one specific reflections of yourself. So you would have multiple reflections of yourself, confusing you when you try to find that direct reflection of yourself.
Sadly I cannot post an image..........
So...
Character is "C"
It goes from
C
to
C C
when I attempt to move right.
package WASD;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class WASD extends JFrame implements KeyListener, ActionListener{
private int playerX = 400;
private int playerY = 400;
int C = 1;
private int RESTART = 0; // Three ENTER = Restart
private Timer timer;
JFrame j = new JFrame();
private int previousX = -50;
private int previousY = -50;
public WASD() {
JPanel panel = new JPanel();
setTitle("Not supposed to be a painting program.");
setSize(2000, 2000);
timer = new Timer(8, this);
this.getContentPane().add(panel);
addKeyListener(this);
setVisible(true);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
WASD W = new WASD();
}
public void paint(Graphics g) { //TODO paint is only working once, then failing forever.
//////////////////////////
g.setColor(Color.BLACK);
g.drawRect(0, 0, 3000, 3000); // Background
if(C == 1) g.setColor(Color.RED);
else if (C == 2) g.setColor(Color.BLUE);
else if (C == 3) g.setColor(Color.GREEN);
else if (C == 4) g.setColor(Color.YELLOW);
else if(C>4){
g.setColor(Color.GRAY);
try {
Thread.sleep(1000); //Gray pauses for a second I guess...
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
C = 1;
}
g.fillRect(playerX, playerY, 50, 50); // Player/
g.setColor(Color.BLACK);
g.fillRect(previousX, previousY, 50, 50);
g.dispose(); //Last thing
}
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
repaint();
}
#Override
public void keyPressed(KeyEvent K) {
// TODO Auto-generated method stub
int e = K.getKeyCode();
repaint(); //timer.start(); does not affect this. g.dispose() is unavailable.
/*
If this repaint is used, then the previous locations
that the player was at will be painted as well.
Basically, instead of moving, all instances
made will not be deleted. #PaintingApplication
However, if it is not used, then the CHARACTER will not move at all.
It seems that the problem is not about
playerX, or playerY,
instead, it is about the program not refreshing.
*/
if((e == KeyEvent.VK_RIGHT || e == KeyEvent.VK_D) && playerX<2000){
playerX += 200;
}
else if((e == KeyEvent.VK_LEFT || e == KeyEvent.VK_A) && playerX>0){
playerX -= 200;
}
else if((e == KeyEvent.VK_UP || e == KeyEvent.VK_W) && playerY>0){
playerY -= 200;
}
else if(e == KeyEvent.VK_DOWN || e == KeyEvent.VK_S && playerY<2000){ // Easter egg bug 1
playerY += 200;
}
else if (e == KeyEvent.VK_C){
C++;
}
else if(e == KeyEvent.VK_ENTER){
if(RESTART == 3){
playerX = 400;
playerY = 400;
RESTART = 0; //TODO
repaint();
}
else{
RESTART++;
}
}
else{
RESTART = 0;
}
}
#Override public void keyTyped(KeyEvent arg0) {}
#Override public void keyReleased(KeyEvent arg0) {}
}
I apologize for making such a simple mistake. The problem is in the function "paint". The line
g.drawRect(0, 0, 3000, 3000); //Outline of Rectangle
should be
g.fillRect(0, 0, 3000, 3000); //Actually filling the background.

Java 'Background' opens to small to see anything

I am making a game and the game window will only open to the size of the title. Please let me know what changes I need to make the "b.setSize(900,885)" work. I will change or add any amount of code if needed.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Background extends JFrame implements KeyListener, ActionListener{
int platform1X = 300, platform1Y = 555, platform2X, platform2Y;
Image image;
public boolean isJumping = false;
int playerx = 100, playery = 585, velX = 0, velY = 0;
public boolean[] keyDown = new boolean[4];
private int fallingSpeed = 0;
private int gravity = 5;
private int jumpPower = -30;
public Background(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
keyDown[0] = false;
keyDown[1] = false;
keyDown[2] = false;
keyDown[3] = false;
}
public void paint(Graphics g){
if(!isOnGround()){
fall();
}
ImageIcon i = new ImageIcon("/Users/kairotieremorton/Documents/java code/Kairo and Enoch Game/src/images/Backgroundsquareman.png");
image = i.getImage();
g.drawImage(image, 0, 0, 900, 700, null);
g.setColor(Color.BLUE);
g.fillRect(platform1X, platform1Y, 120, 20);
g.setColor(Color.RED);
g.fillRect(playerx, playery, 30, 30);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
playery = playery + velY;
playerx = playerx + velX;
}
public static void main(String[] args){
Background b = new Background();
b.setTitle("Game");
b.setSize(900,885);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setVisible(true);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(isOnGround() && key == KeyEvent.VK_SPACE){
keyDown[0] = true;
jump();
}
//if(key == KeyEvent.VK_DOWN){ setvelY(5); keyDown[1] = true;}
if(key == KeyEvent.VK_LEFT) { setvelX(-5); keyDown[2] = true;}
if(key == KeyEvent.VK_RIGHT) { setvelX(5); keyDown[3] = true;}
System.out.println(key);
System.out.println(playerx);
System.out.println(playery);
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_SPACE){ keyDown[0] = false;} //tempObject.setVelY(0);
//if(key == KeyEvent.VK_DOWN) keyDown[1] = false;//tempObject.setVelY(0);
if(key == KeyEvent.VK_LEFT) keyDown[2] = false;//tempObject.setVelX(0);
if(key == KeyEvent.VK_RIGHT) keyDown[3] = false; //tempObject.setVelX(0);
//vertical movement
if(!keyDown[0]) setvelY(0); System.out.println(isOnGround());
//horizontal movement
if(!keyDown[2] && !keyDown[3]) setvelX(0);
}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
//playery = playery + velY;
//playerx = playerx + velX;
//repaint();
}
public boolean isOnGround(){
if(playery + (30 /2) >= 585) {
return true;
}
return false;
}
public void fall(){
playery = playery + fallingSpeed;
fallingSpeed = fallingSpeed + gravity;
}
public void jump(){
fallingSpeed = jumpPower;
fall();
}
public void setvelX(int velX) {
this.velX = velX;
}
public void setvelY(int velY) {
this.velY = velY;
}
public float getvelX(){
return velX;
}
public float getvelY(){
return velY;
}
public int getplayerx(){
return playerx;
}
public int getplayery(){
return playery;
}
public void setplayerx(int playerx) {
this.playerx = playerx;
}
public void setplayery(int playery) {
this.playery = playery;
}
public Rectangle getBounds(){
return new Rectangle(getplatform1X(), platform1Y(), 120, 20);
}
public int getplatform1X(){
return platform1X;
}
public int platform1Y(){
return platform1Y;
}
public Rectangle getBoundsTop(){
return new Rectangle(getplayerx() + 10, getplayery(), 30 - 20, 5);
}
public Rectangle getBoundsBottom(){
return new Rectangle(getplayerx() + 10, getplayery() + 30 - 5, 30 - 20, 5);
}
public Rectangle getBoundsLeft(){
return new Rectangle(getplayerx(), getplayery()+10, 5, 30 -20);
}
public Rectangle getBoundsRigth(){
return new Rectangle(getplayerx() + 30 - 5, getplayery()+10, 5, 30 - 20);
}
}
Okay, that took a lot of looking, but...
public Rectangle getBounds() {
return new Rectangle(getplatform1X(), platform1Y(), 120, 20);
}
is your problem. JFrame#getBounds is a method used by JFrame to return the position and the size of the component and since you've overridden it, it will now ignore any values you pass to setSize (directly or indirectly)
Have a read of the following for reasons why you shouldn't override paint of top level containers like JFrame
How can I set in the midst?
Graphics rendering in title bar
Java JFrame .setSize(x, y) not working?
How to get the EXACT middle of a screen, even when re-sized
As a general rule of thumb, you should avoid extending from JFrame, as you're not really adding any new functionality to the class, it locks you into a single use case and, based on your experience, can cause other problems.
You should start with something like JPanel and override its paintComponent method instead (and make sure you call super.paintComponent before you do any custom painting)
Take a look at Painting in AWT and Swing and Performing Custom Painting
You paint methods should run as fast as possible, so you should avoid loading resources like loading images, within the paint method
Swing is single threaded, so calling Thread.sleep in the paint method will cause the entire program to stop, including it's ability to respond to new events from the user.
I'd also discourage you from using KeyListener, using the key bindings API will be more reliable. Take a look at How to Use Key Bindings for more details
Edit:
A better way to achieve the same result is to call b.setPreferredSize(dimension); and then pack() your frame.
See this answer for more information about JFrame.pack() :
https://stackoverflow.com/a/22982334/5224040
Try this in your main method:
public static void main(String[] args) {
Background b = new Background();
Dimension d = new Dimension(900, 885); //Create a new Dimension
b.setTitle("Game");
b.setPreferredSize(d); //Set the PreferredSize;
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.pack(); //Pack the frame
b.setVisible(true); //Setting Visible
}
You can also use the following methods to reposition your frame as necessary:
b.setLocationRelativeTo(null); //center the location on the screen.
b.setLocation(0, 0); //Set location explicitly
Call either of these methods below b.pack(); to reposition your frame.

Can i add JPanels to a JFrame with Graphics already on it?

So I recently started playing around with java graphics and have encountered an issue. I have drawn images onto a JFrame, but did not learn that the images' bounds cannot overlap each other if they're all in one JFrame (setting bounds over where another image is makes the image disappear). I heard something about using multiple JPanels to fix this. I do not know how to do this since I used a JFrame and not a JPanel in my program, so some help would be appreciated on this issue. Thank you, and I apologize if this question is dumb. (My other question that others seem to think was the same as this one was an issue of setting bounds, this question regards bounds overlapping and covering each other)
Here are my classes:
Window Class-
package game.thirdTry;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame {
private static Window instance;
public static Window getInstance() {
if(instance == null) {
instance = new Window("Game");
}
return instance;
}
private Window(String name) {
super(name);
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
//setUndecorated(true);
addKeyListener(new UserInput());
//this.getContentPane().getSize();
WindowStructure banner = new WindowStructure("Beatles Logo.jpg", 0, 0, getWidth(), 75);
//WindowStructure fball = new WindowStructure("fireball.100x100.png", 100, 100, 100, 100);
WindowStructure fball = WindowStructure.getInstanceF();
System.out.println("Fball.xSize: " + fball.xSize + ", Fball.ySize: " + fball.ySize);
System.out.println("Fball.xLoc: " + fball.xLoc + ", Fball.yLoc: " + fball.yLoc);
//banner.setBounds(banner.xLoc, banner.yLoc, banner.xSize, banner.ySize);
//fball.setBounds(fball.xLoc, fball.yLoc, fball.xLoc + fball.xSize, fball.ySize + fball.ySize);
banner.setBounds(0, 0, getWidth(), getHeight());
fball.setBounds(0, 75, getWidth(), getHeight());
add(fball, null);
add(banner, null);
setVisible(true);
while(true){
System.out.println("Fball.xLoc: " + fball.xLoc + ", Fball.yLoc: " + fball.yLoc);
repaint();
try{
Thread.sleep(10);
}catch (Exception e){
}
}
}
/*
public void paint(Graphics g) {
super.paintComponents(g);
}
*/
}
Image Class-
package game.thirdTry;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class WindowStructure extends JPanel {
private static WindowStructure fball;
public static WindowStructure getInstanceF(){
if(fball == null){
fball = new WindowStructure("fireball.100x100.png", 0, 75, 100, 100);
}
return fball;
}
ImageIcon imageIcon;
int xLoc, yLoc, xSize, ySize;
public WindowStructure(String bannerImg, int xLoc, int yLoc, int xSize, int ySize){
URL bannerImgURL = getClass().getResource(bannerImg);
imageIcon = new ImageIcon(bannerImgURL);
this.xLoc = xLoc;
this.yLoc = yLoc;
this.xSize = xSize;
this.ySize = ySize;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(imageIcon.getImage(), xLoc, yLoc, xSize, ySize, null);
}
}
KeyListener / User Input Class-
package game.thirdTry;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class UserInput implements KeyListener {
// Window window = Window.getInstance();
WindowStructure fball = WindowStructure.getInstanceF();
boolean goUp = false;
boolean goDown = false;
boolean goLeft = false;
boolean goRight = false;
public void moveUpDown() {
if (goUp && goDown) {
if (fball.yLoc > 0) {
fball.yLoc -= 10;
}
} else if (goUp) {
if (fball.yLoc > -5) {
fball.yLoc -= 10;
}
} else if (goDown) {
if (fball.yLoc < 480) {
fball.yLoc += 10;
}
}
System.out.println("moveUpDown() method called");
}
public void moveLeftRight() {
if (goLeft && goRight) {
if (fball.xLoc < 1100) {
fball.xLoc += 10;
}
} else if (goRight) {
if (fball.xLoc < 1110) {
fball.xLoc += 10;
}
} else if (goLeft) {
if (fball.xLoc > 0) {
fball.xLoc -= 10;
}
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
goUp = true;
goDown = false;
}
if (e.getKeyCode() == KeyEvent.VK_S) {
goDown = true;
goUp = false;
}
if (e.getKeyCode() == KeyEvent.VK_A) {
goLeft = true;
goRight = false;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
goRight = true;
goLeft = false;
}
moveUpDown();
moveLeftRight();
System.out.println("keyPressed() was called");
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
goUp = false;
}
if (e.getKeyCode() == KeyEvent.VK_S) {
goDown = false;
}
if (e.getKeyCode() == KeyEvent.VK_A) {
goLeft = false;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
goRight = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
//g2d.drawImage(imageIcon.getImage(), xLoc, yLoc, xSize, ySize, null);
The problem is that you are scaling the image as you paint the image. Therefore the image takes up the entire window space and so yes it paints over top of the image painted first.
Just paint the image at its real size:
g2d.drawImage(imageIcon.getImage(), xLoc, yLoc, this);
This is another reason to use a JLabel. You don't need to worry about the size. You just position the label at a specific location and the image will be painted. The code is much simpler. And using this approach you don't need to worry about making the panel non-opaque.
The problem with your code now is that you need to make the panel a large size because you are painting the image relative to your WindowStructure panel. So if your image is (25 x 25) and you want the image painted at (100, 100), you need to make the panel (125, 125), which means the panel need to be transparent so the part of the panel that does not contain the image is not painted. Using a JLable, the size of the label will always be (25, 25) so you simple set the location of the label and only (25, 25) pixels will be painted.
I'll look more into JLabels later
Look at it now. There is no time like the present!
Also, your WindowStructure class has a terrible design. There is no need for the static methods and variables. Each image should be independent of one another.

Grey screen in Netbeans

so i using netbeans, and i'm starting to get into coding games... and i've done this so far with no errors, however when i run it just a grey box with my title "zachs game appears and thats it.... please help if you know the problem 1 -thank you
package swing9;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class JavaApplication2 extends JFrame implements Runnable {
int x, y, xDirection, yDirection;
Font font = new Font("Arial", Font.BOLD | Font.ITALIC, 30);
public void run() {
try {
while (true) {
move();
Thread.sleep(5);
}
} catch (Exception e) {
System.out.println("Error");
}
}
public void move() {
x += xDirection;
y += yDirection;
if (x <= 0)
x = 0;
if (x >= 300)
x = 300;
if (y <= 50)
y = 50;
if (y <= 300)
y = 300;
}
public void seyXDir(int xdir) {
xDirection = xdir;
}
public void setYDirection(int ydir) {
yDirection = ydir;
}
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
int setXDirection = -1;
}
if (keyCode == e.VK_RIGHT) {
int setXDirection = +1;
}
if (keyCode == e.VK_UP) {
int setYDirection = -1;
}
if (keyCode == e.VK_DOWN) {
int setYDirection = +1;
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
int setXDirection = 0;
}
if (keyCode == e.VK_RIGHT) {
int setXDirecetion = 0;
}
if (keyCode == e.VK_UP) {
int setYDirectiom = 0;
}
if (keyCode == e.VK_DOWN) {
int setYDirecction = 0;
}
}
public JavaApplication2() {
addKeyListener((KeyListener) new JavaApplication2.AL());
setTitle("Zachs Game");
setSize(300, 300);
setResizable(false);
setVisible(true);
setBackground(Color.blue);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawString("Play", 40, 40);
g.setFont(font);
g.setColor(Color.red);
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] args) {
new JavaApplication2();
// threads
Thread t1 = new Thread();
t1.start();
}
}
JFrame or any of its super classes do not implement the paintComponent method so is never invoked. Check this yourself by adding the #Override annotation.
Move this method to a new class that extends JComponent and invoke super.paintComponent(g) as the first statement.
Don't call repaint from within paintComponent, this create an infinite loop and degrades performance. Swing Timers were designed to interact more easily with swing components. Use these over than raw Threads for periodic updates.
Aside: JFrame is not focusable by default so KeyEvents which require focus will not be triggered without making the window focusable. Use Key Bindings instead.

Eclipse Indigo bug

I have been running Eclipse Indigo for a few months now, and I have run into a bug that I cannot seem to find an answer to. I am creating a small 2d side-scroller game similar to that of mario, the old zelda, etc.
I was going to show a my dad what new feature I had added into my program. Instead of coming upstairs to see my program on my computer, my dad decided that he could get into it using a sudo screen-viewing thing that I am not sure of. We have used this before, and basically all it does is let you see the screen of another computer in your home (on the same IP interface), and you can use the computer too.
I didn't want to show my program to my dad this way, so I told him to come upstairs. He did, and ever since then, eclipse will not show any graphics inside of your JFrame in your program. It will show things such as words (written on the screen), but will not show ANY graphics. Such as your background image, or your character, or anything else. I am POSITIVE that it isn't some problem with my coding, because I had tested and played the game quite a few times before my dad did the screen-viewing thing (we are both on linux mint 12, BTW).
I think that this bug is related to the screen-viewing thing.
I would love it if I could get some help. any would be great. Thanks.
-This has been solved*
Board
package External;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Board extends JPanel implements ActionListener, Runnable {
Dude p;
Image img;
Timer time;
int v = 172;
Thread animator;
boolean a = false;
boolean done2 = false;
public Board() {
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon ("/home/clark/Desktop/Swindle_test_background.png");
img = i.getImage();
time = new Timer (3, this);
time.start();
}
public void actionPerformed(ActionEvent e) {
p.move();
repaint();
}
public void paint(Graphics g) {
if (p.dy == 1 && done2 == false)
{
done2 = true;
animator = new Thread(this);
animator.start();
}
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if ((p.getX() - 590) % 2400 == 0)
p.nx = 0;
if ((p.getX() - 1790) % 2400 == 0)
p.nx2 = 0;
g2d.drawImage(img, 985-p.nx2, 0, null);
if (p.getX() >= 921)
g2d.drawImage(img, 985-p.nx, 0, null);
g2d.drawImage(p.getImage(), 75, v, null);
}
private class AL extends KeyAdapter {
public void keyReleased(KeyEvent e) {
p.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
p.keyPressed(e);
}
}
boolean h = false;
boolean done = false;
public void cycle() {
if (h == false)
v--;
if (v == 125)
h = true;
if (h == true && v <= 172 ) {
v++;
if (v == 172) {
done = true;
}
}
}
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (done == false) {
cycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = 10 - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
done = false;
h = false;
done2 = false;
}
}
Dude
package External;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Dude {
int x, dx, y, nx2, nx, dy;
Image Swindle_Man_Right;
ImageIcon r = new ImageIcon("/home/clark/Desktop/Swindle_Man_Right.png");
ImageIcon l = new ImageIcon("/home/clark/Desktop/Swindle_Man_Left.png");
ImageIcon j = new ImageIcon("/home/clark/Desktop/Swindle_Man_Jump.png");
public Dude() {
Swindle_Man_Right = l.getImage();
x = 75;
nx2 = 685;
nx = 0;
y = 172;
}
public void move() {
x = x + dx;
nx2 = nx2 + dx;
nx = nx + dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return Swindle_Man_Right;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{ dx = -1;
Swindle_Man_Right = l.getImage();
}
if (key == KeyEvent.VK_RIGHT)
{dx = 1;
Swindle_Man_Right = r.getImage();
}
if (key == KeyEvent.VK_UP)
{dy = 1;
Swindle_Man_Right= j.getImage();
} }
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
dx = 0;
if (key == KeyEvent.VK_RIGHT)
dx = 0;
if (key == KeyEvent.VK_UP)
{dy = 0;
Swindle_Man_Right= r.getImage();}
}
}
Frame
package External;
import javax.swing.*;
public class Frame {
public Frame() {
JFrame frame = new JFrame("Swindle [version 0.1.9]");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,390);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Frame();
}
}
As near as I can tell, you've not added anything to the frame.
After I replaced the graphics with my own, I was able to get it running...
public class Frame {
public static void main(String[] args) {
new Frame();
}
public Frame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Swindle [version 0.1.9]");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// This is kind of important...
frame.add(new Board());
frame.setSize(700, 390);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
While I've only given the code quick glance, I would recommend that you don't use ImageIcon to load you images and instead use the ImageIO API. Apart from supporting more image formats, it will throw more errors when it can't load the images.
I would also avoid using KeyListener in favor of key bindings. They don't suffer from the same focus issues as KeyListener

Categories

Resources