problem for drawimage

i want to draw a image random and they are not stick together but i try that code it only have one image show up.how to do draw a image and they are not stick together too?

and i have one more question how to make a image stand on other image . because i want to make a person walk on a floor.

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Ellipse2D;

import java.awt.image.BufferedImage;

import javax.swing.*;

import javax.swing.event.*;

publicclass Downstair{

Playscreen graphicComponent;

JPanel centerPanel;

private JPanel getCenterPanel(){

graphicComponent =new Playscreen();

CardLayout cards =new CardLayout();

centerPanel =new JPanel(cards);

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

centerPanel.add("Game", graphicComponent);

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();

protectedvoid 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;

}

publicstaticvoid 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);

}

privateclass ListListenerimplements ListSelectionListener{

publicvoid valueChanged(ListSelectionEvent e){

if(!e.getValueIsAdjusting()){

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

int index = list.getSelectedIndex();

switch(index){

case 0:

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

cards.show(centerPanel,"Game");

break;

case 4:

System.exit(0);

break;

default:

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

}

}

}

}

}

class Playscreenextends JPanel{

ImageIcon playbg;

ImageIcon playerIcon;

ImageIcon[] stair;

int floor;

int live;

int randomX;

int randomY;

int randompic;

public Playscreen(){

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

playerIcon =new ImageIcon("image/ball.gif")[10];

stair =new ImageIcon("image/stair.jpg");

randomX = (int)( ( Math.random() * 400 ) + 1 );

randomY = (int)( ( Math.random() * 400 ) + 1 );

randompic = (int)( ( Math.random() * 10 ) + 10 );

setBackground(Color.white);

setOpaque(true);

}

protectedvoid paintComponent(Graphics g){

super.paintComponent(g);

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

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

g.drawImage(playerIcon.getImage(), randomX, randomY,this);

}

}

}

Message was edited by:

nickgoldgodl

[7510 byte] By [nickgoldgodla] at [2007-11-27 4:12:06]
# 1

import java.awt.*;

import java.awt.event.*;

import java.awt.image.BufferedImage;

import java.io.*;

import java.util.Random;

import javax.imageio.ImageIO;

import javax.swing.*;

public class ImageIdeas extends JPanel implements ActionListener {

BufferedImage[] images;

Rectangle[] locators;

Random seed = new Random();

boolean showNonStick = true;

boolean firstTime = true;

public ImageIdeas(BufferedImage[] images) {

this.images = images;

locators = new Rectangle[images.length];

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

locators[j] = new Rectangle(images[j].getWidth(), images[j].getHeight());

}

public void advance() {

if(showNonStick) {

pickNonStickLocations();

} else {

Point p = getRandomLocationFor(locators[1]);

locators[1].setLocation(p);

}

repaint();

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

if(firstTime) {

pickNonStickLocations();

firstTime = false;

}

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

g.drawImage(images[j], locators[j].x, locators[j].y, this);

}

}

private void pickNonStickLocations() {

Point p = getRandomLocationFor(locators[0]);

locators[0].setLocation(p);

do {

p = getRandomLocationFor(locators[1]);

locators[1].setLocation(p);

} while(!notTouching(p));

}

private boolean notTouching(Point p) {

return !locators[0].intersects(locators[1]);

}

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;

}

public void actionPerformed(ActionEvent e) {

String ac = e.getActionCommand();

if(ac.equals("NON-STICK")) {

showNonStick = true;

} else {

showNonStick = false;

// Center the Bird while the Cat moves around.

locators[0].x = (getWidth() - locators[0].width)/2;

locators[0].y = (getHeight() - locators[0].height)/2;

}

}

private JPanel getUIPanel() {

String[] ids = { "non-stick", "move over background" };

ButtonGroup group = new ButtonGroup();

JPanel panel = new JPanel();

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

JRadioButton rb = new JRadioButton(ids[j], j==0);

rb.setActionCommand(ids[j].toUpperCase());

rb.addActionListener(this);

group.add(rb);

panel.add(rb);

}

return panel;

}

