3 Replies - 317 Views - Last Post: 21 April 2013 - 09:35 AM Rate Topic: -----

#1 josephine11  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 01-September 12

errors with addTextToTextPane() not placing text on display

Posted 21 April 2013 - 12:03 AM

ok, well I had to modify the program I wrote to play a dice into a swing program, however, everything is ok, apart from getting the results to display on the panel after the game has been played. I have used a else to insert these, but I'm pretty sure I way off!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;

 
public class DieGame2 extends JFrame implements ActionListener{

		//Declare and intialize data
		String result;
		int player, computer;
		double bet, roll, currentAmount, answer;
		double startingAmount = 500.0;
		int counter =1;
		double remainingAmount = 0.0;
		boolean done = false;
		double [] balance = new double[50];
		int arrayLength =0;
		//construct components
		JTextPane displayPane = new JTextPane();
		
		//construct instance
		public DieGame2(){
			super(" Dice Game");
		}
		
		public Container createContentPane(){
			//construct and populate main panel
			JPanel mainPanel = new JPanel();
			mainPanel.setLayout (new FlowLayout());
			displayPane = addTextToTextPane();
			JScrollPane scrollPane = new JScrollPane(displayPane);
			scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			scrollPane.setWheelScrollingEnabled(true);
			scrollPane.setPreferredSize(new Dimension(300, 300));
			mainPanel.add(scrollPane);
			Container c = getContentPane();
			c.setLayout(new FlowLayout());
			c.add(mainPanel);
		
		return c;
		
		}//end container
		public JTextPane addTextToTextPane(){
		
		Document doc = displayPane.getDocument();
			
			try{
				//The following lines generate JTextPane attributes on-the-fly
				//to simplify adding text to the JTextPane
				StyleContext style = StyleContext.getDefaultStyleContext();
				AttributeSet set = style.addAttribute(SimpleAttributeSet.EMPTY,StyleConstants.ALIGN_LEFT,style);
				displayPane.setParagraphAttributes(set,false);
				
				//clear previous text
				doc.remove(0,doc.getLength());
		
				for(int lcv = 0; lcv < arrayLength; lcv++)
				{
					doc.insertString(doc.getLength(), String.valueOf(balance[lcv])+ "\n" ,set);
				}
				
				if(!done)// information to display before game is played
				{
						double calculateBalance = calculateBalance();
						doc.insertString(doc.getLength(),"Let's play!. Your starting balance is "+ startingAmount +"\n",set);
						doc.insertString(doc.getLength(),"Hit 'File' and then 'New Game' "+"\n",set);
				}
				else{//information to display after game is played
						doc.insertString(doc.getLength(),"Your rolled a:"+ player + "\n",set);
						doc.insertString(doc.getLength(),"The computer rolled a:"+ computer + "\n",set);
						doc.insertString(doc.getLength(),"You"+ result + bet+ "\n",set);
						doc.insertString(doc.getLength(),"Your remaining balance is"+ calculateBalance()+ "\n",set);

				}
				
				
				}//end try

				catch(BadLocationException ble)
				{
					System.err.println("Couldn't start game.");
				}
			return displayPane;
		}//end public JTextPane addTextToTextPane() 
		
