Page 1 of 2 12 LastLast
Results 1 to 20 of 28
Like Tree1Likes

Thread: Not exactly the code works correctly ( JFrame, awt)

  1. #1
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Lightbulb Not exactly the code works correctly ( JFrame, awt)

    I've got a small problem with this code:
    Java Code:
    import javax.swing.JFrame;
    
    public class Game {
    
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //frame.setVisible(true);
            for (int i = 0; i < 5000; i++) {
                frame.getContentPane().add(new Star());
                frame.setVisible(true);
                //Thread.sleep(500);
                frame.repaint();
            }
    
        }
    }
    The second class:

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    
    public class Star extends JPanel {
        private static final long serialVersionUID = 1L;
    
        private int x, y, red, green, blue;
    
        public Star() {
            x = (int) (Math.random() * 4500);
            y = (int) (Math.random() * 4500);
    
            red = (int) (Math.random() * 255);
            green = (int) (Math.random() * 255);
            blue = (int) (Math.random() * 255);
    
        }
    
        public void paintComponent(Graphics g) {
            Color startColor = new Color(red, green, blue);
            g.setColor(startColor);
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    
        }
    }
    The number one problem: The code works very slowly ... As you can see, the code would randomly bring a lot of circles.But it's so slow ..Is it possible to speed it up like that?

    Problem number two:

    In this piece of code:

    Java Code:
    public void paintComponent(Graphics g) {
            Color startColor = new Color(red, green, blue);
            g.setColor(startColor);
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    
        }
    I add the following lines:

    Java Code:
    g.setColor(Color.BLACK);
            g.fillRect(0, 0, getWidth(), getHeight());
    JFrame background is black, but the circle was not seen.They seemed to have disappeared ..) Help them to return.


    Help me solve the problem)

    In advance thank you very much!

  2. #2
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    I'm sorry if I'm not there to create a theme

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,039
    Rep Power
    6

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    The problem is probably not slow code but incorrect code. Look at the range of your x and y coordinates. is your JPanel really 4500 x 4500 pixels? Your x and y should be constrained to the size of the area to which you want to paint.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,785
    Blog Entries
    7
    Rep Power
    21

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    You're generating an entire component (a JPanel) for a single star. Components are more expensive that simple 'drawers'. A drawer draws itself given a Graphicss object passed to its draw( ... ) method. Add a single extension of a JPanel to your frame and make the JPanel call the draw( ... ) method for all the stars it 'manages'. w.r.t. your other question: you're painting everything black after painting a star ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Thank you very much for your answers.
    The problem is probably not slow code but incorrect code. Look at the range of your x and y coordinates. is your JPanel really 4500 x 4500 pixels? Your x and y should be constrained to the size of the area to which you want to paint.
    It's all for a little game I'm writing. I wanted to scatter the objects by their "map"
    Then I add the processing of the keyboard, and I will move inside the frame.

    You're generating an entire component (a JPanel) for a single star. Components are more expensive that simple 'drawers'. A drawer draws itself given a Graphicss object passed to its draw( ... ) method. Add a single extension of a JPanel to your frame and make the JPanel call the draw( ... ) method for all the stars it 'manages'. w.r.t. your other question: you're painting everything black after painting a star ...
    I'm sorry, I did not understand a bit, so what should I do?
    Create a paintComponent in the main class? where JFrame

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,365
    Rep Power
    6

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    This code you have in your main():

    Java Code:
    for (int i = 0; i < 5000; i++) {
                frame.getContentPane().add(new Star());
                frame.setVisible(true);
                //Thread.sleep(500);
                frame.repaint();
            }
    Is very much not a good idea. If you want to add 5000 stars, then add 5000 stars and not 5000 stars with 5000 repaints. If you want to add 5000 stars with a delay in between each added star, consider using a Timer.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    I understand that this is not a good idea, but I do not know how to fix it. If anyone else has improved (corrected these shortcomings) code would be great! Thanks in advance.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Move the setVisible and repaint calls to after the loop, not inside it.
    That covers gimbals point.

    Jos is possibly suggesting using a single JPanel that draws 5000 "stars" itself, rather than have 5000 components (which have lots of other things they do that are probably irrelevant to drawing spots on a screen). Are these stars just a backdrop? Are they supposed to be static (ie stay in the same place)?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    If I delete the line and move it after the loop
    Java Code:
    frame.setVisible(true);
    Then I get a empty window(

    That is, here is the following code:
    Java Code:
    for (int i = 0; i < 5000; i++) {
                frame.getContentPane().add(new Star());
                //Thread.sleep(500);
                frame.repaint();
            }
    frame.setVisible(true);
    Does not work (

    Yes, objects (circles are randomly scattered) should remain in place! Even if I change the window size, then they should stay in place.

    Help me please, can anyone has a good working code?)
    I can not cope with the task.

    Thanks in advance)
    Last edited by Tony; 11-13-2013 at 05:02 PM.

  10. #10
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    The purpose of this whole code: Randomly display a circle so that they were in place when the window(JFrame) changes.
    Help please..

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,365
    Rep Power
    6

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Help yourself: spend more time studying Swing custom painting.

    Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    That's a start, Google will provide you a wide variety more examples and tutorials to learn from.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,039
    Rep Power
    6

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    First, you do not need a Star class. What you want to do is draw 5000 circles in a JPanel. So extend JPanel, and add to JFrame. The rest you know how to do because it is all in your Star class. Your paintComponent will have the loop in it. See Jos' comment.

    Regards,
    Jim
    Tolls likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Quote Originally Posted by Tony View Post
    If I delete the line and move it after the loop
    Java Code:
    frame.setVisible(true);
    Then I get a empty window(
    I said "(m)ove the setVisible and repaint calls to after the loop".

    Yes, objects (circles are randomly scattered) should remain in place! Even if I change the window size, then they should stay in place.

    Help me please, can anyone has a good working code?)
    I can not cope with the task.

    Thanks in advance)
    Anyway, the best bet is to produce a single JPanel that draws your background.
    In that JPanel create an array representing your 5000 stars and their coordinates.
    Then either draw all the stars or just those visible at the time in the paintComponent() call.

    But really you do need to read the link gimbal has posted. You have to learn how to do this stuff properly, and a forum really isn;t the best place to do that.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Thank you all!)
    But I have not solved the problem, though I was close to a decision, here's the code:
    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Game extends JPanel {
    
    	private static final long serialVersionUID = 1L;
    
    	private static final String NAME = "Title";
    	private int x, y, red, green, blue;
    
    	public Game() {
    		x = (int) (Math.random() * 100);
    		y = (int) (Math.random() * 100);
    
    		red = (int) (Math.random() * 256);
    		green = (int) (Math.random() * 256);
    		blue = (int) (Math.random() * 256);
    	}
    
    	public void paintComponent(Graphics g) {
    		Graphics2D g2d = (Graphics2D) g;
    
    		g2d.setColor(Color.BLACK);
    		g2d.fillRect(0, 0, getWidth(), getHeight());
    
    		Color startColor = new Color(red, green, blue);
    		g2d.setColor(startColor);
    		g2d.fillRect(x, y, 100, 100);
    	}
    
    	public static void main(String[] args) {
    		JFrame f = new JFrame(NAME);
    		f.setSize(500, 500);
    		f.getContentPane().add(new Game());
    		f.setVisible(true);
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    	}
    }
    This code is a problem. He draws only one object, and need a lot of...
    Can you suggest how to do it?
    Or show working code, or suggest where to put it .. Please!
    Maybe you need to insert a loop? But where to?

    I tried to follow your instructions.Help please!
    Last edited by Tony; 11-13-2013 at 08:22 PM.

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    We've said how to do it.
    You need an array to hold your x and y coordinates for all 5000 points.
    That array is populated in the constructor.
    Then, in the paintComponent, you loop over that and draw them.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Array? but then how to separate from it the x-coordinate and y? Maybe better two arrays?

  17. #17
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,365
    Rep Power
    6

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Normally you would not want to separate the two, they form one singular OBJECTive.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    Quote Originally Posted by Tony View Post
    Array? but then how to separate from it the x-coordinate and y? Maybe better two arrays?
    Or a single array of some Point class (or Star class) that contains both values.
    You need to get in the habit of thinking in terms of classes rather than individual bits of data.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  19. #19
    Tony is offline Member
    Join Date
    Nov 2013
    Posts
    12
    Rep Power
    0

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    I tried to do something like this:

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Game extends JPanel {
    
    	private static final long serialVersionUID = 1L;
    
    	private static final String NAME = "Title";
    	private int x, y, red, green, blue;
    	public static final int STAR_MAX = 5000;
    	private int a[], b[];
    
    	public Game() {
    		x = (int) (Math.random() * 300);
    		y = (int) (Math.random() * 300);
    
    		red = (int) (Math.random() * 256);
    		green = (int) (Math.random() * 256);
    		blue = (int) (Math.random() * 256);
    
    		a = new int[STAR_MAX];
    		b = new int[STAR_MAX];
    
    		for (int i = 0; i < a.length; i++) {
    			a[i] = (int) (Math.random() * 300);
    			System.out.println(a[i]);
    		}
    
    		for (int i = 0; i < a.length; i++) {
    			b[i] = (int) (Math.random() * 300);
    		}
    	}
    
    	public void paintComponent(Graphics g) {
    		Graphics2D g2d = (Graphics2D) g;
    
    		g2d.setColor(Color.BLACK);
    		g2d.fillRect(0, 0, getWidth(), getHeight());
    
    		Color startColor = new Color(red, green, blue);
    		g2d.setColor(startColor);
    		for (int i = 0; i < a.length; i++) {
    				g2d.fillRect(a[i], y, 100, 100);
    		}
    	}
    
    	public static void main(String[] args) {
    		JFrame f = new JFrame(NAME);
    		f.setSize(500, 500);
    		f.getContentPane().add(new Game());
    		f.setVisible(true);
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    	}
    }
    But this code is not working again (
    Help PLease!

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Not exactly the code works correctly ( JFrame, awt)

    "not working again"

    What does that mean?

    We cannot see your machine from here.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Page 1 of 2 12 LastLast

Similar Threads

  1. Code works but nothing shows
    By Hagelslag in forum New To Java
    Replies: 2
    Last Post: 01-21-2013, 07:03 PM
  2. Did I comment this code correctly?
    By Vinx in forum New To Java
    Replies: 5
    Last Post: 06-17-2012, 02:50 AM
  3. Sorting code not working correctly
    By jubbiejub in forum New To Java
    Replies: 3
    Last Post: 05-01-2012, 02:28 AM
  4. Replies: 3
    Last Post: 10-29-2011, 01:39 AM
  5. Please explain how this bit of code works.
    By Allspark in forum New To Java
    Replies: 4
    Last Post: 09-03-2010, 04:56 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •