Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Experimenting with Graphics

  1. #1
    Member tyeeeee1's Avatar
    Join Date
    Sep 2012
    Posts
    61
    Thanks
    31
    Thanked 2 Times in 2 Posts

    Default Experimenting with Graphics

    I've been trying to wrap my head around how to detect and fix collision at the moment but as I'm not very familiar with drawing on a JPanel I managed to mess up somehow. At the moment my loop looks like this:
    import java.awt.*;
    import javax.swing.*;
     
    class GameLoop implements Runnable //This is the Game Loop, it controls all rendering and that. Use the getters/setters to change sprite stuff.
    {
     
    	Thread thread = new Thread(this);
    	Graphics g;
    	private int x = 10, y = 10, a = 10, b = 10;
    	private boolean hasCollided = false;
    	Entity entity = new Entity(x, y, 20, 20);
    	Entity entityTwo = new Entity(a, b, 20, 20);
    	JPanel mainPanel;
     
    	public GameLoop(JPanel mainPanel)
    	{
    		this.mainPanel = mainPanel;
    		this.g = mainPanel.getGraphics();
    	}
     
    	public void startThread()
    	{
    		thread.start();
    	}
     
    	public void run()
    	{
    		while(true)
    		{
    			try
    			{	
    				if(entity.getBounds().intersects(entityTwo.getBounds()))
    					hasCollided = true;
    				else
    					hasCollided = false;
     
    				if( hasCollided == false)
    				{
    					g.setColor(Color.red);
    					g.fillRect(x, x, 20, 20);
    					g.setColor(Color.blue);
    					g.fillRect(a, b, 20, 20);
    				}
    				else if( hasCollided == true )
    				{
    					g.setColor(Color.red);
    					g.fillRect(x + 1, x + 1, 20, 20);
    					entity.setX(x);
    					entity.setY(y);
    					g.setColor(Color.blue);
    					g.fillRect(a, b, 20, 20);
    				}
     
    				mainPanel.repaint();
     
    				Thread.sleep(30); //Anything lower than 30 bugs out a little bit. This will run at something like 30FPS or something.
    			}
    			catch(Exception e)
    			{
    				e.printStackTrace(); //Prints where the exception occurs and some other info about it if an exception happens.
    			}
    		}
    	}
    }

    At line 8 I create the graphics object, then at line 18 I set it to the JPanel's graphics and then later on I use it to paint with. For some reason nothing is showing up on the JPanel.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Experimenting with Graphics

    Can you make a small, simple program that compiles, executes and shows the problem?
    A Short, Self Contained, Correct Example

    Note: Getting a Graphcs object is not the normal way for custom graphics.
    http://docs.oracle.com/javase/tutori...ing/index.html
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    tyeeeee1 (January 31st, 2013)

  4. #3
    Member tyeeeee1's Avatar
    Join Date
    Sep 2012
    Posts
    61
    Thanks
    31
    Thanked 2 Times in 2 Posts

    Default Re: Experimenting with Graphics

    I've removed the collision related code, here is the basic program:

    Edit: Threw the program into one file, this should still work...

    import javax.swing.*;
    import java.awt.*;
     
    class Rawr
    {
    	public static void main(String args[])
    	{
    		Window window = new Window();
    	}
    }
     
    class Window extends JFrame
    {
    	private JFrame mainFrame;
    	private JPanel mainPanel;
     
    	public Window()
    	{
    		JFrame mainFrame = new JFrame();
    		mainFrame.setSize(1024, 786);
    		mainFrame.setLocationRelativeTo(null); //Centers the window on the users screen.
    		mainFrame.setTitle("Temp Name");
    		mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    		mainFrame.setResizable(false);
    		JPanel mainPanel = new JPanel(); //Creates a new JPanel to put everything on.
    		mainFrame.getContentPane().add(mainPanel);
    		mainPanel.setLayout(null); //Makes it so you can manually positon everything on the JPanel using XY coords
     
    		mainFrame.setVisible(true);
    		mainPanel.setVisible(true);
    		GameLoop gameloop = new GameLoop(mainPanel);
    	}
    }
     
    class GameLoop implements Runnable //This is the Game Loop, it controls all rendering and that. Use the getters/setters to change sprite stuff.
    {
     
    	Thread thread = new Thread(this);
    	Graphics g;
    	private int x = 10, y = 10;
    	JPanel mainPanel;
     
    	public GameLoop(JPanel mainPanel)
    	{
    		this.mainPanel = mainPanel;
    		this.g = mainPanel.getGraphics();
    	}
     
    	public void startThread()
    	{
    		thread.start();
    	}
     
    	public void run()
    	{
    		while(true)
    		{
    			try
    			{	
    				g.setColor(Color.red);
    				g.fillRect(x, x, 20, 20);
     
    				mainPanel.repaint();
     
    				Thread.sleep(30); //Anything lower than 30 bugs out a little bit. This will run at something like 30FPS or something.
    			}
    			catch(Exception e)
    			{
    				e.printStackTrace(); //Prints where the exception occurs and some other info about it if an exception happens.
    			}
    		}
    	}
    }

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Experimenting with Graphics

    nothing is showing up on the JPanel.
    Read the tutorial at the link I posted about how to do drawing/painting in a component.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Member tyeeeee1's Avatar
    Join Date
    Sep 2012
    Posts
    61
    Thanks
    31
    Thanked 2 Times in 2 Posts

    Default Re: Experimenting with Graphics

    I'm going over it now, but it totally lost me when it came to this example:

    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
     
    public class SwingPaintDemo2 {
     
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI(); 
                }
            });
        }
     
        private static void createAndShowGUI() {
            System.out.println("Created GUI on EDT? "+
            SwingUtilities.isEventDispatchThread());
            JFrame f = new JFrame("Swing Paint Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new MyPanel());
            f.pack();
            f.setVisible(true);
        }
    }
     
    class MyPanel extends JPanel {
     
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
        }
     
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        }
     
        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
     
            // Draw Text
            g.drawString("This is my custom Panel!",10,20);
        }  
    }

    Is f.add(new MyPanel()); starting the MyPanel constructor of the MyPanel class? How does the MyPanel class know what panel to paint to, I don't see any JPanels being created in either class.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Experimenting with Graphics

    (new MyPanel()); starting the MyPanel constructor
    Yes, that is what new does.

    what panel to paint to
    It is painting itself. It's a JPanel.
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    tyeeeee1 (January 31st, 2013)

  9. #7
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Experimenting with Graphics

    This line:

    f.add(new MyPanel());

    Is the same as doing this:

    MyPanel myPanel = new MyPanel();
    f.add(myPanel);

    It's just a little more compact is all.

  10. The Following User Says Thank You to curmudgeon For This Useful Post:

    tyeeeee1 (January 31st, 2013)

Similar Threads

  1. how to use graphics g
    By steel55677 in forum AWT / Java Swing
    Replies: 11
    Last Post: November 21st, 2011, 06:35 PM
  2. Graphics class NullPointerException Initialize Graphics Class??
    By bglueck in forum What's Wrong With My Code?
    Replies: 7
    Last Post: May 13th, 2011, 11:13 PM
  3. paintComponent(Graphics g)
    By Kumarrrr in forum Java Theory & Questions
    Replies: 1
    Last Post: February 8th, 2011, 08:55 AM
  4. JButton with 2D Graphics help
    By mystikaljester in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 13th, 2010, 09:33 PM
  5. Help about Graphics
    By mamech in forum What's Wrong With My Code?
    Replies: 13
    Last Post: September 9th, 2010, 03:20 PM