problem for moving image

i want to move the image auto going down when i press enter or space bar.

i do this for my codebut it does't work.

class Playscreenextends JPanel{

ImageIcon playbg;

ImageIcon playerIcon;

ImageIcon[] stair;

int floor;

int live;

Point loc =new Point(100,100);

int dx = 3;

int dy = 3;

Rectangle[] rects;

Random seed =new Random();

String[] fileNames;

boolean firstTime =true;

boolean startplay = fales;

public Playscreen(){

String img ="stair.jpg";

fileNames =new String[20];

playbg =new ImageIcon("image/bgimg.jpg");

playerIcon =new ImageIcon("image/player.gif");

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

while(startplay)

{

loc.y ++;

repaint();

}

for(int f = 0; f < 20; f++){

fileNames[f] = img ;

}

rects =new Rectangle[fileNames.length];

stair =new ImageIcon[fileNames.length];

for(int j = 0; j < rects.length; j++){

stair[j] =new ImageIcon("Image/" + fileNames[j]);

rects[j] =new Rectangle(stair[j].getIconWidth(), stair[j].getIconHeight());

}

}

protectedvoid paintComponent(Graphics g){

super.paintComponent(g);

g.drawImage(playbg.getImage(), 0, 0,this);

g.drawImage(playerIcon.getImage(), loc.x, loc.y,this);

if(firstTime){

setRects();

firstTime =false;

}

for(int j = 0; j < stair.length; j++){

g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y,this);

}

}

privatevoid setRects(){

Point p;

for(int j = 0; j < rects.length; j++){

do{

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

}while(!notTouching(j));

}

}

privateboolean notTouching(int index){

for(int j = 0; j < index; j++){

if(rects[j].intersects(rects[index]))

returnfalse;

}

returntrue;

}

private Point getRandomLocationFor(Rectangle r){

Point p =new Point();

p.x = seed.nextInt(getWidth() - r.width );

p.y = seed.nextInt(getHeight() - r.height);

return p;

}

privatevoid registerKeys(){

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"),"UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"),"LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"),"DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"),"RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction =new AbstractAction(){

publicvoid actionPerformed(ActionEvent e){

}

};

private Action leftAction =new AbstractAction(){

publicvoid actionPerformed(ActionEvent e){

loc.x -= dx;

repaint();

}

};

private Action downAction =new AbstractAction(){

publicvoid actionPerformed(ActionEvent e){

startplay = fales;

}

};

private Action rightAction =new AbstractAction(){

publicvoid actionPerformed(ActionEvent e){

loc.x += dx;

repaint();

}

};

}

i add startplay = fales to make the image when press downarror auto going down.

i want make look like this pic .the people can stand on the rect.

http://i104.photobucket.com/albums/m173/finalmilk/ok.jpg

Message was edited by:

nickgoldgodl

[7720 byte] By [nickgoldgodla] at [2007-11-27 4:30:41]
# 1

i add startplay = fales

You may have meant to write it as false.

i want make look like this pic .the people can stand on the rect.

Okay. Try this.

import java.awt.*;

import java.awt.event.*;

import java.awt.image.BufferedImage;

import javax.swing.*;

public class StairStep extends JPanel {

BufferedImage bgImage;

BufferedImage stairStep;

BufferedImage hero;

Rectangle[] rects;

Rectangle heroRect;

int dx = 2;

int dy = 2;

public StairStep() {

registerKeys();

addComponentListener(cl);

}

private void moveHero(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

x += heroRect.x;

y += heroRect.y;

heroRect.setFrameFromDiagonal(x, y, x+heroRect.width, y+heroRect.height);

repaint();

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

if(rects == null) {

createImages();

initRects();

}

g2.drawImage(bgImage, 0, 0, this);

for(int j = 0; j < rects.length; j++) {

g2.draw(rects[j]);

g2.drawImage(stairStep, rects[j].x, rects[j].y, this);

}

g2.draw(heroRect);

g2.drawImage(hero, heroRect.x, heroRect.y, this);

}

private void initRects() {

double[][] coords = {

{ 0.2, 0.175 }, { 0.2, 0.30 }, { 0.35, 0.45 },

{ 0.55, 0.60 }, { 0.75, 0.75 }, { 0.1, 0.85 }

};

rects = new Rectangle[coords.length];

int w = getWidth();

int h = getHeight();

int iw = stairStep.getWidth();

int ih = stairStep.getHeight();

for(int j = 0; j < rects.length; j++) {

int x = (int)(coords[j][0]*w);

int y = (int)(coords[j][1]*h);

rects[j] = new Rectangle(x, y, iw, ih);

}

iw = hero.getWidth();

ih = hero.getHeight();

int x = rects[3].x + 20;

int y = rects[3].y - ih;

heroRect = new Rectangle(x, y, iw, ih);

}

private void createImages() {

int w = getWidth();

int h = getHeight();

int type = BufferedImage.TYPE_INT_RGB;

bgImage = new BufferedImage(w, h, type);

Graphics2D g2 = bgImage.createGraphics();

g2.setBackground(Color.pink);

g2.clearRect(0,0,w,h);

g2.setPaint(Color.red);

g2.setFont(g2.getFont().deriveFont(24f));

g2.drawString("bgImage", w/2, h*11/12f);

g2.dispose();

stairStep = new BufferedImage(85, 15, type);

g2 = stairStep.createGraphics();

g2.setBackground(Color.blue);

g2.clearRect(0,0,86,15);

g2.dispose();

hero = new BufferedImage(25, 40, type);

g2 = hero.createGraphics();

g2.setBackground(Color.green.darker());

g2.clearRect(0,0,25,40);

g2.dispose();

}

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveHero(0, -1);

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveHero(-1, 0);

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveHero(0, 1);

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveHero(1, 0);

}

};

private ComponentListener cl = new ComponentAdapter() {

public void componentResized(ComponentEvent e) {

rects = null;

repaint();

}

};

public static void main(String[] args) {

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(new StairStep());

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

crwooda at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 2

it not work when i press the down arrow the move image cross over the rect. i don't want the move image can cross over that.and also how to make the move image when i press enter the move image will going down but do not stop.when the image move to the rect than stop on there

here is my explaination:

http://i104.photobucket.com/albums/m173/finalmilk/jojo.jpg

this game is a sample i like. the black people(image)stand on the floor(REct) than can walk and walk down.

http://www.java.com/en/games/mobile/stickfighterfury.jsp

Message was edited by:

nickgoldgodl

Message was edited by:

nickgoldgodl

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 3

i have other question i try to make the image can't move out of the playscreen i do this code:(but not work)

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

if(loc.x > 0 || loc.x < 200){

loc.x ++;

repaint();

}else if(loc.x < 0 || loc.x >200){

loc.x = -1;

repaint();

}

}

};

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 4

it not work when i press the down arrow the move image cross over the rect.

The StairStep class showed how to locate the stair rects/images according to your image.

i don't want the move image can cross over that.

CollisionTest showed how to do this. See reply 9 in your thread [url=http://forum.java.sun.com/thread.jspa?threadID=5171926]problem for drawimage[/url].

and also how to make the move image when i press enter the move image will going down but do not stop.

I showed how to do key binding and gave a tutorial link about it in reply 1 of your thread [url=http://forum.java.sun.com/thread.jspa?threadID=5171932]problem for Key Listener[/url].

To make it not stop you will have to start a thread or Swing timer to move the rect.

Start the thread/timer in the Action for the key binding.

when the image move to the rect than stop on there

CollisionTest again.

i have other question i try to make the image can't move out of the playscreen

One way to do this was shown in DSController of reply 1 of your thread [url=http://forum.java.sun.com/thread.jspa?threadID=5171811]crwood please come(every one can come too)[/url]. See the checkBoundries method.

crwooda at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 5

the part of son't move out of the screen i do this :(i have error)

//playerIcon is image name

private void checkBoundries() {

int w = this.getWidth();

int h = this.getHeight();

if(loc.x + dx < 0 || loc.x + playerIcon.getWidth() + dx > w)

dx *= -1;

if(loc.y + dy < 0 || loc.y + playerIcon.getHeight() + dy > h)

dy *= -1;

}

Downstair.java:192: cannot find symbol

symbol : method getWidth()

location: class javax.swing.ImageIcon

if(loc.x + dx < 0 || loc.x + playerIcon.getWidth() + dx > w)

^

Downstair.java:192: operator + cannot be applied to int,javax.swing.ImageIcon.ge

tWidth

if(loc.x + dx < 0 || loc.x + playerIcon.getWidth() + dx > w)

^

Downstair.java:192: operator + cannot be applied to <nulltype>,int

if(loc.x + dx < 0 || loc.x + playerIcon.getWidth() + dx > w)

^

Downstair.java:192: operator > cannot be applied to <nulltype>,int

if(loc.x + dx < 0 || loc.x + playerIcon.getWidth() + dx > w)

^

Downstair.java:194: cannot find symbol

symbol : method getHeight()

location: class javax.swing.ImageIcon

if(loc.y + dy < 0 || loc.y + playerIcon.getHeight() + dy > h)

^

Downstair.java:194: operator + cannot be applied to int,javax.swing.ImageIcon.ge

tHeight

if(loc.y + dy < 0 || loc.y + playerIcon.getHeight() + dy > h)

^

Downstair.java:194: operator + cannot be applied to <nulltype>,int

if(loc.y + dy < 0 || loc.y + playerIcon.getHeight() + dy > h)

^

Downstair.java:194: operator > cannot be applied to <nulltype>,int

if(loc.y + dy < 0 || loc.y + playerIcon.getHeight() + dy > h)

^

8 errors

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 6

the part of stand on the rect :it have problem too(at the move ball () and haveCollision())

public Playscreen(){

String img = "stair.jpg";

fileNames = new String[10];

playbg = new ImageIcon("image/bgimg.jpg");

playerIcon = new ImageIcon("image/player.gif");

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

for(int f = 0; f < 10; f++){

fileNames[f] = img ;

}

rects = new Rectangle[fileNames.length];

stair = new ImageIcon[fileNames.length];

for(int j = 0; j < rects.length; j++) {

stair[j] = new ImageIcon("Image/" + fileNames[j]);

rects[j] = new Rectangle(stair[j].getIconWidth(), stair[j].getIconHeight());

}

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(playbg.getImage(), 0, 0, this);

g.drawImage(playerIcon.getImage(), loc.x, loc.y, this);

if(firstTime) {

setRects();

firstTime = false;

}

for(int j = 0; j < stair.length; j++) {

g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y, this);

}

}

private void setRects() {

Point p;

for(int j = 0; j < rects.length; j++) {

do {

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

for(int j = 0; j < index; j++) {

if(rects[j].intersects(rects[index]))

return false;

}

return true;

}

private Point getRandomLocationFor(Rectangle r) {

Point p = new Point();

p.x = seed.nextInt(getWidth() - r.width );

p.y = seed.nextInt(getHeight() - r.height);

return p;

}

private void checkBoundries() {

int w = this.getWidth();

int h = this.getHeight();

if(loc.x + dx < 0 || loc.x + playerIcon.getWidth() + dx > w)

dx *= -1;

if(loc.y + dy < 0 || loc.y + playerIcon.getHeight() + dy > h)

dy *= -1;

}

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += playerIcon.x;

y += playerIcon.y;

playerIcon.setFrameFromDiagonal(x, y, x+playerIcon.width, y+playerIcon.height);

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = playerIcon.x + deltaX;

double y = playerIcon.y + deltaY;

return e.intersects(rect[index]);

}

}

Message was edited by:

nickgoldgodl

Message was edited by:

nickgoldgodl

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 7

playIcon.x

x+playerIcon.width

playerIcon.getWidth()

Look up the ImageIcon class in the javadocs. It does not have a getWidth method nor does

it have an x or y field. It does have a getIconWidth method.

Rectangles have (x,y) location and (width,height) size. That's why they are used to locate

the images which have no location information. You can't just go and substitute an

ImageIcon for a Rectangle and expect the code to compile. This takes a lot of care and

attention to detail. If you don't understand what you are doing then start over and build

up slowly. Make one single change and re-compile. If you get compile or run-time errors

you know right away what and where the trouble is: the last change.

Also, the compiler errors give the class, line number and the cause of each error. You

must read these and trace the difficulty to the line to find out what is causing the error

and fix it.

If you don't understand something then play with it, change it and see how it works. Look

up the methods in the javadocs so you can understand what's going on. You should never

move ahead until you understand everything you've done so far.

crwooda at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 8

i want ask what is the getwidth() and getheight of x and y get for?

private void initRect() {

int w = image.getWidth();

int h = image.getHeight();

int x = (getWidth() - w)/2;<========

int y = (getHeight() - h)/2;<=====

rect = new Rectangle(x, y, w, h);

}

and thanks a lots u are right may be i learning too fast .now i will understand first and go to next step.

and i also want to ask what is intersects means?

i can not find it

Is setFrameFromDiagonal() to set a rect for the Shape?

how can i know which object can use that method?

i have fixed the problem of geticonimage.

but i can't know fixed setFrameFromDiagonal()

and e.intersect.

Downstair.java:203: cannot find symbol

symbol : method setFrameFromDiagonal(double,double,double,double)

location: class javax.swing.ImageIcon

playerIcon.setFrameFromDiagonal(x, y, x+playerIcon.getIconWidth(), y

+playerIcon.getIconHeight() );

Message was edited by:

nickgoldgodl

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 9

what is the getwidth() and getheight of x and y get for?

The getWidth and getHeight methods are methods of the Component class. To see this go to

the javadocs [url=http://java.sun.com/j2se/1.5.0/docs/api/index.html]j2se 1.5[/url]. If

you are using the newest version of java, 1.6 or 6, the page is here [url=http://java.sun.com/javase/6/docs/api/]javase 6[/url].

The frame on the left is all classes. Scroll down to the Component class and click the

link. The Component class api will loadf into the main frame. Scroll down to the Method

Summary section and to the getWidth and getHeight methods. You can follow the links to the

Method Detail section for more information. This is how you look up information about

classes, their fields and methods.

int x = (getWidth() - w)/2;

Here the getWidth method is being called inside your Playscreen which extends JPanel which

extends from Component. You can see this class hierarchy for any class at the top of the

class api. There is a ladder of how the class extends from Object.

what is intersects means ... i can not find it

It is a method available in/to the Rectangle class. Look up the Rectangle class in the

javadocs and scroll down to the Method Summary section. Here you find an intersects

method. Farther down you find methods inherited from superclasses and the interface Shape.

All of these inherited methods, methods of Rectangles superclasses are available to

Rectangle. The RectangularShape class has a lot of useful methods.

Is setFrameFromDiagonal() to set a rect for the Shape?

how can i know which object can use that method?

You will find this in the RectangularShape class. It is available to any class that

extends RectangularShape. At the top of the RectangularShape class api is a header "Direct

Known Subclasses" and under it are the classes that can use this method.

Downstair.java:203: cannot find symbol

symbol : method setFrameFromDiagonal(double,double,double,double)

location: class javax.swing.ImageIcon

playerIcon.setFrameFromDiagonal(x, y, x+playerIcon.getIconWidth(), y

+playerIcon.getIconHeight() );

You can look up the ImageIcon class and see what methods are listed and available to it.

In the code that uses a Rectangle to test for intersections, boundry-checking and image

location, the rectangle(s) is what uses these "setFrameXXX" methods. The image is simply

drawn at the origin (x,y) of the rectangle after it is placed in the app.

In the haveCollision method of CollisionTest class an Ellipse2D.Double is used because we

are doing collision detection for a ball.

Ellipse2D.Double e = new Ellipse2D.Double(x, y, ball.width, ball.height);

return e.intersects(rect);

In your code you are doing collision detection for playerIcon which you can use a

Rectangle for.

// Use this to locate the playerIcon.

Rectangle playerRect = new Rectangle(playerIcon.getIconWidth(),

playerIcon.getIconHeight());

...

private void checkBoundries() {

int w = this.getWidth();// width/height of this component,

int h = this.getHeight(); // the enclosing class, a JPanel

if(loc.x + dx < 0 || loc.x + playerRect.width + dx > w)

dx *= -1;

if(loc.y + dy < 0 || loc.y + playerRect.height + dy > h)

dy *= -1;

}

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += playerIcon.x;

y += playerIcon.y;

playerRect.setFrameFromDiagonal(x, y, x+playerRect.width,

y+playerRect.height);

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = playerRect.x + deltaX;

double y = playerRect.y + deltaY;

// Loop through your stair rectangles and see if the playerRect

// is intersecting (piercing) any of them. If so you have a

// collision.

for(int j = 0; j < stair.length; j++) {

if(playerRect.intersects(stair[j]))

return true;// collision!

}

return false;

}

crwooda at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 10

this my code i have no error but i can not run why?

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Ellipse2D;

import java.awt.image.BufferedImage;

import javax.swing.*;

import javax.swing.event.*;

import java.util.Random;

public class Downstair {

Playscreen playScreen;

Pseudo pseudo;

JPanel rightPanel;

private JPanel getCenterPanel() {

playScreen = new Playscreen();

pseudo = new Pseudo();

// Layout right panel.

rightPanel = new JPanel(new CardLayout());

rightPanel.add("Menu", getMenuPanel());

rightPanel.add("Game", playScreen);

// Layout center panel.

JPanel centerPanel = new JPanel(new BorderLayout());

centerPanel.add(pseudo,BorderLayout.LINE_START);

centerPanel.add(rightPanel, BorderLayout.CENTER);

return centerPanel;

}

private JPanel getMenuPanel() {

// Create components.

String[] gameMenulist = {"New Game","Abouts","how to play","Options","Exit"};

JList menulist= new JList(gameMenulist);

ListSelectionModel menulistModel = menulist.getSelectionModel();

//menulist setting

menulist.setLayoutOrientation(JList.HORIZONTAL_WRAP);

menulist.setVisibleRowCount(-1);

menulist.setBackground(Color.BLACK);

menulist.setForeground(Color.WHITE);

menulist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

menulist.addListSelectionListener(new ListListener());

JPanel panel = new JPanel() {

Image bg = new ImageIcon("image/bgimg.jpg").getImage();

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(bg, 0, 0, this);

}

};

panel.setBackground(Color.white);

panel.setOpaque(true); // default value

panel.setLayout(new GridBagLayout());

GridBagConstraints a = new GridBagConstraints();

// The anchor constraint requires a non-zero weight

// constraint in the direction it is going, ie,

// weightx for horizontal values such as EAST,

// WEST, LINE_START, LINE_END.

a.anchor = GridBagConstraints.PAGE_END;

panel.add(menulist, a);

return panel;

}

public static void main(String[] args) {

Downstair app = new Downstair();

JFrame mainframe = new JFrame();

mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

mainframe.getContentPane().add(app.getCenterPanel());

mainframe.setSize(600, 600);

mainframe.setVisible(true);

}

private class ListListener implements ListSelectionListener {

public void valueChanged(ListSelectionEvent e) {

if(!e.getValueIsAdjusting()) {

JList list = (JList)e.getSource();

int index = list.getSelectedIndex();

switch(index) {

case 0:

CardLayout cards = (CardLayout)rightPanel.getLayout();

cards.show(rightPanel, "Game");

break;

case 4:

System.exit(0);

break;

default:

System.out.println("unexpected type: " + index);

}

}

}

}

}

class Playscreen extends JPanel {

ImageIcon playbg;

ImageIcon playerIcon;

ImageIcon[] stair;

Point loc = new Point(100,100);

int dx = 3;

int dy = 3;

Rectangle[] rects;

Random seed = new Random();

String[] fileNames;

boolean firstTime = true;

Rectangle playerRect = new Rectangle(playerIcon.getIconWidth(),

playerIcon.getIconHeight());

Rectangle rect;

public Playscreen(){

String img = "stair.jpg";

fileNames = new String[10];

playbg = new ImageIcon("image/bgimg.jpg");

playerIcon = new ImageIcon("image/player.gif");

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

for(int f = 0; f < 10; f++){

fileNames[f] = img ;

}

rects = new Rectangle[fileNames.length];

stair = new ImageIcon[fileNames.length];

for(int j = 0; j < rects.length; j++) {

stair[j] = new ImageIcon("Image/" + fileNames[j]);

rects[j] = new Rectangle(stair[j].getIconWidth(), stair[j].getIconHeight());

}

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(playbg.getImage(), 0, 0, this);

g.drawImage(playerIcon.getImage(), loc.x, loc.y, this);

if(firstTime) {

setRects();

firstTime = false;

}

for(int j = 0; j < stair.length; j++) {

g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y, this);

}

}

private void setRects() {

Point p;

for(int j = 0; j < rects.length; j++) {

do {

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

for(int j = 0; j < index; j++) {

if(rects[j].intersects(rects[index]))

return false;

}

return true;

}

private Point getRandomLocationFor(Rectangle r) {

Point p = new Point();

p.x = seed.nextInt(getWidth() - r.width );

p.y = seed.nextInt(getHeight() - r.height);

return p;

}

private void checkBoundries() {

int w = this.getWidth();// width/height of this component,

int h = this.getHeight(); // the enclosing class, a JPanel

if(loc.x + dx < 0 || loc.x + playerRect.width + dx > w)

dx *= -1;

if(loc.y + dy < 0 || loc.y + playerRect.height + dy > h)

dy *= -1;

}

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += loc.x;

y += loc.y;

playerRect.setFrameFromDiagonal(x, y, x+playerRect.width,

y+playerRect.height);

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = playerRect.x + deltaX;

double y = playerRect.y + deltaY;

// Loop through your stair rectangles and see if the playerRect

// is intersecting (piercing) any of them. If so you have a

// collision.

for(int j = 0; j < stair.length; j++) {

if(playerRect.intersects(rects[j]))

return true;// collision!

}

return false;

}

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, -1);

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(-1, 0);

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, 1);

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(1, 0);

}

};

}