public static void main(String[] args) throws IOException {

String[] ids = { "Bird.gif", "Cat.gif" };

BufferedImage[] images = new BufferedImage[ids.length];

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

images[j] = ImageIO.read(new File("images/" + ids[j]));

ImageIdeas ideas = new ImageIdeas(images);

new AnimationController(ideas);

JFrame f = new JFrame("Click to start/stop");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(ideas);

f.getContentPane().add(ideas.getUIPanel(), "Last");

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

class AnimationController implements Runnable {

ImageIdeas imageIdeas;

Thread thread;

boolean running = false;

final int DELAY = 1000;

AnimationController(ImageIdeas imageIdeas) {

this.imageIdeas = imageIdeas;

imageIdeas.addMouseListener(ml);

}

public void run() {

while(running) {

try {

Thread.sleep(DELAY);

} catch(InterruptedException e) {

stop();

}

imageIdeas.advance();

}

}

private MouseListener ml = new MouseAdapter() {

public void mousePressed(MouseEvent e) {

if(running)

stop();

else

start();

}

};

private void start() {

if(!running) {

running = true;

thread = new Thread(this);

thread.setPriority(Thread.NORM_PRIORITY);

thread.start();

}

}

private void stop() {

running = false;

if(thread != null)

thread.interrupt();

thread = null;

}

}

Images found near the bottom of this page: [url=http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html]Using Swing Components Examples[/url].

crwooda at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 2
i think my word not clearly say what i want.i want to random draw a same image ,but not stick.
nickgoldgodla at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 3
but not stick.I thought this meant that the images were not to touch one another. Do you mean instead that the image never stops moving?
crwooda at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 4

i means that is draw 10 same image maybe more on the jframe screen but the place is random.also there will no image over the other.

here is my purpose:

click newgame go to the page like this:

<a href="http://photobucket.com" target="_blank"><img src="http://i104.photobucket.com/albums/m173/finalmilk/stairgame.jpg" border="0" alt="Photo Sharing and Video Hosting at Photobucket"></a>

and the RECTimage is random draw and the ball can move and it can stand on the RECT.

i know how to move form your post .

thanks very much .

Message was edited by:

nickgoldgodl

Message was edited by:

nickgoldgodl

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

means that is draw 10 same image maybe more on the jframe screen but the place is

random.also there will no image over the other...and the RECTimage is random draw

Okay. I can show this.

and the ball can move ... i know how to move form your post

Okay.

and it can stand on the RECT

This part I may not understand. By "stand on" do you mean that the ball can be drawn

between an image/rectangle and the viewer's eye, ie, appear to be laying_on/moving_over

the flat surface of the image? If so then you draw the rectangle/image first and the ball

last. The ball will not go out of view when it occupies the same screen space as one of

the rectangle/images. If this is not what you mean then I do not understand.

About the method setRects: If there are too many rectangles or if they are too big

or if the graphic component is too small this method may not be able to find a legal

location for one of the rectangles.

import java.awt.*;

import java.awt.event.*;

import java.util.Random;

import javax.swing.*;

public class ImageIdeas extends JPanel implements ActionListener {

Rectangle[] rects;

Random seed = new Random();

boolean firstTime = true;

public ImageIdeas() {

rects = new Rectangle[5];

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

rects[j] = new Rectangle(75, 75);

}

public void advance() {

setRects();

repaint();

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

if(firstTime) {

setRects();

firstTime = false;

}

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

g2.draw(rects[j]);

}

}

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;

}

public void actionPerformed(ActionEvent e) {

setRects();

repaint();

}

private JPanel getUIPanel() {

JButton button = new JButton("Test");

button.addActionListener(this);

JPanel panel = new JPanel();

panel.add(button);

return panel;

}

public static void main(String[] args) {

ImageIdeas ideas = new ImageIdeas();

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(ideas);

f.getContentPane().add(ideas.getUIPanel(), "Last");

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

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

i try to change your code to draw image but it doesn't work.

import java.awt.*;

import java.awt.event.*;

import java.util.Random;

import javax.swing.*;

public class ImageIdeas extends JPanel implements ActionListener {

Rectangle[] rects;

Random seed = new Random();

boolean firstTime = true;

ImageIcon[] ok;

public ImageIdeas() {

rects = new Rectangle[5];

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

ok[j] = new ImageIcon("/Image/ok.jpg");

}

public void advance() {

setRects();

repaint();

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

if(firstTime) {

setRects();

firstTime = false;

}

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

g2.draw(ok[j]);

}

}

private void setRects() {

Point p;

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

do {

p = getRandomLocationFor(rects[j]);

ok[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

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

if(ok[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;

}

public void actionPerformed(ActionEvent e) {

setRects();

repaint();

}

private JPanel getUIPanel() {

JButton button = new JButton("Test");

button.addActionListener(this);

JPanel panel = new JPanel();

panel.add(button);

return panel;

}

public static void main(String[] args) {

ImageIdeas ideas = new ImageIdeas();

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(ideas);

f.getContentPane().add(ideas.getUIPanel(), "Last");

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

Message was edited by:

nickgoldgodl

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

public ImageIdeas() {

// Create an array of your image file names to load.

String[] fileNames = { "ok.jpg", ... };

// Instantiate the rects array.

rects = new Rectangle[fileNames.length];

// Instantiate the ok array.

ok = new ImageIcon[fileNames.length];

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

// Instantiate the elements of the ok array.

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

// We still need to instantiate the elements of the rects array.

// We use these to locate the images for drawing and for checking

// for boundry violations and rectangle intersections during the

// process of re-locating the rects in the setRects method.

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

}

}

...

protected void paintComponent(Graphics g) {

...

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

// g2.draw(Shape s) will take a Rectangle as an argument.

// To draw an image we use a different method.

g2.drawImage(ok[j], 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]);

// ImageIcon does not have a setLocation method.

// Rectangle does. We're using the rectangle to

// locate the image.

rects[j].setLocation(p);

} while(!notTouching(j));

}

}

private boolean notTouching(int index) {

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

// ImageIcon does not have an intersects method.

// Rectangle does. We use rectangles because we

// can test them for things like intersections.

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

return false;

}

return true;

}

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

thanks a lot i can do this now but i have ather question will the image draw out of the jframe?

and do you know how to onw image stand on ather image. i means that the move image can not cross over the other image . (eg.imgae block the move image)

may be i ask you how to make a image when i press space bar and it dropdown until have other image block it and stand on it

and how to add one more panel at the left side?

class Playscreen extends 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;

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);

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());

}

}

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 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) {

loc.y -= dy;

repaint();

}

};

