Results 1 to 4 of 4
  1. #1
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default BufferStrategy in JFrame

    well Im creating a pong game and im pretty close to done. This last little bit has me pretty stumped though. Im trying to get my ball to draw on my JFrame after my title screen pop ups and does its thing. So far, the JFrame pop ups on que, but it leaves behind a nasty trail from the ball, but theres no noticeable lag and I think the bufferstrategy is working. Any suggestions?

    my main class:

    Java Code:
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import java.io.IOException;
    import javax.swing.*;
    
    public class PongInterfaceViewer extends JPanel
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public static void main(String[]args) throws IOException
    	{
    		frame = new JFrame();
    		BackGround component = new BackGround( );
    		frame.getContentPane( ).add(component);
    		
    		PongComboBoxes PongComboBoxes = new PongComboBoxes();
    		
    		ComboListener pong3 = new ComboListener();
    		JButton play = new JButton("Play");
    		play.addActionListener(pong3);
    		
    		JPanel ControlPanel = new JPanel();
    		ControlPanel.setLayout(new GridLayout(1,3));
    		ControlPanel.add(PongComboBoxes.addPlayer());
    		ControlPanel.add(play);
    		ControlPanel.add(PongComboBoxes.addSpeed());
    		
    		frame.add(ControlPanel, BorderLayout.SOUTH);
    		frame.setSize(850,590);
    		frame.setLocation(400,200);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    	public static void closeOperation (int speed, int player)
    	{
    		Speed = speed;
    		Player = player;
    		frame.dispose();
    		run();
    	}
    	public static void run()
    	{
    		frame1 = new JFrame();
    		
    		control = new ControlPanel();
    		frame1.add(control);
    		
    		frame1.setIgnoreRepaint(true);
    	    frame1.setVisible(true);
    		frame1.setSize(600,700);
    		frame1.setLocation(450,150);
    		frame1.setBackground (Color.RED);
    		
    		frame1.createBufferStrategy(2);
    		new PongBall(Speed);
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    	public synchronized void updateScreen(int x_pos, int y_pos, int radius, int length)
    	{
    		BufferStrategy buff = frame1.getBufferStrategy();
    		g2 = null;
    		if (radius >= 0)
    		{
    			try
    			{
    				System.out.println("ball");
    			    g2 = buff.getDrawGraphics();
    			    g2.setColor(Color.white);
    			    g2.fillOval(x_pos, y_pos, radius, radius);
    		   }
    		   finally{g2.dispose();}
    		}
    		else if (radius == 0 && x_pos == 75)
    		{
    			try{
    				System.out.println("paddle1");
    				g2 = buff.getDrawGraphics();
    				g2.setColor(Color.blue);
    				g2.fillRect(x_pos, y_pos,125,125);
    			}
    			finally{g2.dispose();}
    		}
    		else if (radius == 0 && x_pos == 525)
    		{
    			try{
    				System.out.println("paddle2");
    				g2 = buff.getDrawGraphics();
    				g2.setColor(Color.yellow);
    				g2.fillRect(x_pos, y_pos,125,125);
    			}
    			finally{g2.dispose();}
    		}
    		buff.show();
    		notifyAll();
    		System.out.println("notify all the threads");
    	}
    	private static JPanel control;
    	private static Graphics g2;
    	private static int Player;
    	private static int Speed;
    	private static JFrame frame1;
    	private static JFrame frame;
    }
    my background for the first frame:

    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    
    public class BackGround extends JComponent
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public BackGround () throws IOException
    	{
          	String inputFileName = "welcomescreen.gif";
          	backgroundImage = ImageIO.read(new File(inputFileName));
    	}
    	 public void paintComponent(Graphics g) 
    	{
    		 super.paintComponents(g);
    		 g.drawImage(backgroundImage, 0, 0, null);
    	}
    	private Image backgroundImage;
    }
    the combo boxes for the main screen:

    Java Code:
    import java.awt.Component;
    
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    
    class PongComboBoxes extends JPanel
    {
        public Component addPlayer() 
        {
            return PlayerCombo;
        }
        public Component addSpeed()
        {
        	return SpeedCombo;
        }
        public static String getPlayer() 
        {
            return (String) PlayerCombo.getSelectedItem();
        }
        public static String getSpeed() 
        {
            return (String) SpeedCombo.getSelectedItem();
        }
        public static final String[] PLAYER = {"1 Player", "2 Players"};
        public static final String[] SPEED = {"slow", "medium", "fast", "bullet speed"};
        
        private static JComboBox PlayerCombo = new JComboBox(PLAYER);
        private static JComboBox SpeedCombo = new JComboBox(SPEED);
        
        private static final long serialVersionUID = 1L;
    }
    the combolistener for the first screens combo boxes:

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class ComboListener implements ActionListener,Runnable
    {
    	public void actionPerformed(ActionEvent evt) 
    	{
    		run();
    	}
    	public void run() 
    	{
    		player1 = PongComboBoxes.getPlayer();
    		speed1 = PongComboBoxes.getSpeed();
    		if (player1.equals("1 Player"))
    		{
    			player = 1;
    		}
    		else 
    		{
    			player = 2;
    		}
    		if (speed1.equals("slow"))
    		{
    			speed = 1;
    		}
    		else if (speed1.equals("medium"))
    		{
    			speed = 2;
    		}
    		else if (speed1.equals("fast"))
    		{
    			speed = 3;
    		}
    		else 
    		{
    			speed = 4;
    		}
    		
    		PongInterfaceViewer.closeOperation(speed,player);
    	}
    	private String player1;
    	private String speed1;
    	private int player;
    	private int speed;
    }
    the control panel that draws on the JFrame for the first time:

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    
    public class ControlPanel extends JPanel
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	public void createPanel ()
    	{
    		repaint();
    	}
    	protected void paintComponent(Graphics g)
    	{
    		super.paint(g);
    		g.setColor(Color.white);
    		g.fillOval(300,100,10,10);
    		g.setColor(Color.blue);
    		g.fillRect(75, 300, 25, 125);
    		g.setColor(Color.yellow);
    		g.fillRect(525, 300, 25, 125);
    	}
    }
    the score class that holds the current score between the users:

    Java Code:
    public class UpdateScore 
    {
    	public void addScore(int x_pos)
    	{
    		if (x_pos == 0)
    		{
    			Player1++;
    		}
    		else if (x_pos == 600)
    		{
    			Player2++;
    		}
    	}
    	public int getPlayer1()
    	{
    		return Player1;
    	}
    	public int getPlayer2()
    	{
    		return Player2;
    	}
    	private int Player1 = 0;
    	private int Player2 = 0;
    }
    finally the ball moving class that changes the balls location:

    Java Code:
    //Dylan Smith PongBall
    
    public class PongBall implements Runnable
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public PongBall(int speed)
    	{
    		x_pos = 300;	
    		y_pos = 100;
    		y_speed = speed;
    		x_speed = speed;
    		radius = 15;
    		appletsize_x = 700; 
    		appletsize_y = 600;
    		run();
    	}
    	public synchronized void run ()
    	{
    		Thread th = new Thread (this);
    		th.start ();
    		
    		while (true)
    		{
    			 if (x_pos > appletsize_x - radius)
    			 {
    				 x_speed *= -1;
    				 x_pos += x_speed;
    			     UpdateScore score = new UpdateScore();
    			     score.addScore(x_pos);
    			 }
    			 else if (x_pos < radius)
    			 {
    				 x_speed *= -1;
    			     UpdateScore score = new UpdateScore();
    			     score.addScore(x_pos);
    			 }
    			 else if (y_pos > appletsize_y - radius)
    			 {
    				 y_speed *= -1;
    			 }
    			 else if (y_pos < radius)
    			 {
    				 y_speed *= -1;
    			 }
    			 
    			 x_pos += x_speed;
    			 y_pos += y_speed;
    			
    			PongInterfaceViewer pong = new PongInterfaceViewer();
    			pong.updateScreen(x_pos, y_pos, radius, 0);
    			
    			try 
    			{
    				wait();
    			}
    			catch (InterruptedException e) 
    			{
    				e.printStackTrace();
    			}
    		}
    	}
    	private int x_pos;	
    	private int y_pos;
    	private int x_speed;
    	private int y_speed;
    	private int radius;
    	private int appletsize_x; 
    	private int appletsize_y;	
    }
    Some of this is empty code that i need to expand upon. Such as using the info in the update score class, but I wanted to make sure I could at least draw the ball first. Before I moved on to putting the finishing touches on the game.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    A lot of code to go thru. Can you make a smaller test program that demonstrates the problem?

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,457
    Rep Power
    20

    Default

    And get rid of all the old AWT-style code. Learn how to correctly perform custom painting in Swing:
    Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    db

  4. #4
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    I looked over the link you posted about AWT. im not sure that i completely understand the difference, but i will post my changes.

    Java Code:
    	public static void letsPlay()
    	{
    		SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
    	}
    	private static void createAndShowGUI()
    	{
    		System.out.println(Player);
    		System.out.println(Speed);
    		
    		frame1 = new JFrame();
    		frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame1.setLocation(425,125);
    		
    		intialize = new ControlPanel(Speed);
    		intialize.setLayout(new BorderLayout());
    		frame1.add(intialize);
    		
    		frame1.pack();
    	    frame1.setVisible(true);
    	}
    	private static ControlPanel intialize;
    	private static int Player;
    	private static int Speed;
    	private static JFrame frame1;
    	private static JFrame frame;
    }
    I have two frames, but this is the one im having issues with.

    Java Code:
    import java.awt.*;
    import javax.swing.JPanel;
    
    public class ControlPanel extends JPanel
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public ControlPanel(int Speed)
    	{
    		System.out.println("Im constructed");
    		new PongBall(Speed);
    		Paddle1 player1 = new Paddle1(Speed);
    		Paddle2 player2 = new Paddle2(Speed);
    		addKeyListener(player1);
    		addKeyListener(player2);
    	}
        public Dimension getPreferredSize() {
            return new Dimension(700,600);
        }
        public void gameOn() throws InterruptedException
        {
        	while (new UpdateScore().getPlayer1() != 10 || new UpdateScore().getPlayer1() != 10)
        		System.out.println("Im running");
            	repaint();
                Thread.sleep(50);
        }
    	protected void paintComponent(Graphics g)
    	{
    		super.paintComponent(g);
    		
    		System.out.println("Im painting");
    		g.setColor(Color.white);
    		g.fillOval(PongBall.getxCoordinate(),PongBall.getyCoordinate(), 15, 15 );
    		g.setColor(Color.blue);
    		g.fillRect(25, Paddle1.getyCoordinate(), 25, 75);
    		g.setColor(Color.yellow);
    		g.fillRect(525, Paddle2.getyCoordinate(), 25, 75);
    	}
    }
    this is where i want to draw my ball and the paddles respectively. I can also post the ball and the two paddles (their codes at least), but I wanted to try to keep it smaller.

Similar Threads

  1. Replies: 5
    Last Post: 06-14-2010, 07:10 PM
  2. BufferStrategy
    By Shadowdude04 in forum AWT / Swing
    Replies: 0
    Last Post: 03-13-2010, 03:59 PM
  3. Passing data from one JFrame to another JFrame
    By tarami in forum New To Java
    Replies: 3
    Last Post: 08-06-2009, 06:44 PM
  4. Replies: 4
    Last Post: 04-23-2009, 12:02 AM
  5. BufferStrategy and white rows of pixels
    By TobyLobster in forum Java 2D
    Replies: 2
    Last Post: 12-29-2008, 02:49 PM

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
  •