class Pseudo extends JPanel {

int floornum = 0;

int lifenum = 0;

JLabel floor = new JLabel("Floor" +" "+ floornum);

JLabel life = new JLabel("Life" +" "+ lifenum);

public Pseudo() {

setPreferredSize(new Dimension(100,100));

setBackground(Color.BLACK);

setForeground(Color.WHITE);

add(floor);

add(life);

}

public Dimension getPreferredSize() {

return new Dimension(100,100);

}

}

Exception in thread "main" java.lang.NullPointerException

at Playscreen.<init>(Downstair.java:117)

at Downstair.getCenterPanel(Downstair.java:18)

at Downstair.main(Downstair.java:77)

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 11

Exception in thread "main" java.lang.NullPointerException

at Playscreen.<init>(downstair.java:117)

at Downstair.getCenterPanel(downstair.java:18)

at Downstair.main(downstair.java:77)

Something on line number 117 in your application is null. So find line 117. Scroll down to

approximately where you think it might be and type a slash in the left edge of the file.

Save and re-compile. The compiler will tell you what line the out-of-place symbol is on.

You repaeat this till close and then count up or down to find line 117.

Rectangle playerRect = new Rectangle(playerIcon.getIconWidth(),

playerIcon.getIconHeight());

What is null in this line? playerIcon has not yet been instantiated. It has been declared