private Action leftAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

loc.x -= dx;

repaint();

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

loc.y += dy;

repaint();

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

loc.x += dx;

repaint();

}

};

}

i have add

JPanel lifescreen = new JPanel();

add(lifescreen);

in playscreen(){}

there is no error but nothing happened too.

Message was edited by:

nickgoldgodl

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

thanks a lot i can do this now but i have ather question will the image draw out of the

jframe?

No.

and do you know how to onw image stand on ather image. i means that the move image can

not cross over the other image . (eg.imgae block the move image)

Yes. This brings up the subject of collision detection. You can search for examples in

this forum, the games forum and via Google. See simple example below.

may be i ask you how to make a image when i press space bar and it dropdown until have

other image block it and stand on it

Better to use the arrow keys because the space bar is used to select/press buttons in a

gui. If you do bind the space bar you may have to remove its bindings in ancestor input

maps - see tutorial for details.

and how to add one more panel at the left side

have add

JPanel lifescreen = new JPanel();

add(lifescreen);

in playscreen(){}

there is no error but nothing happened too.

The default layout manager for JPanel is Flowlayout which tries to show its child

components at their preferred size. The preferred siae of a JPanel is calculated by its

layout manager after checking the preferred size of each of the children it is given to

layout. If there are no components and no size hints have been provided the panel is shown

at its default size which is 10, 10. To provide a size hint you can call setPreferredSize

on the panel or override the getPreferredSize method inside the class - like this:

class Pseudo extends JPanel {

public Pseudo() {

setPreferredSize(new Dimension(100,100));

}

public Dimension getPreferredSize() {

return new Dimension(100,100);

}

}

Use one or the other but not both.

Another option is to have another panel with BorderLayout, add your graphic component to

its center and add your extra panel, lifescreen to the west section. Add this panel to

your frames center section.

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Ellipse2D;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class CollisionTest extends JPanel {

BufferedImage image;

Rectangle rect;

Ellipse2D.Double ball = new Ellipse2D.Double(75, 100, 30,30);

int dx = 2;

int dy = 2;

public CollisionTest(BufferedImage image) {

this.image = image;

registerKeys();

}

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

if(rect == null)

initRect();

g2.drawImage(image, rect.x, rect.y, this);

g2.setPaint(Color.red);

g2.fill(ball);

}

private void moveBall(int xInc, int yInc) {

double x = xInc*dx;

double y = yInc*dy;

if(!haveCollision(x, y)) {

x += ball.x;

y += ball.y;

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

repaint();

} else {

Toolkit.getDefaultToolkit().beep();

}

}

private boolean haveCollision(double deltaX, double deltaY) {

double x = ball.x + deltaX;

double y = ball.y + deltaY;

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

return e.intersects(rect);

}

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);

}

public static void main(String[] args) throws IOException {

String path = "images/Bird.gif";

BufferedImage image = ImageIO.read(new File(path));

CollisionTest test = new CollisionTest(image);

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(test);

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

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) {

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);

}

};

}

crwooda at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 10
i try to understand your code i can display the panel but i want the new panel on the left side and the playing panel on the rightside(the panel of the image random) but i have done is the new panel cover the playing panel.
nickgoldgodla at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 11

Earlier you had