		public JMenuBar createMenuBar(){
		 
			// Create an instance of the menu
			JMenuBar mnuBar = new JMenuBar();
			setJMenuBar(mnuBar);
			
			//Construct and add the File menu
			JMenu mnuFile = new JMenu("File");
				mnuFile.setMnemonic(KeyEvent.VK_F);
				mnuFile.setDisplayedMnemonicIndex(0);
				mnuBar.add(mnuFile);
				
			//Construct and add the menu command to add measurements
			JMenuItem mnuFileNewGrades = new JMenuItem("New Game");
				mnuFileNewGrades.setMnemonic(KeyEvent.VK_W);
				mnuFileNewGrades.setDisplayedMnemonicIndex(0);
				mnuFile.add(mnuFileNewGrades);
				mnuFileNewGrades.setActionCommand("NewGame");
				mnuFileNewGrades.addActionListener(this);
			
			//Construct and add the Exit Command
			JMenuItem mnuFileExit = new JMenuItem("Exit");
				mnuFileExit.setMnemonic(KeyEvent.VK_X);
				mnuFileExit.setDisplayedMnemonicIndex(1);
				mnuFile.add(mnuFileExit);
				mnuFileExit.setActionCommand("Exit");
				mnuFileExit.addActionListener(this);
			
			return mnuBar;
		} // end public JMenuBar createMenuBar()


	     
		public void actionPerformed(ActionEvent e){ 
		
			String arg = e.getActionCommand();
					
			if(arg.equals("NewGame")){//begin if new measurement is clicked
			
				while (startingAmount != 0.0){  //while the starting amount is not zero play game
				
					bet = getMoney();//receive bet amount
					
					//generate random numbers for player.
					player = 1+(int)(Math.random()*12);
					System.out.println("Your Roll is:" +player);
				 
					//generate random numbers for the computer.
					computer = 2+(int)(Math.random()*12);
				   System.out.println("Computer's Roll is:" + computer );

					//calculate results
					if(player == computer && player > 7)
					{
						remainingAmount = startingAmount += bet;
						balance[counter] = remainingAmount;
						counter = counter + 1;
						result = ("Win");
						System.out.println("YOU WIN !");
						System.out.println("You Won: $"+bet);
						System.out.println("Your remaining balance is: $" + remainingAmount);
						done = true;
	
					} 
					else if (computer == player && player <7)
					{
						remainingAmount = startingAmount -= bet;
						balance [counter] = remainingAmount;
						counter = counter + 1;
						result = ("Lose");
						System.out.println("YOU LOSE");
						System.out.println("You Lost: $"+bet);
						System.out.println("Your remaining balance is:$"+ remainingAmount);
						done = true;
	
					}
					else if(computer == player && player ==7)
					{
						System.out.println("IT'S A TIE!");
						result = ("Both Win");
						System.out.println("Your remaining balance is:$"+ remainingAmount);
						done = true;
					}
					else if(computer > player)
					{
						remainingAmount = startingAmount -= bet;
						balance [counter] =remainingAmount;
						counter = counter + 1;
						result = ("Lose");
						System.out.println("YOU LOSE");
						System.out.println("You Lost: $"+bet);
						System.out.println("Your remaining balance is:$"+ remainingAmount);	
						done = true;
					}
					else if(computer < player)
					{
						remainingAmount = startingAmount += bet;
						balance [counter] =remainingAmount;
						counter = counter +1;
						result = ("Win");
						System.out.println("YOU WIN !");
						System.out.println("You Won: $"+bet);
						System.out.println("Your remaining balance is: $" + remainingAmount);
						done = true;
					}
		 		}//end while
			addTextToTextPane();	
			}//end if NewGame Clicked

			if(arg.equals("Exit"))//if exit is clicked 
			{
				System.out.println("Ciao Ciao.");
				System.exit(0);
			}
		}//end actionPerformed
	
	//The getMoney() method asks users to input the bet amount and checks for an entry of zero to end the game
	public double getMoney(){
	         
		//Declare Method Variables
		double bet = 0.0;
		       
		String answer = JOptionPane.showInputDialog(null, "Enter the amount you wish to gamble:");
		bet = Double.parseDouble(answer);
		
		if (bet == 0.0) 
		{
			
			System.out.println("Thank you for playing.  Goodbye!");
			System.exit(0);
		}	
		
	return bet;
	} 
	public double calculateBalance(){
	// keep track of money to calculate balance
		//sum values of array
		double sum = 0, calculateBalance;
		int total = 0;
		
		for(int lcv =0;lcv < balance.length; lcv++){
			if(balance[lcv] > 0)
				sum+= balance[lcv];
		}
		calculateBalance = sum;
	return calculateBalance;
	}
	public static void main(String[] args){
			DieGame2 m = new DieGame2();
			m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			m.setJMenuBar( m.createMenuBar());
			m.setContentPane( m.createContentPane());
			m.setSize(375, 375);
			m.setVisible(true);
		} //end main
}//end DieGame2 class



