Page 1 of 2 12 LastLast
Results 1 to 20 of 39
Like Tree2Likes

Thread: Double-buffering and mouse=event help please

  1. #1
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Double-buffering and mouse=event help please

    I'm working on a java project for class, but I don't know how to double-buffer, animate the image, or make mouse-events work. Also, the JPanel covers the JMenubar and I don't know how to fix that. Could someone help me with all this, please? The game is a modified chess game and I want to be able to drag and drop the pieces in the end. The main class is proChess, the class for the game itself is classAppBoard.
    Java Code:
    /*
      date: Dec 16 2011
      purpose: proChess*/
    
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    
    public class proChess extends JFrame implements ActionListener
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 8828135172836094084L;
    	
    	static JFrame frameProChess = new JFrame("ProChess");
    		// all items in window
    		static Panel panelProChess = new Panel();
    			static JLabel iconTitle = new JLabel(createImageIcon("iconLogo.png")); 
    			static Panel panelDisplay = new Panel(new GridLayout(3,1));
    				static JLabel labelPlayer1;
    				static JLabel labelPlayer2;
    				static JLabel labelTurn;
    			static JLabel labelPromotionTitle;
    			static Panel panelChoice = new Panel(new GridLayout(1,4));
    				static JButton buttonChoice1 = new JButton();
    				static JButton buttonChoice2 = new JButton();
    				static JButton buttonChoice3 = new JButton();
    				static JButton buttonChoice4 = new JButton();
    	
    	static JFrame frameHelp = new JFrame("Help");
    	static boolean bolHelp = false;
    	static JFrame frameSetting = new JFrame("Settings");
    	static boolean bolSetting = false;
    
    	public static void main(String[] args) 
    	{
    		proChess proChess = new proChess();
    	}
    	
    	public proChess()
    	{	
    		newGame();
            
    		// Menu
    		JMenuBar JMenuBar = new JMenuBar();
    		frameProChess.setJMenuBar(JMenuBar);
    			JMenu menuMenu = new JMenu("Menu");
    				JMenuItem itemNewGame = new JMenuItem("New Game");
    				menuMenu.add(itemNewGame);
    				itemNewGame.setActionCommand ("New Game");
    				itemNewGame.addActionListener((ActionListener)this);
    				JMenuItem itemSaveGame = new JMenuItem("Save Game");
    				menuMenu.add(itemSaveGame);
    				itemSaveGame.setActionCommand ("Save Game");
    				itemSaveGame.addActionListener((ActionListener)this);
    				JMenuItem itemLoadGame = new JMenuItem("Load Game");
    				menuMenu.add(itemLoadGame);
    				itemLoadGame.setActionCommand ("Load Game");
    				itemLoadGame.addActionListener((ActionListener)this);
    				JMenuItem itemSetting = new JMenuItem("Settings");
    				itemSetting.setActionCommand ("Settings");
    				itemSetting.addActionListener((ActionListener)this);
    				menuMenu.add(itemSetting);
    				JMenuBar.add(menuMenu);
    			JMenu menuHelp = new JMenu("Help");
    				JMenuItem itemHelp = new JMenuItem("Help");
    				menuHelp.add(itemHelp);
    				itemHelp.setActionCommand ("Help");
    				itemHelp.addActionListener((ActionListener)this);
    				JMenuBar.add(menuHelp);
    		
    		// disable auto layout
    		panelProChess.setLayout(null);
    		
    			/* Not as good on XP
    			 *try 
    			 *{
    			 *	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    			 *}catch(Exception e){}
    			 */
    			 
    		iconTitle = new JLabel(createImageIcon("iconLogo.png"));
    		
    		JPanel appBoard = new classAppBoard();
    		
    		labelPlayer2 = new JLabel("<html><u>Player 2</u><br><br>Time:<br>Gold:<br>Score:</html>");
    		panelDisplay.add(labelPlayer2);			
    		labelPlayer1 = new JLabel("<html><u>Player 1</u><br><br>Time:<br>Gold:<br>Score:</html>");
    		panelDisplay.add(labelPlayer1);
    		labelTurn = new JLabel("It is Player 1's turn.");
    		panelDisplay.add(labelTurn);
    
    		// Segment Three
    		labelPromotionTitle = new JLabel("<html><u>Promotion</u></html>");
    
    		buttonChoice1 = new JButton();
    		panelChoice.add(buttonChoice1);
    		buttonChoice2 = new JButton();
    		panelChoice.add(buttonChoice2);
    		buttonChoice3 = new JButton();
    		panelChoice.add(buttonChoice3);
    		buttonChoice4 = new JButton();
    		panelChoice.add(buttonChoice4);
    
    		panelProChess.add(iconTitle);
    		iconTitle.setBounds(15,15,484,107);
    		panelProChess.add(appBoard);
    		appBoard.setBounds(15,122,480,480);
    		panelProChess.add(panelDisplay);
    		panelDisplay.setBounds(514,0,254,768);
    		panelProChess.add(labelPromotionTitle);
    		labelPromotionTitle.setBounds(225,621,63,18);
    		panelProChess.add(panelChoice);
    		panelChoice.setBounds(135,653,242,60);
    
    		frameProChess.add(panelProChess);
    		
    		frameProChess.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frameProChess.pack();
    		frameProChess.resize(768,768);
    		frameProChess.setLocationRelativeTo(null);
    		frameProChess.setResizable(false);
    		frameProChess.setVisible(true);
    	}
    	public void newGame()
    	{
    			// reset board
    			for(int y = 0; y < 8; y++)
    			{
    					for(int x = 0; x < 8; x++)
    					{
    						classAppBoard.position[x][y] = "      ";
    						classAppBoard.positionChosen[x][y] = false;
    						classAppBoard.positionMove[x][y] = false;
    					}
    			}
    			
    		// positions pawns for black
    		int y = 1;
    		
    			for(int x = 0; x < 8; x++)
    			{
    				classAppBoard.position[x][y] = "bp0000";
    			}
    			
    		// positions pawns for white
    		y = 6;
    			
    			for(int x = 0; x < 8; x++)
    			{
    				classAppBoard.position[x][y] = "wp0000";
    			}
    			
    		// positions pieces for black
    		classAppBoard.position[0][0] = "br";
    		classAppBoard.position[1][0] = "bk";
    		classAppBoard.position[2][0] = "bb";
    		classAppBoard.position[3][0] = "bq";
    		classAppBoard.position[4][0] = "bw";
    		classAppBoard.position[5][0] = "bb";
    		classAppBoard.position[6][0] = "bk";
    		classAppBoard.position[7][0] = "br";
    		
    		// positions pieces for white	
    		classAppBoard.position[0][7] = "wr";
    		classAppBoard.position[1][7] = "wk";
    		classAppBoard.position[2][7] = "wb";
    		classAppBoard.position[3][7] = "wq";
    		classAppBoard.position[4][7] = "ww";
    		classAppBoard.position[5][7] = "wb";
    		classAppBoard.position[6][7] = "wk";
    		classAppBoard.position[7][7] = "wr";
    		
    		classAppBoard.turn = 1;
    		
    			for(int x = 0; x < 2; x++)
    			{
    				classAppBoard.time[x] = classAppBoard.timeSet;
    				classAppBoard.gold[x] = 0;
    				classAppBoard.score[x] = 0;
    			}
    	}
    	public void saveGame()
    	{
    
    	}
    	public void loadGame()
    	{
    		
    	}
    	public void actionPerformed(ActionEvent e) 
    	{
    			if(e.getActionCommand().equals ("New Game"))
    			{
    				newGame();
    			}
    			if(e.getActionCommand().equals ("Save Game"))
    			{
    				saveGame();
    			}
    			if(e.getActionCommand().equals ("Load Game"))
    			{
    				loadGame();
    			}			
    			if(e.getActionCommand().equals ("Help"))
    			{
    					if(frameHelp.isVisible() == false && bolHelp == false)
    					{
    						bolHelp = true;						
    						JFrame FrameHelp = new classFrameHelp();
    					}
    					else
    						frameHelp.setVisible(true);
    			}
    			if(e.getActionCommand().equals ("Settings"))
    			{
    					if(frameSetting.isVisible() == false && bolSetting == false)
    					{
    						bolSetting = true;
    						JFrame FrameSettings = new classFrameSettings();
    					}
    					else 
    						frameSetting.setVisible(true);
    			}
    	}
    	protected static ImageIcon createImageIcon (String path)
    	{
    		java.net.URL imgURL = proChess.class.getResource (path);
    		
    			if (imgURL != null)
    			{
    				return new ImageIcon (imgURL);
    			}
    			else
    			{
    				System.err.println ("Couldn't find file: " + path);
    				return null;
    			}
    	}
    }
    Java Code:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class classAppBoard extends JApplet implements ActionListener, MouseListener, MouseMotionListener
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = -4529456824050911554L;
    	
    	static Color colorOne = Color.white;
    	static Color colorTwo = Color.black;
    	
    	static Color colorPieceOne = Color.blue;
    	static Color colorPieceTwo = Color.green;
    	
    	static int positionX = 0;
    	static int positionY = 0;
    	static String[][] position = new String[8][8];
    	static Boolean[][] positionChosen = new Boolean[8][8];
    	static Boolean[][] positionMove = new Boolean[8][8];
    	
    	static int turn;
    	static int[] time = new int[2];
    	static int[] gold = new int[2];
    	static int[] score = new int[2];
    	
    	static int timeSet = 600;
    
        // The object we will use to write with instead of the standard screen graphics 
        Graphics bufferGraphics; 
        // The image that will contain everything that has been drawn on 
        // bufferGraphics. 
        Image offscreen; 
        // x and y of mouse
        int curX, curY;
    
        public void init()  
        { 
             // We'll redraw the applet eacht time the mouse has moved. 
             addMouseListener(this);
     	     addMouseMotionListener(this); 
             // Create an offscreen image to draw on 
             // Make it the size of the applet, this is just perfect larger 
             // size could slow it down unnecessary. 
             offscreen = createImage(768,768); 
             // by doing this everything that is drawn by bufferGraphics 
             // will be written on the offscreen image. 
             bufferGraphics = offscreen.getGraphics(); 
             
             repaint();
        }
    
         public void paint(Graphics g)  
         {
        	 bufferGraphics.clearRect(0,0,768,768); 
        	 
    			for(int y = 0; y < 8; y++)
    			{
    					for(int x = 0; x < 8; x++)
    					{
    						/*
    						Graphics2D g2 = (Graphics2D) bufferGraphics;
    						g2.setStroke(new BasicStroke(4));*/
    						
    							if(x % 2 == 1 && y % 2 == 1 || x % 2 == 0 && y % 2 == 0)
    							{
    								bufferGraphics.setColor(colorOne);
    								bufferGraphics.fillRect(x*60,y*60,60,60);
    							}
    							else
    							{
    								bufferGraphics.setColor(colorTwo);
    								bufferGraphics.fillRect(x*60,y*60,60,60);
    							}
    							
    							// highlight chosen square
    							if(positionChosen[x][y] == true)
    							{
    								bufferGraphics.drawImage(getToolkit().getImage("highlightPiece.png"), x*60, y*60, null);
    							}
    							// highlight available moves
    							if(positionMove[x][y] == true)
    							{
    								bufferGraphics.drawImage(getToolkit().getImage("highlightMove.png"), x*60, y*60, null);
    							}
    							
    							// draw circles
    							if(position[x][y].charAt(0) == 'b')
    							{
    								bufferGraphics.setColor(colorPieceOne);
    								bufferGraphics.fillOval(x*60+5,y*60+5,50,50);
    							}
    							else if(position[x][y].charAt(0) == 'w')
    							{
    								bufferGraphics.setColor(colorPieceTwo);
    								bufferGraphics.fillOval(x*60+5,y*60+5,50,50);
    							}
    							
    							bufferGraphics.setColor(Color.black);
    						
    							// draw pawns
    							if(position[x][y].charAt(1) == 'p')
    							{
    									if(position[x][y].charAt(0) == 'b')
    									{
    										bufferGraphics.setColor(Color.white);
    										bufferGraphics.fillRect(x*60+29,y*60+30,4,20);
    										bufferGraphics.setColor(Color.black);
    										bufferGraphics.drawLine(x*60+30,y*60+30,x*60+16,y*60+44);
    										bufferGraphics.drawLine(x*60+31,y*60+30,x*60+44,y*60+44);
    									}
    									else
    									{
    										bufferGraphics.setColor(Color.white);
    										bufferGraphics.fillRect(x*60+29,y*60+10,4,20);
    										bufferGraphics.setColor(Color.black);
    										bufferGraphics.drawLine(x*60+30,y*60+30,x*60+16,y*60+16);
    										bufferGraphics.drawLine(x*60+31,y*60+30,x*60+44,y*60+16);
    									}
    									
    									if(position[x][y].charAt(2) == '1')
    									{
    										bufferGraphics.fillRect(x*60+28,y*60+10,4,40);
    										bufferGraphics.fillRect(x*60+10,y*60+28,40,4);
    									}
    									if(position[x][y].charAt(3) == '1')
    									{
    										bufferGraphics.drawLine(x*60+15,y*60+15,x*60+45,y*60+45);
    										bufferGraphics.drawLine(x*60+45,y*60+15,x*60+15,y*60+45);
    									}
    									if(position[x][y].charAt(4) == '1')
    									{
    										bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    										bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    										bufferGraphics.fillRect(x*60+16,y*60+10,4,40);
    										bufferGraphics.fillRect(x*60+40,y*60+10,4,40);
    										bufferGraphics.fillRect(x*60+10,y*60+16,40,4);
    										bufferGraphics.fillRect(x*60+10,y*60+40,40,4);
    									}
    									if(position[x][y].charAt(5) == '1')
    									{
    										bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    										bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    										bufferGraphics.drawLine(x*60+22,y*60+22,x*60+38,y*60+38);
    										bufferGraphics.drawLine(x*60+38,y*60+22,x*60+22,y*60+38);
    										
    										/* TOO BIG
    										 * g.drawLine(x*60+20,y*60+20,x*60+40,y*60+40);
    										 * g.drawLine(x*60+40,y*60+20,x*60+20,y*60+40);*/
    									}
    										
    							}
    							
    							// draw rooks
    							if(position[x][y].charAt(1) == 'r')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+10,y*60+28,40,4);
    							}
    							// draw knights
    							if(position[x][y].charAt(1) == 'k')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    								bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    								bufferGraphics.fillRect(x*60+16,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+40,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+10,y*60+16,40,4);
    								bufferGraphics.fillRect(x*60+10,y*60+40,40,4);
    							}
    							// draw bishops
    							if(position[x][y].charAt(1) == 'b')
    							{
    								bufferGraphics.drawLine(x*60+15,y*60+15,x*60+45,y*60+45);
    								bufferGraphics.drawLine(x*60+45,y*60+15,x*60+15,y*60+45);
    							}
    							// draw queens
    							if(position[x][y].charAt(1) == 'q')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+10,y*60+28,40,4);
    								bufferGraphics.drawLine(x*60+15,y*60+15,x*60+45,y*60+45);
    								bufferGraphics.drawLine(x*60+45,y*60+15,x*60+15,y*60+45);
    							}
    							// draw kings
    							if(position[x][y].charAt(1) == 'w')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    								bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    								bufferGraphics.drawLine(x*60+22,y*60+22,x*60+38,y*60+38);
    								bufferGraphics.drawLine(x*60+38,y*60+22,x*60+22,y*60+38);
    							}
    					}		
    			}
             
             // draw the offscreen image to the screen like a normal image. 
             // Since offscreen is the screen width we start at 0,0. 
             g.drawImage(offscreen,0,0,this); 
        }
    
        // Always required for good double-buffering. 
        // This will cause the applet not to first wipe off 
        // previous drawings but to immediately repaint. 
        // the wiping off also causes flickering. 
        // Update is called automatically when repaint() is called.
    
        public void update(Graphics g) 
        { 
             paint(g); 
        } 
    
    	public Image createImage(String img)
    	{
    		Dimension size = new Dimension();
    		Image image = new ImageIcon(this.getClass().getResource(img)).getImage();
    		size.width = image.getWidth(null);
    		size.width = image.getWidth(null);
    		setPreferredSize(size);
    		return image;
    	}
    	public void actionPerformed(ActionEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mouseDragged(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mouseMoved(MouseEvent e) 
    	{
    		 curX = e.getX(); 
             curY = e.getY();
             showStatus(curX + " " + curY);
             repaint();
    	}
    	public void mouseClicked(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    		for(int y = 0; y < 8; y++)
    		{
    				for(int x = 0; x < 8; x++)
    				{
    					positionChosen[x][y] = false;
    					positionMove[x][y] = false;
    				}
    		}
    		
    		positionX = (int)(e.getX()/60);
    		positionY = (int)(e.getX()/60);
    		
    		positionChosen[positionX][positionY] = true;
    		
    		repaint();
    	}
    	public void mouseEntered(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mouseExited(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub	
    	}
    	public void mouseReleased(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mousePressed(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	
    }
    Last edited by Parkournerd; 01-12-2012 at 03:20 AM.

  2. #2
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    I updated the post, now I only need help with my double buffering, nothing is showing up

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,781
    Rep Power
    25

    Default Re: Double-buffering and mouse=event help please

    Why does classAppBoard extend JApplet?

  4. #4
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    I changed it back, I thought it might have done something. Do you get why nothing shows up? Am I using the right code to display from the bufferedImage?

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,781
    Rep Power
    25

    Default Re: Double-buffering and mouse=event help please

    When are the methods in the ClassAppBoard called? Add some printlns to them to see.

  6. #6
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    It's a problem with being called from within the main class. I'm trying to make an applet a component in the main JFrame. This is how to do it? Applet appBoard = new classAppBoard();
    The Applet works as a standalone applet after I run newGame(), but it's white when I run it from the main class.

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,781
    Rep Power
    25

    Default Re: Double-buffering and mouse=event help please

    When are the methods in the ClassAppBoard called? Add some printlns to them to see.
    Did you see this question? Did you add some printlns to the mehtods in ClassAppBoard? What printed?

    Do you understand how Applets work? Their methods are called by a browser. Is there a browser in your app?

  8. #8
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    The methods in classAppBoard are working though. I don't understand how they work. What would I use in this case instead of an Applet?

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,781
    Rep Power
    25

    Default Re: Double-buffering and mouse=event help please

    The methods in classAppBoard are working
    What prints out when you execute the program?
    Where is there any code that calls the init() method?

  10. #10
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    Do you mean the errors?


    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at classAppBoard.paint(classAppBoard.java:61)
    at sun.awt.RepaintArea.paintComponent(Unknown Source)
    at sun.awt.RepaintArea.paint(Unknown Source)
    at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,781
    Rep Power
    25

    Default Re: Double-buffering and mouse=event help please

    Those errors are the reason it's white when I run it from the main

    If you want to "run" an applet from an application, you need to provide the support the browser does.
    That includes having an AppletStub and AppletContext for the applet code to use. Also you will need to call the various applet methods that the browser calls.

    Another way to share code between applets and applications is to move the code into a class that extends JPanel and then you can add/use that code in either the applet or the application
    DarrylBurke likes this.

  12. #12
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    Can you help me do that please?

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,781
    Rep Power
    25

    Default Re: Double-buffering and mouse=event help please

    DO what? I mentioned two ways to do it.
    The simplest is to change the extends from JApplet to JPanel
    and call the init() method from the ProChess class.

    That's it for me tonight.
    Back tomorrow.

  14. #14
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    Thanks man. Sorry for frustrating you, but I've only been doing this for a few months. Merci Beacucoup =).

  15. #15
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: Double-buffering and mouse=event help please

    FYI all that double buffering means is that you draw to an offscreen image rather than to the screen. If you draw to a bufferedImage for example, and after drawing is complete, render the bufferedImage, you have just implemented a simple double buffering system. However, JComponents have this functionality built in, and using a BufferStrategy, you can specify the particulars of double or triple buffering, and then use the built in methods to notify the window that it is ok to refresh.

  16. #16
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    Yes, I know that, thanks; I did Visual Basic :P. It works within the Applet, but now my only problem is that I can't get the Applet inside the JFrame ... yet. But, it's about time to sleep so goodnight man =).

  17. #17
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: Double-buffering and mouse=event help please

    If you're working from within a JFrame anyway, why use an applet at all? They're a huge pain in the ass IMHO.
    Fubarable likes this.

  18. #18
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    I don't know type of component I need to make that Applet class. I tried making it a JPanel, but it didn't work, so I think there's more to do than just that.

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Double-buffering and mouse=event help please

    Quote Originally Posted by Parkournerd View Post
    I don't know type of component I need to make that Applet class.
    As has been stated many times, if you're creating a stand-alone program, you don't need to make that Applet class.

    I tried making it a JPanel, but it didn't work, so I think there's more to do than just that.
    If this isn't working, you may want to show us your attempt, else we won't be able to help you fix the problem.

  20. #20
    Parkournerd is offline Member
    Join Date
    Jan 2012
    Posts
    20
    Rep Power
    0

    Default Re: Double-buffering and mouse=event help please

    Java Code:
    /*name:
      date: Dec 16 2011
      purpose: proChess*/
    
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class proChess extends JFrame implements ActionListener
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 8828135172836094084L;
    	
    	static JFrame frameProChess = new JFrame("ProChess");
    		// all items in window
    		static Panel panelProChess = new Panel();
    			static JLabel iconTitle = new JLabel(createImageIcon("iconLogo.png")); 
    			static Panel panelDisplay = new Panel(new GridLayout(3,1));
    				static JLabel labelPlayer1;
    				static JLabel labelPlayer2;
    				static JLabel labelTurn;
    			static JLabel labelPromotionTitle;
    			static Panel panelChoice = new Panel(new GridLayout(1,4));
    				static JButton buttonChoice1 = new JButton();
    				static JButton buttonChoice2 = new JButton();
    				static JButton buttonChoice3 = new JButton();
    				static JButton buttonChoice4 = new JButton();
    	
    	static JFrame frameHelp = new JFrame("Help");
    	static boolean bolHelp = false;
    	static JFrame frameSetting = new JFrame("Settings");
    	static boolean bolSetting = false;
    
    	public static void main(String[] args) 
    	{
    		@SuppressWarnings("unused")
    		proChess proChess = new proChess();
    	}
    	
    	@SuppressWarnings("deprecation")
    	public proChess()
    	{	
    		newGame();
    		
            
    		// Menu
    		JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    		JMenuBar JMenuBar = new JMenuBar();
    		frameProChess.setJMenuBar(JMenuBar);
    			JMenu menuMenu = new JMenu("Menu");
    				JMenuItem itemNewGame = new JMenuItem("New Game");
    				menuMenu.add(itemNewGame);
    				itemNewGame.setActionCommand ("New Game");
    				itemNewGame.addActionListener((ActionListener)this);
    				JMenuItem itemSaveGame = new JMenuItem("Save Game");
    				menuMenu.add(itemSaveGame);
    				itemSaveGame.setActionCommand ("Save Game");
    				itemSaveGame.addActionListener((ActionListener)this);
    				JMenuItem itemLoadGame = new JMenuItem("Load Game");
    				menuMenu.add(itemLoadGame);
    				itemLoadGame.setActionCommand ("Load Game");
    				itemLoadGame.addActionListener((ActionListener)this);
    				JMenuItem itemSetting = new JMenuItem("Settings");
    				itemSetting.setActionCommand ("Settings");
    				itemSetting.addActionListener((ActionListener)this);
    				menuMenu.add(itemSetting);
    				JMenuBar.add(menuMenu);
    			JMenu menuHelp = new JMenu("Help");
    				JMenuItem itemHelp = new JMenuItem("Help");
    				menuHelp.add(itemHelp);
    				itemHelp.setActionCommand ("Help");
    				itemHelp.addActionListener((ActionListener)this);
    				JMenuBar.add(menuHelp);
    		
    		// disable auto layout
    		panelProChess.setLayout(null);
    		
    			/* Not as good on XP
    			 *try 
    			 *{
    			 *	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    			 *}catch(Exception e){}
    			 */
    			 
    		iconTitle = new JLabel(createImageIcon("iconLogo.png"));
    		
    		Applet panelBoard = new classAppBoard();
    		
    		labelPlayer2 = new JLabel("<html><u>Player 2</u><br><br>Time:<br>Gold:<br>Score:</html>");
    		panelDisplay.add(labelPlayer2);			
    		labelPlayer1 = new JLabel("<html><u>Player 1</u><br><br>Time:<br>Gold:<br>Score:</html>");
    		panelDisplay.add(labelPlayer1);
    		labelTurn = new JLabel("It is Player 1's turn.");
    		panelDisplay.add(labelTurn);
    
    		// Segment Three
    		labelPromotionTitle = new JLabel("<html><u>Promotion</u></html>");
    
    		buttonChoice1 = new JButton();
    		panelChoice.add(buttonChoice1);
    		buttonChoice2 = new JButton();
    		panelChoice.add(buttonChoice2);
    		buttonChoice3 = new JButton();
    		panelChoice.add(buttonChoice3);
    		buttonChoice4 = new JButton();
    		panelChoice.add(buttonChoice4);
    
    		panelProChess.add(iconTitle);
    		iconTitle.setBounds(15,15,484,107);
    		panelProChess.add(panelBoard);
    		panelBoard.setBounds(15,122,480,480);
    		panelProChess.add(panelDisplay);
    		panelDisplay.setBounds(514,0,254,768);
    		panelProChess.add(labelPromotionTitle);
    		labelPromotionTitle.setBounds(225,621,63,18);
    		panelProChess.add(panelChoice);
    		panelChoice.setBounds(135,653,242,60);
    
    		frameProChess.add(panelProChess);
    		
    		frameProChess.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frameProChess.pack();
    		frameProChess.resize(768,768);
    		frameProChess.setLocationRelativeTo(null);
    		frameProChess.setResizable(false);
    		frameProChess.setVisible(true);
    	}
    	public static void newGame()
    	{
    			// reset board
    			for(int y = 0; y < 8; y++)
    			{
    					for(int x = 0; x < 8; x++)
    					{
    						classAppBoard.position[x][y] = "      ";
    						classAppBoard.positionChosen[x][y] = false;
    						classAppBoard.positionMove[x][y] = false;
    					}
    			}
    			
    		// positions pawns for black
    		int y = 1;
    		
    			for(int x = 0; x < 8; x++)
    			{
    				classAppBoard.position[x][y] = "bp0000";
    			}
    			
    		// positions pawns for white
    		y = 6;
    			
    			for(int x = 0; x < 8; x++)
    			{
    				classAppBoard.position[x][y] = "wp0000";
    			}
    			
    		// positions pieces for black
    		classAppBoard.position[0][0] = "br";
    		classAppBoard.position[1][0] = "bk";
    		classAppBoard.position[2][0] = "bb";
    		classAppBoard.position[3][0] = "bq";
    		classAppBoard.position[4][0] = "bw";
    		classAppBoard.position[5][0] = "bb";
    		classAppBoard.position[6][0] = "bk";
    		classAppBoard.position[7][0] = "br";
    		
    		// positions pieces for white	
    		classAppBoard.position[0][7] = "wr";
    		classAppBoard.position[1][7] = "wk";
    		classAppBoard.position[2][7] = "wb";
    		classAppBoard.position[3][7] = "wq";
    		classAppBoard.position[4][7] = "ww";
    		classAppBoard.position[5][7] = "wb";
    		classAppBoard.position[6][7] = "wk";
    		classAppBoard.position[7][7] = "wr";
    		
    		classAppBoard.turn = 1;
    		
    			for(int x = 0; x < 2; x++)
    			{
    				classAppBoard.time[x] = classAppBoard.timeSet;
    				classAppBoard.gold[x] = 0;
    				classAppBoard.score[x] = 0;
    			}
    	}
    	public void saveGame()
    	{
    
    	}
    	public void loadGame()
    	{
    		
    	}
    	public void actionPerformed(ActionEvent e) 
    	{
    			if(e.getActionCommand().equals ("New Game"))
    			{
    				newGame();
    			}
    			if(e.getActionCommand().equals ("Save Game"))
    			{
    				saveGame();
    			}
    			if(e.getActionCommand().equals ("Load Game"))
    			{
    				loadGame();
    			}			
    			if(e.getActionCommand().equals ("Help"))
    			{
    					if(frameHelp.isVisible() == false && bolHelp == false)
    					{
    						bolHelp = true;						
    						@SuppressWarnings("unused")
    						JFrame FrameHelp = new classFrameHelp();
    					}
    					else
    						frameHelp.setVisible(true);
    			}
    			if(e.getActionCommand().equals ("Settings"))
    			{
    					if(frameSetting.isVisible() == false && bolSetting == false)
    					{
    						bolSetting = true;
    						@SuppressWarnings("unused")
    						JFrame FrameSettings = new classFrameSettings();
    					}
    					else 
    						frameSetting.setVisible(true);
    			}
    	}
    	protected static ImageIcon createImageIcon (String path)
    	{
    		java.net.URL imgURL = proChess.class.getResource (path);
    		
    			if (imgURL != null)
    			{
    				return new ImageIcon (imgURL);
    			}
    			else
    			{
    				System.err.println ("Couldn't find file: " + path);
    				return null;
    			}
    	}
    }
    Java Code:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Point2D;
    
    public class classAppBoard extends Applet implements ActionListener, MouseListener, MouseMotionListener
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = -4529456824050911554L;
    	
    	static Color colorOne = Color.white;
    	static Color colorTwo = Color.black;
    	
    	static Color colorPieceOne = Color.blue;
    	static Color colorPieceTwo = Color.green;
    	static Color colorAlpha = new Color(0,0,0,0);
    	
    	static int positionX = 0;
    	static int positionY = 0;
    	static String[][] position = new String[8][8];
    	static Boolean[][] positionChosen = new Boolean[8][8];
    	static Boolean[][] positionMove = new Boolean[8][8];
    	
    	static int turn;
    	static int[] time = new int[2];
    	static int[] gold = new int[2];
    	static int[] score = new int[2];
    	
    	static int timeSet = 600;
    
        // The object we will use to write with instead of the standard screen graphics 
        Graphics bufferGraphics = null; 
        // The image that will contain everything that has been drawn on 
        // bufferGraphics. 
        Image offscreen = null; 
        
        // x and y of mouse
        int curX, curY;
    
        public void init()  
        {         
        	addMouseListener(this);
     	    addMouseMotionListener(this);
     	    proChess.newGame(); 
        	resize(480,480);
    
            offscreen = createImage(768,768); 
            bufferGraphics = offscreen.getGraphics(); 
            repaint();
        }
    
         public void paint(Graphics g)  
         {
        	 bufferGraphics.clearRect(0,0,768,768); 
        	 
    			for(int y = 0; y < 8; y++)
    			{
    					for(int x = 0; x < 8; x++)
    					{
    
    						Graphics2D g2 = (Graphics2D) bufferGraphics;
    						g2.setStroke(new BasicStroke(4));
    						
    							if(x % 2 == 1 && y % 2 == 1 || x % 2 == 0 && y % 2 == 0)
    							{
    								bufferGraphics.setColor(colorOne);
    								bufferGraphics.fillRect(x*60,y*60,60,60);
    							}
    							else
    							{
    								bufferGraphics.setColor(colorTwo);
    								bufferGraphics.fillRect(x*60,y*60,60,60);
    							}
    							
    							// highlight chosen square
    							if(positionChosen[x][y] == true)
    							{
    								((Graphics2D) bufferGraphics).setPaint(generateRadialGradient(Color.orange,x,y));
    								bufferGraphics.fillOval(x*60-10,y*60-10,90,90);
    							}
    							// highlight available moves
    							if(positionMove[x][y] == true)
    							{
    								((Graphics2D) bufferGraphics).setPaint(generateRadialGradient(Color.red,x,y));
    								bufferGraphics.fillOval(x*60-10,y*60-10,90,90);
    							}
    							
    							// draw circles
    							if(position[x][y].charAt(0) == 'b')
    							{
    								((Graphics2D) bufferGraphics).setPaint(generateGradient(colorPieceOne,x,y));
    								bufferGraphics.fillOval(x*60+5,y*60+5,50,50);
    							}
    							else if(position[x][y].charAt(0) == 'w')
    							{
    								((Graphics2D) bufferGraphics).setPaint(generateGradient(colorPieceTwo,x,y));
    								bufferGraphics.fillOval(x*60+5,y*60+5,50,50);
    							}
    							
    							bufferGraphics.setColor(Color.black);
    						
    							// draw pawns
    							if(position[x][y].charAt(1) == 'p')
    							{
    									if(position[x][y].charAt(0) == 'b')
    									{
    										bufferGraphics.setColor(Color.white);
    										bufferGraphics.fillRect(x*60+29,y*60+30,4,20);
    										bufferGraphics.setColor(Color.black);
    										bufferGraphics.drawLine(x*60+30,y*60+30,x*60+16,y*60+44);
    										bufferGraphics.drawLine(x*60+31,y*60+30,x*60+44,y*60+44);
    									}
    									else
    									{
    										bufferGraphics.setColor(Color.white);
    										bufferGraphics.fillRect(x*60+29,y*60+10,4,20);
    										bufferGraphics.setColor(Color.black);
    										bufferGraphics.drawLine(x*60+30,y*60+30,x*60+16,y*60+16);
    										bufferGraphics.drawLine(x*60+31,y*60+30,x*60+44,y*60+16);
    									}
    									
    									if(position[x][y].charAt(2) == '1')
    									{
    										bufferGraphics.fillRect(x*60+28,y*60+10,4,40);
    										bufferGraphics.fillRect(x*60+10,y*60+28,40,4);
    									}
    									if(position[x][y].charAt(3) == '1')
    									{
    										bufferGraphics.drawLine(x*60+15,y*60+15,x*60+45,y*60+45);
    										bufferGraphics.drawLine(x*60+45,y*60+15,x*60+15,y*60+45);
    									}
    									if(position[x][y].charAt(4) == '1')
    									{
    										bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    										bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    										bufferGraphics.fillRect(x*60+16,y*60+10,4,40);
    										bufferGraphics.fillRect(x*60+40,y*60+10,4,40);
    										bufferGraphics.fillRect(x*60+10,y*60+16,40,4);
    										bufferGraphics.fillRect(x*60+10,y*60+40,40,4);
    									}
    									if(position[x][y].charAt(5) == '1')
    									{
    										bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    										bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    										bufferGraphics.drawLine(x*60+22,y*60+22,x*60+38,y*60+38);
    										bufferGraphics.drawLine(x*60+38,y*60+22,x*60+22,y*60+38);
    										
    										/* TOO BIG
    										 * g.drawLine(x*60+20,y*60+20,x*60+40,y*60+40);
    										 * g.drawLine(x*60+40,y*60+20,x*60+20,y*60+40);*/
    									}	
    							}
    							
    							// draw rooks
    							if(position[x][y].charAt(1) == 'r')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+10,y*60+28,40,4);
    							}
    							// draw knights
    							if(position[x][y].charAt(1) == 'k')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    								bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    								bufferGraphics.fillRect(x*60+16,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+40,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+10,y*60+16,40,4);
    								bufferGraphics.fillRect(x*60+10,y*60+40,40,4);
    							}
    							// draw bishops
    							if(position[x][y].charAt(1) == 'b')
    							{
    								bufferGraphics.drawLine(x*60+15,y*60+15,x*60+45,y*60+45);
    								bufferGraphics.drawLine(x*60+45,y*60+15,x*60+15,y*60+45);
    							}
    							// draw queens
    							if(position[x][y].charAt(1) == 'q')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+10,4,40);
    								bufferGraphics.fillRect(x*60+10,y*60+28,40,4);
    								bufferGraphics.drawLine(x*60+15,y*60+15,x*60+45,y*60+45);
    								bufferGraphics.drawLine(x*60+45,y*60+15,x*60+15,y*60+45);
    							}
    							// draw kings
    							if(position[x][y].charAt(1) == 'w')
    							{
    								bufferGraphics.fillRect(x*60+28,y*60+20,4,20);
    								bufferGraphics.fillRect(x*60+20,y*60+28,20,4);
    								bufferGraphics.drawLine(x*60+22,y*60+22,x*60+38,y*60+38);
    								bufferGraphics.drawLine(x*60+38,y*60+22,x*60+22,y*60+38);
    							}
    					}		
    			}
             // draw the offscreen image to the screen like a normal image. 
             // Since offscreen is the screen width we start at 0,0. 
             g.drawImage(offscreen,0,0,this); 
        }
        public void update(Graphics g) 
        { 
             paint(g); 
        } 
        public GradientPaint generateGradient(Color c, int x,int y)
        {
        	GradientPaint gradient = new GradientPaint(x*60+5,y*60+5,c,x*60+30,y*60+30,Color.gray,true);
    		return gradient;
        }
        public RadialGradientPaint generateRadialGradient(Color c, int x,int y)
        {
        	Point2D center = new Point2D.Float(x*60+30, y*60+30);
            float radius = 45;
            float[] dist = {0.0f, 1f};
            Color[] colors = {c, colorAlpha};
        	RadialGradientPaint gradient = new RadialGradientPaint(center, radius, dist, colors);
    		return gradient;
        }
    	/*public Image createImage(String img)
    	{
    		Dimension size = new Dimension();
    		Image image = new ImageIcon(this.getClass().getResource(img)).getImage();
    		size.width = image.getWidth(null);
    		size.width = image.getWidth(null);
    		setPreferredSize(size);
    		return image;
    	}*/
    	public void actionPerformed(ActionEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mouseDragged(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mouseMoved(MouseEvent e) 
    	{
    		 curX = e.getX(); 
             curY = e.getY();
             showStatus(curX + " " + curY);
             repaint();
    	}
    	public void mouseClicked(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    		for(int y = 0; y < 8; y++)
    		{
    				for(int x = 0; x < 8; x++)
    				{
    					positionChosen[x][y] = false;
    					positionMove[x][y] = false;
    				}
    		}
    		
    		positionX = (int)(e.getX()/60);
    		positionY = (int)(e.getY()/60);
    		
    		positionChosen[positionX][positionY] = true;
    		
    		repaint();
    	}
    	public void mouseEntered(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mouseExited(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub	
    	}
    	public void mouseReleased(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	public void mousePressed(MouseEvent e) 
    	{
    		// TODO Auto-generated method stub
    	}
    	
    }
    There's the current code I have. Is there any way to keep classAppBoard in its own class? I'm doing this for organization's sake.

Page 1 of 2 12 LastLast

Similar Threads

  1. Double Buffering
    By Macpwnage in forum Java 2D
    Replies: 8
    Last Post: 07-18-2011, 10:17 PM
  2. Help with double Buffering
    By Kyle227 in forum AWT / Swing
    Replies: 1
    Last Post: 10-26-2010, 10:08 PM
  3. Double Buffering an Application?
    By Moncleared in forum New To Java
    Replies: 8
    Last Post: 09-14-2009, 05:45 AM
  4. Double Buffering
    By dunff2k in forum SWT / JFace
    Replies: 1
    Last Post: 11-14-2008, 04:26 PM
  5. Double Buffering problem
    By aprenz in forum Java Applets
    Replies: 0
    Last Post: 05-28-2008, 05:26 AM

Posting Permissions

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