as a member variable but not instantiated, ie, the variable reference "playerIcon" does

not point to or refer to an object; it is null. This variable, playerRect, should be

instantiated after playerIcon has been instantiated.

ImageIcon playerIcon; // declaration

....

// somewhere later on

playerIcon = new ImageIcon(stringPath);// instantiation

// Now playerIcon points/refers to an object, ie, is not null.

playerRect = new Rectangle(...playerIcon...// okay now

crwooda at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 12

now i have no error can run but now it can't not move the image(playerIcon)...

class Playscreen extends JPanel {

ImageIcon playbg;

ImageIcon playerIcon;

ImageIcon[] stair;

Point loc = new Point(100,100);

int dx = 3;

int dy = 3;

Rectangle[] rects;

Random seed = new Random();

String[] fileNames;

boolean firstTime = true;

Rectangle playerRect;

public Playscreen(){

String img = "stair.jpg";

fileNames = new String[10];

playbg = new ImageIcon("image/bgimg.jpg");

playerIcon = new ImageIcon("image/player.gif");

playerRect = new Rectangle(playerIcon.getIconWidth(),playerIcon.getIconHeight());

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

for(int f = 0; f < 10; f++){

fileNames[f] = img ;

}

rects = new Rectangle[fileNames.length];

stair = new ImageIcon[fileNames.length];

for(int j = 0; j < rects.length; j++) {

stair[j] = new ImageIcon("Image/" + fileNames[j]);

rects[j] = new Rectangle(stair[j].getIconWidth(), stair[j].getIconHeight());

}

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(playbg.getImage(), 0, 0, this);

g.drawImage(playerIcon.getImage(), loc.x, loc.y, this);

if(firstTime) {

setRects();

firstTime = false;

}

for(int j = 0; j < stair.length; j++) {

g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y, this);

}

}

private void setRects() {

Point p;

for(int j = 0; j < rects.length; j++) {

do {

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

for(int j = 0; j < index; j++) {

if(rects[j].intersects(rects[index]))

return false;

}

return true;

}

private Point getRandomLocationFor(Rectangle r) {

Point p = new Point();

p.x = seed.nextInt(getWidth() - r.width );

p.y = seed.nextInt(getHeight() - r.height);

return p;

}

private void checkBoundries() {

int w = this.getWidth();// width/height of this component,

int h = this.getHeight(); // the enclosing class, a JPanel

if(loc.x + dx < 0 || loc.x + playerRect.width + dx > w)

dx *= -1;

if(loc.y + dy < 0 || loc.y + playerRect.height + dy > h)

dy *= -1;

}

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += loc.x;

y += loc.y;

playerRect.setFrameFromDiagonal(x, y, x+playerRect.width, y+playerRect.height);

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = playerRect.x + deltaX;

double y = playerRect.y + deltaY;

// Loop through your stair rectangles and see if the playerRect

// is intersecting (piercing) any of them. If so you have a

// collision.

for(int j = 0; j < rects.length; j++) {

if(playerRect.intersects(rects[j]))

return true;// collision!

}

return false;

}

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, -1);

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(-1, 0);

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, 1);

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(1, 0);

}

};

}

