Jump to content

Java: Need help with while(true) in canvas of game

Go to solution Solved by fizzlesticks,
run:Entering drawFrame();actionPerformed();actionPerformed();actionPerformed();actionPerformed();

I now edited the obj declarations to public so I can access them everywhere.

And I did what you said, here the newest Version so far: http://pastebin.com/yU7850tM

 

However, as you can see above, he doesn't access the paintComponent()...

 

You got rid of your draw object, you still need one of those. Change the definition of canvas to

JPanel canvas = new drawObjects();

We are programming pinball and have a problem with the draw of the objects in canvas.

 

How it works:

We get frame_drawSizeX and frame_drawSizeY from our Config Menu, and draw the Frame with it's basic contents: the menu bar and a panel canvas in which we want to draw everything of the game itself.

public void drawFrame(int frame_drawSizeX, int frame_drawSizeY)    {        System.out.println("Entering drawFrame();");               //Create new GUI        //<editor-fold defaultstate="collapsed" desc=" Declaration and Definition of JFrame ">        JFrame game = new JFrame();         game.setType(Window.Type.UTILITY);        game.setResizable(false);        game.setSize(frame_drawSizeX, frame_drawSizeY);        game.setLocationRelativeTo(null);        game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        game.setVisible(true);        //</editor-fold>         //Creates a menubar for a JFrame        JMenuBar menuBar = new JMenuBar();         //Add the menubar to the frame        game.setJMenuBar(menuBar);         //Define and add dropdown menus to the menubar        JMenu returnToMenu = new JMenu("Return to Menu");        JMenu pointCounter = new JMenu("Your Points: 0");        JMenu liveCounter = new JMenu("Remaining Lives: 3");        JMenu levelCounter = new JMenu("Level: 0");         //Make them visible:        menuBar.add(returnToMenu);        menuBar.add(pointCounter);        menuBar.add(liveCounter);        menuBar.add(levelCounter);               JPanel canvas = new JPanel();        game.add(canvas);               canvas.add(draw);        draw.repaint();    }

Then we start with drawing the needed objects.

//Creates the Object canvas    drawObjects draw = new drawObjects();

If we run this program through, it launches without any problems but doesn't display any Objects which should be drawn by entering drawObjects() - Yes, it enters paintCompnent().

// Drawing objects    class drawObjects extends JPanel    {                   @[member='override2299']        protected void paintComponent(Graphics g)        {            System.out.println("Entering paintComponent();");                       g.setColor(Color.BLACK);                       //g draws ball            g.fillOval(ball_posX, ball_posY, ball_radius*2, ball_radius*2);                       //g draws paddle            g.fillRect(paddle_posX, paddle_posY, paddle_width, paddle_height);        }    }

But we want to draw it permanetly, so a while(true) must be programmed in drawFrame():

while(true)        {            canvas.add(draw);            draw.repaint();        }

However, since this while(true) is implemented, the program doesn't even draw anything if you start it! Instead of the normal UI with a Menu, it displays the Frameborder and a white background.

 

 

Our question is how can we solve this problem?

Here is the whole code: http://pastebin.com/izC536Td

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Well,that's one way of doing it.I usually use sprites,spritesheets and such.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

Well,that's one way of doing it.I usually use sprites,spritesheets and such.

 

We learned it this way in school, so for me there is no other way. (because we have to use the learnt mechanics)

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

We learned it this way in school, so for me there is no other way. (because we have to use the learnt mechanics)

Oh. :D

Also,remember,after you draw something you have to clear.

 

Do you actually have the drawObjects() constructor/method,(or wait,is it repaint()?) in your drawObjects class?

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

Oh. :D

Also,remember,after you draw something you have to clear.

 

Do you actually have the drawObjects() constructor/method,(or wait,is it repaint()?) in your drawObjects class?

 

Clear: Funny thing, we did this game once before (very bad quality) and we never had to clear the panel :huh:

 

I have no constructor in the drawObjects class, why should I need one? For calling paintComponent()?

 

Edit: paintComponent can't be called...

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

 

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

@Clear17Mud: Funny thing, we did this game once before (very bad quality) and we never had to clear the panel :huh:

 

I have no constructor in the drawObjects class, why should I need one? For calling paintComponent()?

No,but I can't see where you're calling paintComponent();.

I only see draw.repaint();  I could be partially blind though.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

No,but I can't see where you're calling paintComponent();.

I only see draw.repaint();  I could be partially blind though.

 

You are 100% right, I haven't called paintComponent yet :D

 

But what should I add to it? I need a Graphics g object...

(NULL won't work as you get a NullPointerExc. if launching...)

while(true)        {            canvas.add(draw);            draw.paintComponent(null);            draw.repaint();        }

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Does drawing work without the while(true)?

 

Java does stuff behind the scenes that will never be called properly with an infinite loop there.

 

Edit: also doesn't repaint automatically call the paintComponent method of each object inside of it?

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

As you have stated, you need to pass the Graphics of your panel to your drawObjects. I've done something similar except I didn't need to add my class and it also did not have to extend to JPanel that draws things.

public class DrawManager {   private void drawAll(Graphics g){      ...   }   ...}

Have this function call all of your drawing functions in the class. Then you would call it in the repaint using (assuming that DrawManager's variable is called drawer)

 

drawer.drawAll(g);

Its the way I did it, but I'm not too sure how great it is. If you have questions, I might be able to add more after I get to work

 

EDIT: I'm pretty sure the problem is the fact that your using two different JPanels inside each other. I'm not too sure how that exactly works, since each panel has their own graphics and I'm not too sure of whether drawing on lower one will show anything.

Link to comment
Share on other sites

Link to post
Share on other sites

Does drawing work without the while(true)?

 

Java does stuff behind the scenes that will never be called properly with an infinite loop there.

 

Edit: also doesn't repaint automatically call the paintComponent method of each object inside of it?

 

No, the Frame is displayed but no drawing happens.

 

At edit: what?

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

No, the Frame is displayed but no drawing happens.

 

At edit: what?

Calling jpanel.repaint() (same with any other swing element) should call your paintComponent method. You should never call paintComponent, it's something swing handles.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

As you have stated, you need to pass the Graphics of your panel to your drawObjects. I've done something similar except I didn't need to add my class and it also did not have to extend to JPanel that draws things.

public class DrawManager {   private void drawAll(Graphics g){      ...   }   ...}

Have this function call all of your drawing functions in the class. Then you would call it in the repaint using (assuming that DrawManager's variable is called drawer)

 

drawer.drawAll(g);

Its the way I did it, but I'm not too sure how great it is. If you have questions, I might be able to add more after I get to work

 

EDIT: I'm pretty sure the problem is the fact that your using two different JPanels inside each other. I'm not too sure how that exactly works, since each panel has their own graphics and I'm not too sure of whether drawing on lower one will show anything.

 

In my Project, this class is called drawObjects extends JPanel.

However, I have a protected void which could lead to problems(?)...

 

At edit: Where do I have a second Panel? I only see one Frame (game) and one Panel (canvas). My target of this was to create a frame with a panel stretched out in it, so the magic happens in the panel. Does a Frame have a default panel inside?

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Calling jpanel.repaint() (same with any other swing element) should call your paintComponent method. You should never call paintComponent, it's something swing handles.

while(true)        {            System.out.println("Entering loop");            canvas.add(draw);            game.repaint();            System.out.println("Re-entering loop");        }
CONSOLE:run:Entering drawFrame();Entering loopRe-entering loopEntering loopRe-entering loopEntering loopRe-entering loopEntering loop[And so on...]

It still doesn't draw the objects, not even without the while(true)... :(

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Add the line

 

draw.setPreferredSize(new Dimension(frame_drawSizeX, frame_drawSizeY));

 

before adding draw to canvas

 

edit: And the first line of paintCompontent should be

 

super.paintComponent(g);

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Add the line

 

draw.setPreferredSize(new Dimension(frame_drawSizeX, frame_drawSizeY));

 

before adding draw to canvas

 

edit: And the first line of paintCompontent should be

 

super.paintComponent(g);

 

Great, thanks!

Now it draws once :lol:

However, if I add a while(true), it still doesn't work...

Any ideas how to solve this problem? The while(true) should draw the ball and the paddle..

 

Here is the new code: http://pastebin.com/yU7850tM

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Great, thanks!

Now it draws once :lol:

However, if I add a while(true), it still doesn't work...

Any ideas how to solve this problem? The while(true) should draw the ball and the paddle..

 

Here is the new code: http://pastebin.com/yU7850tM

Don't use a loop, swing isn't meant to work that way.

 

You could use a timer to call a method every X milliseconds

  int delay = 33; //milliseconds  ActionListener taskPerformer = new ActionListener() {      public void actionPerformed(ActionEvent evt) {          //...Perform a task...      }  };  new Timer(delay, taskPerformer).start();

In the actionPerformed you could call repaint or do anything else that needs to be constantly run.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

At edit: Where do I have a second Panel? I only see one Frame (game) and one Panel (canvas). My target of this was to create a frame with a panel stretched out in it, so the magic happens in the panel. Does a Frame have a default panel inside?

 

You are adding a canvas (which is one JPanel) and then adding to canvas another JPanel (called draw). And then in your while loop you are constantly adding more JPanels to the canvas JPanel. Also, I would recommend starting to name variables based on what their specific role is. It makes it a lot more readable. Just tips for the future :P

Link to comment
Share on other sites

Link to post
Share on other sites

Don't use a loop, swing isn't meant to work that way.

 

You could use a timer to call a method every X milliseconds

  int delay = 33; //milliseconds  ActionListener taskPerformer = new ActionListener() {      public void actionPerformed(ActionEvent evt) {          //...Perform a task...      }  };  new Timer(delay, taskPerformer).start();

In the actionPerformed you could call repaint or do anything else that needs to be constantly run.

 

Now everything is ready but I have to generate new Objects for actionPerformed()...

It starts but there is no movement.

Is there any way to implement game, canvas and draw?

public void drawFrame(int frame_drawSizeX, int frame_drawSizeY)    {        System.out.println("Entering drawFrame();");               //Create new GUI        //<editor-fold defaultstate="collapsed" desc=" Declaration and Definition of JFrame ">        JFrame game = new JFrame();         game.setType(Window.Type.UTILITY);        game.setResizable(false);        game.setSize(frame_drawSizeX, frame_drawSizeY);        game.setLocationRelativeTo(null);        game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        game.setVisible(true);        //</editor-fold>         //Creates a menubar for a JFrame        JMenuBar menuBar = new JMenuBar();         //Add the menubar to the frame        game.setJMenuBar(menuBar);         //Define and add dropdown menus to the menubar        JMenu returnToMenu = new JMenu("Return to Menu");        JMenu pointCounter = new JMenu("Your Points: 0");        JMenu liveCounter = new JMenu("Remaining Lives: 3");        JMenu levelCounter = new JMenu("Level: 0");         //Make them visible:        menuBar.add(returnToMenu);        menuBar.add(pointCounter);        menuBar.add(liveCounter);        menuBar.add(levelCounter);               draw.setPreferredSize(new Dimension(frame_drawSizeX, frame_drawSizeY));        JPanel canvas = new JPanel();        game.add(canvas);        canvas.add(draw);               int delay = 20; //Milliseconds for delay               ActionListener taskPerformer = new ActionListener()        {            @[member=override2299]            public void actionPerformed(ActionEvent evt)            {              System.out.println("Begin loop");              JFrame game = new JFrame();              JPanel canvas = new JPanel();                           //Move the ball              ball_posX += ball_deltaX;              ball_posY += ball_deltaY;                           game.repaint();              canvas.repaint();            }        };        new Timer(delay, taskPerformer).start();    }
CONSOLE:run:Entering drawFrame();Entering paintComponent();Begin loopBegin loopBegin loopBegin loopBegin loopBegin loopBegin loop[And so on...]

Updated Version: http://pastebin.com/yU7850tM

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

You are adding a canvas (which is one JPanel) and then adding to canvas another JPanel (called draw). And then in your while loop you are constantly adding more JPanels to the canvas JPanel. Also, I would recommend starting to name variables based on what their specific role is. It makes it a lot more readable. Just tips for the future :P

 

Oh ok :lol:

 

What do you mean by specific role?

This is code from a Netbeans example:

    // Game field info    public static final int BRICK_WIDTH = 48;    public static final int BRICK_HEIGHT = 24;    public static final int SHADOW_WIDTH = 10;    public static final int SHADOW_HEIGHT = 16;    public static final double BALL_MIN_SPEED = 6;    public static final double BALL_MAX_SPEED = BRICK_HEIGHT;    public static final double BALL_MIN_COORD_SPEED = 2;    public static final double BALL_SPEED_INC = 0.5f;    public static final int BAT_Y = SCREEN_HEIGHT - 40;    public static final int BAT_SPEED = 8;    public static final int BONUS_SPEED = 3;    public static final int FIELD_WIDTH = FIELD_BRICK_IN_ROW * BRICK_WIDTH;    public static final int FIELD_HEIGHT = FIELD_WIDTH;    public static final int FIELD_Y = SCREEN_HEIGHT - FIELD_HEIGHT;

About the variable names: I named them the first time this way here, because it's easier to find your connected variables by entering ball and press Strg+Space for autocorrection :P

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Now everything is ready but I have to generate new Objects for actionPerformed()...

It starts but there is no movement.

Is there any way to implement game, canvas and draw?

        ActionListener taskPerformer = new ActionListener()        {            @[member='override2299']            public void actionPerformed(ActionEvent evt)            {              System.out.println("Begin loop");              JFrame game = new JFrame();              JPanel canvas = new JPanel();                           //Move the ball              ball_posX += ball_deltaX;              ball_posY += ball_deltaY;                           game.repaint();              canvas.repaint();            }        };        new Timer(delay, taskPerformer).start();    }

Don't make a new game or panel inside the timer. Each time you enter your method your destroying all the work you did the last time.

 

Change the actionPerformed to just

public void actionPerformed(ActionEvent evt)            {              System.out.println("Begin loop");              //Move the ball              ball_posX += ball_deltaX;              ball_posY += ball_deltaY;                           game.repaint();            }

You'll also need to change

JFrame game = new JFrame();

to

final JFrame game = new JFrame();

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Oh ok :lol:

 

What do you mean by specific role?

This is code from a Netbeans example:

    // Game field info    public static final int BRICK_WIDTH = 48;    public static final int BRICK_HEIGHT = 24;    public static final int SHADOW_WIDTH = 10;    public static final int SHADOW_HEIGHT = 16;    public static final double BALL_MIN_SPEED = 6;    public static final double BALL_MAX_SPEED = BRICK_HEIGHT;    public static final double BALL_MIN_COORD_SPEED = 2;    public static final double BALL_SPEED_INC = 0.5f;    public static final int BAT_Y = SCREEN_HEIGHT - 40;    public static final int BAT_SPEED = 8;    public static final int BONUS_SPEED = 3;    public static final int FIELD_WIDTH = FIELD_BRICK_IN_ROW * BRICK_WIDTH;    public static final int FIELD_HEIGHT = FIELD_WIDTH;    public static final int FIELD_Y = SCREEN_HEIGHT - FIELD_HEIGHT;

About the variable names: I named them the first time this way here, because it's easier to find your connected variables by entering ball and press Strg+Space for autocorrection :P

For example, your draw JPanel is very confusing. As you saw in my example I would change it to something that is more of a noun like painter or drawer.

Some things I have learnt are to start all functions with a verb. I understand that draw JPanel draws the objects, but it could also mean the verb draw (which in my opinion would refer to a function).

For constants, they should be all caps like in your example.

 

I've heard it is also better to name objects and classes the way the user would perceive them or classify them as. I guess the cold truth is that each has their own style of naming and such.

Link to comment
Share on other sites

Link to post
Share on other sites

For example, your draw JPanel is very confusing. As you saw in my example I would change it to something that is more of a noun like painter or drawer.

Some things I have learnt are to start all functions with a verb. I understand that draw JPanel draws the objects, but it could also mean the verb draw (which in my opinion would refer to a function).

For constants, they should be all caps like in your example.

 

I've heard it is also better to name objects and classes the way the user would perceive them or classify them as. I guess the cold truth is that each has their own style of naming and such.

 

Thanks for the tips, I'll definetly use them :)

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

Don't make a new game or panel inside the timer. Each time you enter your method your destroying all the work you did the last time.

 

Change the actionPerformed to just

public void actionPerformed(ActionEvent evt)            {              System.out.println("Begin loop");              //Move the ball              ball_posX += ball_deltaX;              ball_posY += ball_deltaY;                           game.repaint();            }

You'll also need to change

JFrame game = new JFrame();

to

final JFrame game = new JFrame();

run:Entering drawFrame();actionPerformed();actionPerformed();actionPerformed();actionPerformed();

I now edited the obj declarations to public so I can access them everywhere.

And I did what you said, here the newest Version so far: http://pastebin.com/yU7850tM

 

However, as you can see above, he doesn't access the paintComponent()...

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

run:Entering drawFrame();actionPerformed();actionPerformed();actionPerformed();actionPerformed();

I now edited the obj declarations to public so I can access them everywhere.

And I did what you said, here the newest Version so far: http://pastebin.com/yU7850tM

 

However, as you can see above, he doesn't access the paintComponent()...

 

You got rid of your draw object, you still need one of those. Change the definition of canvas to

JPanel canvas = new drawObjects();

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×