the error I believe is come from here:
if(!done)// information to display before game is played
				{
						double calculateBalance = calculateBalance();
						doc.insertString(doc.getLength(),"Let's play!. Your starting balance is "+ startingAmount +"\n",set);
						doc.insertString(doc.getLength(),"Hit 'File' and then 'New Game' "+"\n",set);
				}
				else{//information to display after game is played
						doc.insertString(doc.getLength(),"Your rolled a:"+ player + "\n",set);
						doc.insertString(doc.getLength(),"The computer rolled a:"+ computer + "\n",set);
						doc.insertString(doc.getLength(),"You"+ result + bet+ "\n",set);
						doc.insertString(doc.getLength(),"Your remaining balance is"+ calculateBalance()+ "\n",set);

				}



Is This A Good Question/Topic? 0
  • +

Replies To: errors with addTextToTextPane() not placing text on display

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: errors with addTextToTextPane() not placing text on display

Posted 21 April 2013 - 01:32 AM

Does the game play in the console on purpose? You've done a pretty good job of adding GUI around a console game, but why not then add the game play to the GUI? If that's not the goal, say so.

While you ponder that, here are some other suggestions.

This is what the main() method should look like:
	// creates an instance of DieGame2 on the EDT
	public static void main(String[] args)
	{
		SwingUtilities.invokeLater( new Runnable()
		{
			public void run()
			{
				new DieGame2();
			}
		} );
		
	} //end main

Then the constructor would do the work to create and show the GUI:
	//construct instance
	public DieGame2()
	{
		super(" Dice Game");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setJMenuBar( createMenuBar());
		setContentPane( createContentPane());
		setSize(375, 375);

		double calculateBalance = calculateBalance();

                // this could also be moved to a method like
                // playTheGame() that controls game flow and
                // outputs results
		addTextToTextPane( "Let's play!. Your starting balance is "+ startingAmount + "\n" );
		addTextToTextPane( "Hit 'File' and then 'New Game' "+"\n" );

		setVisible(true);
	}

I also included two lines as an example of how I think the method addTextToTextPane() could be used to move the gameplay from the console to the GUI.

There's more work to do, and there could be many variations, but that's a start.

Edit: Looking closer at your code, you do several things that are mind boggling. For example:

Why is the balance an array? Why not just keep track of the balance in a double variable?

The variable arrayLength is an unnecessary hack.

The only time the flag done needs to be set to true is before the final call to addTextToTextPane().

The reason you are not seeing the results you're expecting is because the program is encountering an error before completing. Are you seeing the error? If so, you should fix it, or if you need help with it, you should post the error.

This construction, repeated several times, is making something very simple as hard as possible:
remainingAmount = startingAmount -= bet;
balance [counter] = remainingAmount;
counter = counter + 1;

All of that could be replaced by:

balance -= bet;

This post has been edited by GregBrannon: 21 April 2013 - 09:18 AM

Was This Post Helpful? 2
  • +
  • -

#3 josephine11  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 01-September 12

Re: errors with addTextToTextPane() not placing text on display

Posted 21 April 2013 - 08:30 AM

Yes that did HELP...a whole lot! I have now got the results to show in the DisplayPane. Any ideas how I can align the results in the pane a little better? I tried to put the code in separate line, like this:
displayPane.setText("YOU WIN !");
displayPane.setText("You Won: $"+bet);
displayPane.setText("Your remaining balance is: $" + remainingAmount);

However, it would not display. I ended up putting displaying the text like this:
displayPane.setText(" You Won! You Rolled:   " + player+ ". The Computer Rolled:   " + computer + ". Your remaining balance is: $" + remainingAmount);