Message was edited by:

nickgoldgodl

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 13

ather question i do this for move image can not go out of the panel but when the image stop i press left arror but it don't not move.

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

if (loc.x < 0){

dx = -1;

repaint();

}else if (loc.x < 300 && loc.x > 0){

loc.x -= dx;

repaint();

}

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

// start this thread

th.start();

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

if (loc.x > 300){

dx = -1;

repaint();

}else if (loc.x < 300 && loc.x > 0){

loc.x += dx;

repaint();

}

}

};

nickgoldgodla at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 14

now i have no error can run but now it can't not move the image(playerIcon)...

The playerRect was not being used for the setRects placement tests. Therefore, one or more

stairs could be placed such that they intersected with playerRect. Then the collision test

would prevent any movement. Add plaerRect to the notTouching method tests.

private boolean notTouching(int index) {

if(playerRect.intersects(rects[index])) // add these

return false;// two lines

for(int j = 0; j < index; j++) {

move image can not go out of the panel but when the image stop i press left arror but

it don't not move.

The playerRect was being tested for collisions with the rects array before it was being

"moved" into the new/prospective position. Changed the test for collision.

private boolean haveCollision(double deltaX, double deltaY) {

// Loop through your stair rectangles and see if playerRect,

// moved to the prospective position, is intersecting any of

// them. If so you have a collision.

for(int j = 0; j < rects.length; j++) {

if(rects[j].intersects(x, y, playerRect.width, playerRect.height)) // <****

return true;// collision!

import java.awt.*;

import java.awt.event.*;

import java.awt.image.BufferedImage;

import java.util.Random;

import javax.swing.*;

public class Playscreen2 extends JPanel {

ImageIcon playbg;

ImageIcon playerIcon;

ImageIcon[] stair;

int dx = 3;

int dy = 3;

Rectangle[] rects;

Random seed = new Random();

String[] fileNames;

boolean firstTime = true;

Rectangle playerRect;

public Playscreen2(BufferedImage image){

String img = "stair.jpg";

fileNames = new String[10];

playbg = new ImageIcon("image/bgimg.jpg");

//"../images/owls.jpg");

playerIcon = new ImageIcon("image/player.gif");

//"../images/Bird.gif");

playerRect = new Rectangle(100, 100,

playerIcon.getIconWidth(),

playerIcon.getIconHeight());

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

for(int f = 0; f < 10; f++){

fileNames[f] = img ;

}

rects = new Rectangle[fileNames.length];

stair = new ImageIcon[fileNames.length];

for(int j = 0; j < rects.length; j++) {

stair[j] = new ImageIcon(image);

rects[j] = new Rectangle(stair[j].getIconWidth(),

stair[j].getIconHeight());

}

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(playbg.getImage(), 0, 0, this);

g.drawImage(playerIcon.getImage(), playerRect.x, playerRect.y, this);

if(firstTime) {

setRects();

firstTime = false;

}

for(int j = 0; j < stair.length; j++) {

g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y, this);

}

}

private void setRects() {

Point p;

for(int j = 0; j < rects.length; j++) {

do {

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

if(playerRect.intersects(rects[index]))

return false;

for(int j = 0; j < index; j++) {

if(rects[j].intersects(rects[index]))

return false;

}

return true;

}

private Point getRandomLocationFor(Rectangle r) {

Point p = new Point();

p.x = seed.nextInt(getWidth() - r.width );

p.y = seed.nextInt(getHeight() - r.height);

return p;

}

/*

private void checkBoundries() {

int w = this.getWidth();// width/height of this component,

int h = this.getHeight(); // the enclosing class, a JPanel

if(playerRect.x + dx < 0 || playerRect.x + playerRect.width + dx > w)

dx *= -1;

if(playerRect.y + dy < 0 || playerRect.y + playerRect.height + dy > h)

dy *= -1;

}

*/

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += playerRect.x;

y += playerRect.y;

// Update playerRect.

playerRect.setFrameFromDiagonal(x, y, x+playerRect.width,

y+playerRect.height);

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = playerRect.x + deltaX;

double y = playerRect.y + deltaY;

// Loop through your stair rectangles and see if playerRect,

// moved to the prospective position, is intersecting any of

// them. If so you have a collision.

for(int j = 0; j < rects.length; j++) {

if(rects[j].intersects(x, y, playerRect.width, playerRect.height))

return true;// collision!

}

return false;

}

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, -1);

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(-1, 0);

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, 1);

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(1, 0);

}

};

public static void main(String[] args) {

int type = BufferedImage.TYPE_INT_RGB;

BufferedImage image = new BufferedImage(85, 15, type);

Graphics2D g2 = image.createGraphics();

g2.setBackground(Color.blue);

g2.clearRect(0,0,86,15);

g2.dispose();

Playscreen2 app = new Playscreen2(image);

JFrame mainframe = new JFrame();

mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

mainframe.getContentPane().add(app);

mainframe.setSize(600, 600);

mainframe.setVisible(true);

}

}