Playscreen playScreen = new Playscreen();

frame.add(playScreen, "Center");

Now try it like this

Playscreen playScreen = new Playscreen();

LeftPanel leftPanel = new LeftPanel();

JPanel parentPanel = new JPanel(new BorderLayout());

parentPanel.add(leftPanel, "West");

parentPanel.add(playScreen, "Center");

frame.add(parentPanel, "Center");

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

i try this code i add a new class for leftpanel and add the playscreen panel and new leftpanel to a new panel it no error but can not run.

public class Downstair {

Playscreen graphicComponent;

JPanel centerPanel;

Pseudo graphicComponent2;

JPanel centerPanel2;

private JPanel getCenterPanel() {

graphicComponent = new Playscreen();

CardLayout cards = new CardLayout();

graphicComponent2 = new Pseudo();

centerPanel = new JPanel(cards);

centerPanel2 = new JPanel(new BorderLayout());

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

centerPanel.add("Game", centerPanel2);

centerPanel2.add(graphicComponent2, BorderLayout.LINE_START);

centerPanel2.add(graphicComponent, BorderLayout.LINE_END);

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)centerPanel.getLayout();

cards.show(centerPanel, "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;

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;

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);

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());

}

}

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 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) {

loc.x -= dx;

repaint();

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

loc.x += dx;

repaint();

}

};

}

class Pseudo extends JPanel {

JButton ok = new JButton();

public Pseudo() {

setPreferredSize(new Dimension(100,100));

add(ok);

}

public Dimension getPreferredSize() {

return new Dimension(100,100);

}

}

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

fileNames = new String[20];

20 images is a lot for this small space.

Recall one of comments from reply 5:

About the method setRects: If there are too many rectangles or if they are too big

or if the graphic component is too small this method may not be able to find a legal

location for one of the rectangles.

What this means is this: if an acceptable location cannot be found for any of the rects

(which are used to place the images) your app will freeze while setRect goes on in an

infinite loop.

import java.awt.*;

import java.awt.event.*;

import java.util.Random;

import javax.swing.*;

import javax.swing.event.*;

public class Downstair {

Playscreen playScreen;

Pseudo pseudo;

JPanel rightPanel;

private JPanel getCenterPanel() {

// Instantiate components.

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();

"images/geek--.gif").getImage();

protected void paintComponent(Graphics g) {

super.paintComponent(g);

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

}

};

panel.setBackground(Color.white);

panel.setOpaque(true);

panel.setLayout(new GridBagLayout());

GridBagConstraints a = new GridBagConstraints();

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.pack();

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;

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;

public Playscreen(){

String img = //"stair.jpg";

"../images/geek--.gif";

fileNames = new String[5];

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

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

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

"../images/Cat.gif");

setBackground(Color.white);

setOpaque(true);

registerKeys();

setFocusable(true);

for(int f = 0; f < fileNames.length; 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]);

"../images/" + 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);

}

}

public Dimension getPreferredSize() {

return new Dimension(600,500);

}

private void setRects() {

Point p;

int count = 0;

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

do {

p = getRandomLocationFor(rects[j]);

rects[j].setLocation(p);

System.out.println("count for " + j + " = " + count++);

} 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 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) {

loc.x -= dx;

repaint();

}

};

private Action downAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

}

};

private Action rightAction = new AbstractAction() {

public void actionPerformed(ActionEvent e) {

loc.x += dx;

repaint();

}

};

}

class Pseudo extends JPanel {

JButton ok = new JButton("Okay");

public Pseudo() {

setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();

gbc.gridwidth = GridBagConstraints.REMAINDER;

add(new JLabel("Pseudo Panel", JLabel.CENTER), gbc);

gbc.weighty = 1.0;

add(ok, gbc);

setBorder(BorderFactory.createLineBorder(Color.red));

}

public Dimension getPreferredSize() {

return new Dimension(200,100);

}

}

crwooda at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 14
i can do it now thatnk but how to set the left panel veiw size?
nickgoldgodla at 2007-7-12 9:18:01 > top of Java-index,Security,Cryptography...
# 15

As given before. Specify the desired size in this method. Since this component is going into

the West section of a BorderLayout only the width part is important. The height of the

component will be expanded to fill the available vertical space. See the comments in the

BorderLayout api for details.

public Dimension getPreferredSize() {

return new Dimension(200,100);

}

crwooda at 2007-7-21 21:03:18 > top of Java-index,Security,Cryptography...
# 16
thanks very much crwood if you not here i will don't know what i can do because i am using this for my school project,
nickgoldgodla at 2007-7-21 21:03:18 > top of Java-index,Security,Cryptography...