This is the program as of now:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;

 
public class DieGame2 extends JFrame implements ActionListener{

		//Declare and intialize data
		String result;
		int player, computer;
		double bet, roll, currentAmount, answer;
		double startingAmount = 500.0;
		double remainingAmount = 0.0;
		boolean done = false;
		int arrayLength =0;
		//construct components
		JTextPane displayPane = new JTextPane();
		
		//construct instance
		public DieGame2(){
			
			super(" Dice Game");
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
			setJMenuBar( createMenuBar()); 
			setContentPane( createContentPane()); 
			setSize(375, 375); 
		
			
			setVisible(true); 

		}
		
		public Container createContentPane(){
			//construct and populate main panel
			JPanel mainPanel = new JPanel();
			mainPanel.setLayout (new FlowLayout());
			displayPane = addTextToTextPane();
			JScrollPane scrollPane = new JScrollPane(displayPane);
			scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			scrollPane.setWheelScrollingEnabled(true);
			scrollPane.setPreferredSize(new Dimension(300, 300));
			mainPanel.add(scrollPane);
			Container c = getContentPane();
			c.setLayout(new FlowLayout());
			c.add(mainPanel);
		
		return c;
		
		}//end container
		public JTextPane addTextToTextPane(){
		
		Document doc = displayPane.getDocument();
			
			try{
				//The following lines generate JTextPane attributes on-the-fly
				//to simplify adding text to the JTextPane
				StyleContext style = StyleContext.getDefaultStyleContext();
				AttributeSet set = style.addAttribute(SimpleAttributeSet.EMPTY,StyleConstants.ALIGN_LEFT,style);
				displayPane.setParagraphAttributes(set,false);
				
				//resents
				doc.remove(0,doc.getLength());
		
				for(int lcv = 0; lcv < arrayLength; lcv++)
				{
					doc.insertString(doc.getLength(), String.valueOf(startingAmount)+ "\n" ,set);
				}
				
				if(!done)// information to display before game is played
				{
						doc.insertString(doc.getLength(),"Let's play!. Your starting balance is "+ startingAmount +"\n",set);
						doc.insertString(doc.getLength(),"Hit 'File' and then 'New Game' "+"\n",set);
						done = true;
				}
								
				
				
				}//end try

				catch(BadLocationException ble)
				{
					System.err.println("Couldn't start game.");
				}
			return displayPane;
		}//end public JTextPane addTextToTextPane() 
		