crwooda at 2007-7-12 9:40:01 > top of Java-index,Security,Cryptography...
# 15

i add the top two line but it still can't not move.

now i can move left and rigth back but i have ather problem.i make a theard to fall down but when it stop on the rect. i press left go to the place no rect under it. it still stop .how can i make it continuous when it walk out of the rects

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

if(loc.x > 0 ){

loc.x -= dx;

repaint();

}

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

// start this thread

th.start();

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

if(loc.x + playerIcon.getIconWidth() < 500){

loc.x += dx;

repaint();

}

}

};

public void run(){

// lower ThreadPriority

Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

// run a long while (true) this means in our case "always"

while (true){

for(int j = 0; j < rects.length; j++){

if (loc.y + playerIcon.getIconHeight() > 550 || loc.y + playerIcon.getIconHeight() == rects[j].y && loc.x > rects[j].x && loc.x + playerIcon.getIconWidth() < rects[j].x + stair[j].getIconWidth()){

th.stop();

}

}

loc.y += dy;

// repaint the image

repaint();

try {

// Stop thread for 20 milliseconds

Thread.sleep (50);

}catch (InterruptedException ex){ // do nothing }

// set ThreadPriority to maximum value

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

}

}

}

nickgoldgodla at 2007-7-21 21:07:58 > top of Java-index,Security,Cryptography...
# 16

here is my code can't move image

class Playscreen extends JPanel {

ImageIcon playbg;

ImageIcon playerIcon;

ImageIcon[] stair;

Point loc = new Point(100,100);

int dx = 3;

int dy = 3;

Rectangle[] rects;

Random seed = new Random();

String[] fileNames;

boolean firstTime = true;

Rectangle playerRect;

public Playscreen(){

String img = "stair.jpg";

fileNames = new String[10];

playbg = new ImageIcon("image/bgimg.jpg");

playerIcon = new ImageIcon("image/player.gif");

playerRect = new Rectangle(playerIcon.getIconWidth(),playerIcon.getIconHeight());

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

for(int f = 0; f < 10; f++){

fileNames[f] = img ;

}

rects = new Rectangle[fileNames.length];

stair = new ImageIcon[fileNames.length];

for(int j = 0; j < rects.length; j++) {

stair[j] = new ImageIcon("Image/" + fileNames[j]);

rects[j] = new Rectangle(stair[j].getIconWidth(), stair[j].getIconHeight());

}

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawImage(playbg.getImage(), 0, 0, this);

g.drawImage(playerIcon.getImage(), loc.x, loc.y, this);

if(firstTime) {

setRects();

firstTime = false;

}

for(int j = 0; j < stair.length; j++) {

g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y, this);

}

}