		public JMenuBar createMenuBar(){
		 
			// Create an instance of the menu
			JMenuBar mnuBar = new JMenuBar();
			setJMenuBar(mnuBar);
			
			//Construct and add the File menu
			JMenu mnuFile = new JMenu("File");
				mnuFile.setMnemonic(KeyEvent.VK_F);
				mnuFile.setDisplayedMnemonicIndex(0);
				mnuBar.add(mnuFile);
				
			//Construct and add the menu command to add measurements
			JMenuItem mnuFileNewGrades = new JMenuItem("New Game");
				mnuFileNewGrades.setMnemonic(KeyEvent.VK_W);
				mnuFileNewGrades.setDisplayedMnemonicIndex(0);
				mnuFile.add(mnuFileNewGrades);
				mnuFileNewGrades.setActionCommand("NewGame");
				mnuFileNewGrades.addActionListener(this);
			
			//Construct and add the Exit Command
			JMenuItem mnuFileExit = new JMenuItem("Exit");
				mnuFileExit.setMnemonic(KeyEvent.VK_X);
				mnuFileExit.setDisplayedMnemonicIndex(1);
				mnuFile.add(mnuFileExit);
				mnuFileExit.setActionCommand("Exit");
				mnuFileExit.addActionListener(this);
			
			return mnuBar;
		} // end public JMenuBar createMenuBar()


	     
		public void actionPerformed(ActionEvent e){ 
		
			String arg = e.getActionCommand();
					
			if(arg.equals("NewGame")){//begin if new measurement is clicked		

				while (startingAmount != 0.0){  //while the starting amount is not zero play game
				
					bet = getMoney();//receive bet amount
					
					//generate random numbers for player.
					player = 1+(int)(Math.random()*12);
				
				 
					//generate random numbers for the computer.
					computer = 2+(int)(Math.random()*12);


					//calculate results
					if(player == computer && player > 7)
					{
						remainingAmount = startingAmount += bet;
						displayPane.setText(" You Won!n You Rolled:   " + player+ ". The Computer Rolled:   " + computer +
						". Your remaining balance is: $" + remainingAmount);
						done = true;
	
					} 
					else if (computer == player && player <7)
					{
						remainingAmount = startingAmount -= bet;
						displayPane.setText(" You Lost!n You Rolled:   " + player+ ". The Computer Rolled:   " + computer +
						". Your remaining balance is: $" + remainingAmount);
						done = true;
	
					}
					else if(computer == player && player ==7)
					{
						displayPane.setText("IT'S A TIE!n  Your remaining balance is:  $"+ remainingAmount);
						done = true;
					}
					else if(computer > player)
					{
						remainingAmount = startingAmount -= bet;
						displayPane.setText(" You Lost!n  You Rolled:   " + player+ ". The Computer rolled:   " + computer +
						". Your remaining balance is: $" + remainingAmount);
						done = true;
					}
					else if(computer < player)
					{
						remainingAmount = startingAmount += bet;
						displayPane.setText(" You Won! You Rolled:   " + player+ ". The Computer Rolled:   " + computer +
						      ". Your remaining balance is: $" + remainingAmount);
						done = true;
					}
		 		}//end while

			}//end if NewGame Clicked

			if(arg.equals("Exit"))//if exit is clicked 
			{
				System.out.println("Ciao Ciao.");
				System.exit(0);
			}
		}//end actionPerformed
	
	//The getMoney() method asks users to input the bet amount and checks for an entry of zero to end the game
	public double getMoney(){
	         
		//Declare Method Variables
		double bet = 0.0;
		       
		String answer = JOptionPane.showInputDialog(null, "Enter the amount you wish to gamble:");
		bet = Double.parseDouble(answer);
		
		if (bet == 0.0) 
		{
			
			System.out.println(" GoodBye. Thank you for playing.Your remaining balance is " + remainingAmount);
			System.exit(0);
		}	
		
	return bet;
	} 

// creates an instance of DieGame2 on the EDT
	public static void main(String[] args){
		SwingUtilities.invokeLater( new Runnable()
		{
			public void run()
			{
				new DieGame2();
			}
		} );
	}//end main
}//end DieGame2 class


Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: errors with addTextToTextPane() not placing text on display

Posted 21 April 2013 - 09:35 AM

Very nice changes. You still have a couple println() statments I wonder about, but nice progress nonetheless. Keep it up!

As for improving the appearance of the output, I recommend you use a JTextArea rather than a JTextPane, because the JTextArea allows you to append text to the text already there. You can also put the JTextArea in a JScrollPane as you're doing now so that the player can see the history of their game. (Of course, you could write a method to add text to a JTextPane, but that's probably partly why the JTextArea was invented. Edit: After refreshing my memory, I remembered that your addTextToTextPane() method could be used to add text to the text pane if the line that clears the text already in the pane was removed. That's why I suggested passing a String to the method.)

If you can't use a JTextArea for some reason, then I'm sure there's a better way. I notice you're not adding linefeeds to your lines of output as you were before. Simply doing that would help the appearance of the output a lot.

Another comment about the main() method: You can create an instance of DieGame2 as you were doing before, and then call a method, like playTheGame(), to control game play. So then, the run() method would look like:
public void run()
{
    DieGame2 dieGame = new DieGame2();
    dieGame.playTheGame();
}

This post has been edited by GregBrannon: 21 April 2013 - 09:57 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1