private void setRects() {

Point p;

for(int j = 0; j < rects.length; j++) {

do {

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

if(playerRect.intersects(rects[index]))

return false;

for(int j = 0; j < index; j++) {

if(rects[j].intersects(rects[index]))

return false;

}

return true;

}

private Point getRandomLocationFor(Rectangle r) {

Point p = new Point();

p.x = seed.nextInt(getWidth() - r.width );

p.y = seed.nextInt(getHeight() - r.height);

return p;

}

private void checkBoundries() {

int w = this.getWidth();// width/height of this component,

int h = this.getHeight(); // the enclosing class, a JPanel

if(loc.x + dx < 0 || loc.x + playerRect.width + dx > w)

dx *= -1;

if(loc.y + dy < 0 || loc.y + playerRect.height + dy > h)

dy *= -1;

}

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += loc.x;

y += loc.y;

playerRect.setFrameFromDiagonal(x, y, x+playerRect.width, y+playerRect.height);

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = playerRect.x + deltaX;

double y = playerRect.y + deltaY;

// Loop through your stair rectangles and see if the playerRect

// is intersecting (piercing) any of them. If so you have a

// collision.

for(int j = 0; j < rects.length; j++) {

if(playerRect.intersects(rects[j]))

return true;// collision!

}

return false;

}

private void registerKeys() {

int c = JComponent.WHEN_IN_FOCUSED_WINDOW;

getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");

getActionMap().put("UP", upAction);

getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");

getActionMap().put("LEFT", leftAction);

getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");

getActionMap().put("DOWN", downAction);

getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");

getActionMap().put("RIGHT", rightAction);

}

private Action upAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, -1);

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(-1, 0);

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(0, 1);

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

moveBall(1, 0);

}

};

}

nickgoldgodla at 2007-7-21 21:07:58 > top of Java-index,Security,Cryptography...