GIDForums  

Go Back   GIDForums > Computer Programming Forums > Java Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 13-May-2008, 11:14
Barman007 Barman007 is offline
New Member
 
Join Date: May 2008
Posts: 10
Barman007 is on a distinguished road
Unhappy

Trouble integrating console code into GUI


Well my problem is I coded a game and got everything working nicely so I decided I wanted to make a GUI in JFrameBuilder and transfer my code into that. Well I havnt been to sleep and 24 hours later I still cant get the code to work. I made a start button and thought I could just execute all the code from there but that doesnt work and i've run out of ideas how to get it working. I want it to pause and wait for user input where needed etc...

First i'll post my main GUI code then i'll post my working game code main im trying to integrate.

I'd be eternally grateful if anyone has any ideas.
JAVA Code:
package visualassignment2;

 
 import java.awt.*; 
 import java.awt.event.*; 
 import javax.swing.*;
 import boardage.*;
 import EasyIn.*;  
 import java.io.*;

  class Error extends Exception {
    public Error() {
        super("*******ERROR*******\n");
        }
}

class badInput extends Exception {
    public badInput() {
        super("Wrong Input type...  Please try again!\n");
        }
}
 
 public class Main extends JFrame
 { 
 	// Declared variables 
 	private JLabel jLabel1; 
        private JLabel jLabel3; 
 	private JTextField input; 
 	private JTextArea displayScreen; 
 	private JScrollPane jScrollPane1;
        private JProgressBar jProgressBar1;  	 
 	private JButton b1; 
 	private JButton b2; 
 	private JButton b3; 
 	private JButton b4; 
 	private JButton b5; 
 	private JButton b6; 
        private JButton b7;
 	private JPanel  contentPane;
        private board   bd;
 	// End of variables declaration 
  
        //Constructor
 	public Main() 
 	{ 
 		super(); 
 		initializeComponent();  
 		this.setVisible(true);
                bd = new board();
 	} 
  
 	
        //This method is called from within the constructor to initialize the form.
 	private void initializeComponent() 
 	{ 
 		jLabel1 = new JLabel(); 
                jLabel3 = new JLabel(); 
 		input = new JTextField(); 
 		displayScreen = new JTextArea(); 
 		jScrollPane1 = new JScrollPane();
                jProgressBar1 = new JProgressBar();  		 
 		b1 = new JButton();
                
 		b2 = new JButton(); 
 		b3 = new JButton(); 
 		b4 = new JButton(); 
 		b5 = new JButton(); 
 		b6 = new JButton(); 
                b7 = new JButton();
 		contentPane = (JPanel)this.getContentPane();          


  
 		// 
 		// jLabel1 
 		// setting image location
 		jLabel1.setIcon(new ImageIcon("K:\\Portable Start Menu\\Documents\\BInfoTech\\2nd Year\\Java\\visualassignment2\\build\\hanoititle.jpg")); 
 		//
                // jLabel3 
 		// Labels the input on the display
 		jLabel3.setText("Input"); 
                //
 		// jTextField1 
 		// This is where the user input goes
                input.setText("Type here");
 		input.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jTextField1_actionPerformed(e); 
 			} 
  
 		}); 
 		input.addKeyListener(new KeyAdapter() { 
 			public void keyPressed(KeyEvent e) 
 			{ 
 				jTextField1_keyPressed(e); 
 			} 
  
 		}); 
 		// 
 		// jTextArea1 
 		//sets wether the main display for instructions and current gamestate is editable or not
 		displayScreen.setEditable(false);
                // Add display area with scroll bars                
 		// 
 		// jScrollPane1 
 		// scrolls textarea1 when needed
 		jScrollPane1.setViewportView(displayScreen); 
 		// jProgressBar1 
 		// sets the color of the progress bar
 		jProgressBar1.setForeground(new Color(246, 5, 21)); 
 		// 
 		
                // 
 		// jButton1 
 		// Move from peg1 to peg2
 		b1.setBackground(new Color(255, 255, 255)); 
 		b1.setForeground(new Color(0, 0, 0)); 
 		b1.setText("Peg 1 to 2"); 
 		b1.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton1_actionPerformed(e);
 			} 
  
 		}); 
 		// 
 		// jButton2 
 		// Move from peg1 to peg3
 		b2.setBackground(new Color(255, 255, 255)); 
 		b2.setForeground(new Color(0, 0, 0)); 
 		b2.setText("Peg 1 to 3"); 
 		b2.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton2_actionPerformed(e); 
 			} 
  
 		}); 
 		// 
 		// jButton3 
 		// Move from peg2 to peg1
 		b3.setBackground(new Color(255, 255, 255)); 
 		b3.setForeground(new Color(0, 0, 0)); 
 		b3.setText("Peg 2 to 1"); 
 		b3.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton3_actionPerformed(e); 
 			} 
  
 		}); 
 		// 
 		// jButton4 
 		// Move from peg2 to peg3
 		b4.setBackground(new Color(255, 255, 255)); 
 		b4.setForeground(new Color(0, 0, 0)); 
 		b4.setText("Peg 2 to 3"); 
 		b4.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton4_actionPerformed(e); 
 			} 
  
 		}); 
 		// 
 		// jButton5 
 		// Move from peg3 to peg1
 		b5.setBackground(new Color(255, 255, 255)); 
 		b5.setForeground(new Color(0, 0, 0)); 
 		b5.setText("Peg 3 to 1"); 
 		b5.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 			displayScreen.setText("dude, seriously");
	
                            jButton5_actionPerformed(e); 
 			} 
  
 		}); 
 		// 
 		// jButton6 
 		// Move from peg3 to peg2
 		b6.setBackground(new Color(255, 255, 255)); 
 		b6.setForeground(new Color(0, 0, 0)); 
 		b6.setText("Peg 3 to 2"); 
 		b6.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton6_actionPerformed(e); 
 			} 
  
 		}); 
                // 
 		// jButton5 
 		// Start game button
 		b7.setText("START GAME"); 
 		b7.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton7_actionPerformed(e); 
 			} 
  
 		}); 
 		// 
 		// contentPane 
 		// 
 		contentPane.setLayout(null); 
 		contentPane.setBackground(new Color(155, 155, 209)); 
 		addComponent(contentPane, jLabel1, -1,0,526,282);
                addComponent(contentPane, jLabel3, 11,475,65,18);
 		addComponent(contentPane, input, 9,452,228,22); 
 		addComponent(contentPane, jScrollPane1, 9,289,505,155);
                addComponent(contentPane, jProgressBar1, 11,280,503,9);  		
 		addComponent(contentPane, b1, 247,450,83,28); 
 		addComponent(contentPane, b2, 246,485,83,28); 
 		addComponent(contentPane, b3, 338,450,83,28); 
 		addComponent(contentPane, b4, 338,485,83,28); 
 		addComponent(contentPane, b5, 430,450,83,28); 
 		addComponent(contentPane, b6, 430,485,83,28);
                addComponent(contentPane, b7, 66,486,132,25); 
 		// 
 		// Main 
 		// 
 		this.setTitle("The Towers of Hanoi"); 
 		this.setLocation(new Point(112, 32)); 
 		this.setSize(new Dimension(538, 555)); 
 		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
 		this.setResizable(false); 
 	} 
    
 	 
           
            
 	/** Add Component Without a Layout Manager (Absolute Positioning) */ 
 	private void addComponent(Container container,Component c,int x,int y,int width,int height) 
 	{ 
 		c.setBounds(x,y,width,height); 
 		container.add(c); 
 	} 
  
 	// 
 	// TODO: Add any appropriate code in the following Event Handling Methods 
 	// 
 	private void jTextField1_actionPerformed(ActionEvent e) 
 	{ 
 		System.out.println("\njTextField1_actionPerformed(ActionEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
        
        	private void jTextField1_keyPressed(KeyEvent e) 
 	{ 
 		System.out.println("\njTextField1_keyPressed(KeyEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
                
 	private void jButton1_actionPerformed(ActionEvent e) 
 	{
  
 	} 
  
 	private void jButton2_actionPerformed(ActionEvent e) 
 	{ 
 		System.out.println("\njButton2_actionPerformed(ActionEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
  
 	private void jButton3_actionPerformed(ActionEvent e) 
 	{ 
 		System.out.println("\njButton3_actionPerformed(ActionEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
  
 	private void jButton4_actionPerformed(ActionEvent e) 
 	{ 
 		System.out.println("\njButton4_actionPerformed(ActionEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
  
 	private void jButton5_actionPerformed(ActionEvent e) 
 	{ 
 		System.out.println("\njButton5_actionPerformed(ActionEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
  
 	private void jButton6_actionPerformed(ActionEvent e) 
 	{ 
 		System.out.println("\njButton6_actionPerformed(ActionEvent e) called."); 
 		// TODO: Add any handling code here 
  
 	} 
 
         	private void jButton7_actionPerformed(ActionEvent e) 
 	{ 
 		 final boolean finished = false;
 		do  {            
            
                    displayScreen.setText("Would you like to start a new Towers of Hanoi game? [Y/N]");
            char yn = input.getText().charAt(0);          

            if (yn == 'Y'  || yn == 'y'){
                //new instance of the board every game
                board bd = new board();               
                displayScreen.setText("M)anual or A)uto mode?");
                char ma = input.getText().charAt(0);
                if(ma == 'm' || ma == 'M'){
                    int count = 0;
//                    String d = JOptionPane.showInputDialog("How many discs would you like to use?");
                    displayScreen.setText("How many discs would you like to use?");
                    // Parse input into integer
                    String d = input.getText();
                    int discNum = Integer.parseInt(d);
                    bd.board(discNum);
                    int optimum = (int)Math.pow(2,discNum)-1 ;
                    System.out.println("\n\n\n\n\n\nThe optimum number of moves to win in is "+optimum+"\n\n");
                    bd.pushPeg();
                    while(!bd.gameFINISH()){
                        //printing the current game state
                        bd.printBoard();                      

//                        System.out.println("So far you have made "+count+" moves.");
//                        System.out.println("Make your move!\nPlease choose peg to move from and then which peg to move to.");
//                        System.out.println("E.g 23 -- would move a disk from peg 2 to peg 3\n Your move.....\n\n");
                        String f = JOptionPane.showInputDialog("So far you have made "+count+" moves.\nPlease choose peg to move from and then which peg to move to.\nE.g 23 -- would move a disk from peg 2 to peg 3");
                        // Parse input into integer
                        int move = Integer.parseInt(f);
                        count++;                        
                        if (move==12){                                        
                            try{
                              bd.movePeg12();  
                            }catch (Exception ee){
                               displayScreen.setText("\n\n*** Bad Input, please try again! \n");                          
                            }                                                                               

                        } else if (move==13) {
                            try{
                              bd.movePeg13();  
                            }catch (Exception ee){
                               displayScreen.setText("\n\n*** Bad Input, please try again! \n"); 
                            }

                        }else if (move==21) {
                            try{
                              bd.movePeg21();  
                            }catch (Exception ee){
                               displayScreen.setText("\n\n*** Bad Input, please try again! \n"); 
                            }                                        
                        }else if (move==23) {
                            try{
                              bd.movePeg23();  
                            }catch (Exception ee){
                                displayScreen.setText("\n\n*** Bad Input, please try again! \n");
                            }                                        
                        }else if (move==31) {
                            try{
                              bd.movePeg31();  
                            }catch (Exception ee){
                                displayScreen.setText("\n\n*** Bad Input, please try again! \n");
                            }                                        
                        }else if (move==32) {
                            try{
                              bd.movePeg32();  
                            }catch (Exception ee){
                                displayScreen.setText("\n\n*** Bad Input, please try again! \n");
                            } 

                        } if (bd.gameFINISH()){
                            

                            

                            System.out.println("\n\n\n\n\n\n\n\n");
                            bd.printBoard();
                            System.out.println("Congratulations!!  You have completed the game!!\n\n");
                            System.out.println("The optimum number of moves was "+optimum); 
                            System.out.println("It took you "+count+" moves to finish.\n\n\n");

                        }

                    }
                } else if (ma == 'a' || ma == 'A') {
                    displayScreen.setText("How many discs would you like to use?");
                    // Parse input into integer
                    String q = input.getText();
                    int discNum = Integer.parseInt(q);                    
                    
                    bd.board(discNum);
                    bd.pushPeg();
                    try{

                    bd.initSolve(discNum);
                    
                    } catch (Exception ee){
                        displayScreen.setText("\n\n*** Bad Input, please try again! \n");
                        
                    }
                }              
             }
            else if (yn == 'n' || yn == 'N'){                      
                System.out.println("       Thankyou for Playing");
                System.out.println("^**____*.Have a Nice Day.*____**^");
                
            }                   
        } while (!finished);
 
  
 	} 
        	
        public static void main(String[] args){ new Main(); }   	 
 	
             }

        }
           
  } 
  
   
  
 

Heres the code im unsucessfully trying to put in there

Any help would be greatly appreciated

JAVA Code:
package assignment2good;
import boardage.*;
import EasyIn.*;
import javax.swing.JOptionPane;
import javax.swing.JDialog;

// Operators exceeded exception class
class Error extends Exception {
    public Error() {
        super("*******ERROR*******\n");
        }
}

class badInput extends Exception {
    public badInput() {
        super("Wrong Input type...  Please try again!\n");
        }
}

public class Main {
    
     /** Creates a new instance of Main */
    public Main() {
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       boolean finished = false;
//         String intString = JOptionPane.showInputDialog("Enter tower height: ");
//        // Convert string into integer
//        int discs = Integer.parseInt(intString);
       System.out.println("```````                                                   `.`    ``    ``                         ``");
            System.out.println("mmNMNmm-                                                 +Mdo    mN`  /Ms                        :N+");
            System.out.println("  :Ms   -oys/  o   oo   o -oys:  oo+y-:sys+      `+syo. /m  -    mN`  /Ms `+sys- .s/+ys-  .oys/` .s:");
            System.out.println("  :Ms  /My:/Nd sM  MM  Mo:My  M+ mm  -Md  s-    `mN  hM:-dM+-    mMmmmNMs :y  NN -Mm  NN /Mh  Nd`:Mo");
            System.out.println("  :Ms  hM.  yM-`NydhdhhN`sMdhhds mM   +dNMd/    :Ms  -My yM.     mN.``+Ms :hhyNM -Ms  mM hM.  yM::Mo");
            System.out.println("  :Ms  /Mh:+Nd  +MM  MM+ :Mh +h: mN  .i   Md    `mN  hN: yM.     NN`  /Ms mM :NM -Ms  mM /Mh  Nd`:Mo");
            System.out.println("  .o:   .oss/     + ` o`  -oys/  +o   -oss+`     `/ss+.  /o`     oo` `-s/`-sy+/o..o:  +o  .oss/  .o:");
            System.out.println("                                                 `           ``                                     ");
            System.out.println("                                   -y/          /y/         :yo                                     ");
            System.out.println("                                  /ydys.        /y/         /yo                                     ");
            System.out.println("                                 `ohdhh/`       /h+         /yo                                     ");
            System.out.println("                                 :yhdhyy.       /y+         /yo                                     ");
            System.out.println("                                `shdddhho       +y+         /yo                                     ");
            System.out.println("                                -yhdddhhy-      +h+         /yo                                     ");
            System.out.println("                               `+hhdddhhho.     /h+         /y+                                     ");
            System.out.println("                             .-/hhhdddhhhd+-....oho.........ohs......`                              ");
            System.out.println("                          `oyyyyyyyyyyyyyyyyyyyyyyysssssssssssssssssss+`                            ");            
            System.out.println("                      This game coded by Damion Mitchell and Phillip Trimmer"); 
       do  {
            
            
            char yn  = JOptionPane.showInputDialog("Would you like to start a new Towers of Hanoi game? [Y/N]").charAt(0); 
            if (yn == 'Y'  || yn == 'y'){
                //new instance of the board every game
                board bd = new board();               
                char ma  = JOptionPane.showInputDialog("M)anual or A)uto mode?").charAt(0);
                if(ma == 'm' || ma == 'M'){
                    int count = 0;
                    String d = JOptionPane.showInputDialog("How many discs would you like to use?");
                    // Parse input into integer
                    int discNum = Integer.parseInt(d);
                    bd.board(discNum);
                    int optimum = (int)Math.pow(2,discNum)-1 ;
                    System.out.println("\n\n\n\n\n\nThe optimum number of moves to win in is "+optimum+"\n\n");
                    bd.pushPeg();
                    while(!bd.gameFINISH()){
                        //printing the current game state
                        bd.printBoard();                      

//                        System.out.println("So far you have made "+count+" moves.");
//                        System.out.println("Make your move!\nPlease choose peg to move from and then which peg to move to.");
//                        System.out.println("E.g 23 -- would move a disk from peg 2 to peg 3\n Your move.....\n\n");
                        String f = JOptionPane.showInputDialog("So far you have made "+count+" moves.\nPlease choose peg to move from and then which peg to move to.\nE.g 23 -- would move a disk from peg 2 to peg 3");
                        // Parse input into integer
                        int move = Integer.parseInt(f);
                        count++;                        
                        if (move==12){                                        
                            try{
                              bd.movePeg12();  
                            }catch (Exception e){
                               System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());                          
                            }                                                                               

                        } else if (move==13) {
                            try{
                              bd.movePeg13();  
                            }catch (Exception e){
                               System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage()); 
                            }

                        }else if (move==21) {
                            try{
                              bd.movePeg21();  
                            }catch (Exception e){
                               System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage()); 
                            }                                        
                        }else if (move==23) {
                            try{
                              bd.movePeg23();  
                            }catch (Exception e){
                                System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());
                            }                                        
                        }else if (move==31) {
                            try{
                              bd.movePeg31();  
                            }catch (Exception e){
                                System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());
                            }                                        
                        }else if (move==32) {
                            try{
                              bd.movePeg32();  
                            }catch (Exception e){
                                System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());
                            } 

                        } if (bd.gameFINISH()){
                            

                            

                            System.out.println("\n\n\n\n\n\n\n\n");
                            bd.printBoard();
                            System.out.println("Congratulations!!  You have completed the game!!\n\n");
                            System.out.println("The optimum number of moves was "+optimum); 
                            System.out.println("It took you "+count+" moves to finish.\n\n\n");

                        }

                    }
                } else if (ma == 'a' || ma == 'A') {
                    String q = JOptionPane.showInputDialog("How many discs would you like to use?");
                    // Parse input into integer
                    int discNum = Integer.parseInt(q);
                    bd.board(discNum);
                    bd.pushPeg();
                    try{

                    bd.initSolve(discNum);
                    
                    } catch (Exception e){
                        System.out.println(e.getMessage());
                        
                    }
                }              
             }
            else if (yn == 'n' || yn == 'N'){                      
                System.out.println("       Thankyou for Playing");
                System.out.println("^**____*.Have a Nice Day.*____**^");
                finished = true;
            }                   
        } while (!finished);
    }
}
    
  #2  
Old 13-May-2008, 12:32
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,233
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Trouble integrating console code into GUI


Pause and wait,for input? Unless I'm missing something, isn't that ultimately what the buttons will do? [well, the GUI 'waits', so to speak, until events are 'fired' is what I mean]

Anyway, what is the nature of these? (as they're not included in the post)
JAVA Code:
 import boardage.*;
 import EasyIn.*;  
I have some other suggestions too (possibly improve JButton handling with ONE actionPerformed handler, for example), but it's hard to help out as no one can compile using this code alone, not even the non-GUI example.

EDIT:
I was able to get the GUI to appear, and can see the button's action messages, but all the board and 'bd' related statements had to be commented-out.

Moving to a GUI, there is really no need for the input of 21, 23, etc. -- because the buttons that you have created will/can now perform those actions (or movements), without the textbox -- unless the textbox is just for dual feature (input and/or button clicks), or some other need??
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #3  
Old 13-May-2008, 16:51
Barman007 Barman007 is offline
New Member
 
Join Date: May 2008
Posts: 10
Barman007 is on a distinguished road

Re: Trouble integrating console code into GUI


Ok cool, i'll post the whole code to the non GUI example at the end of this post. Yes thats my problem im very new to using GUI's and im not too sure how to let the GUI run my code im to use to linear style coding. I have an idea, but minimum experience. Like I know everything runs off click or input events, but I just can't remember how to get it working how I want. And yes your right I dont need input for 12, 32 etc, the buttons handle that, but I wasnt upto that stage so I was still fumbling around trying to get anything to work at all.

Oh and ive taken out the EasyIn packagae now too, I realised I didnt need it anymore, it just helped with Input and output but I changed my code to using JOptionPane.

Heres my working non GUI example, I hope this helps, sorry for my previous lack of information..

MAIN CLASS
JAVA Code:
package assignment2good;
import boardage.*;
import javax.swing.JOptionPane;
import javax.swing.JDialog;

// Operators exceeded exception class
class Error extends Exception {
    public Error() {
        super("*******ERROR*******\n");
        }
}

class badInput extends Exception {
    public badInput() {
        super("Wrong Input type...  Please try again!\n");
        }
}

public class Main {
    
     /** Creates a new instance of Main */
    public Main() {
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       boolean finished = false;

       do  {
            
            
            char yn  = JOptionPane.showInputDialog("Would you like to start a new Towers of Hanoi game? [Y/N]").charAt(0); 
            if (yn == 'Y'  || yn == 'y'){
                //new instance of the board every game
                board bd = new board();               
                char ma  = JOptionPane.showInputDialog("M)anual or A)uto mode?").charAt(0);
                if(ma == 'm' || ma == 'M'){
                    int count = 0;
                    String d = JOptionPane.showInputDialog("How many discs would you like to use?");
                    // Parse input into integer
                    int discNum = Integer.parseInt(d);
                    bd.board(discNum);
                    int optimum = (int)Math.pow(2,discNum)-1 ;
                    System.out.println("\n\n\n\n\n\nThe optimum number of moves to win in is "+optimum+"\n\n");
                    bd.pushPeg();
                    while(!bd.gameFINISH()){
                        //printing the current game state
                        bd.printBoard();                      

//                        System.out.println("So far you have made "+count+" moves.");
//                        System.out.println("Make your move!\nPlease choose peg to move from and then which peg to move to.");
//                        System.out.println("E.g 23 -- would move a disk from peg 2 to peg 3\n Your move.....\n\n");
                        
                        String f = JOptionPane.showInputDialog("So far you have made "+count+" moves.\nPlease choose peg to move from and then which peg to move to.\nE.g 23 -- would move a disk from peg 2 to peg 3");
                        // Parse input into integer
                        int move = Integer.parseInt(f);
                        count++;                        
                        if (move==12){                                        
                            try{
                              bd.movePeg12();  
                            }catch (Exception e){
                               System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());                          
                            }                                                                               

                        } else if (move==13) {
                            try{
                              bd.movePeg13();  
                            }catch (Exception e){
                               System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage()); 
                            }

                        }else if (move==21) {
                            try{
                              bd.movePeg21();  
                            }catch (Exception e){
                               System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage()); 
                            }                                        
                        }else if (move==23) {
                            try{
                              bd.movePeg23();  
                            }catch (Exception e){
                                System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());
                            }                                        
                        }else if (move==31) {
                            try{
                              bd.movePeg31();  
                            }catch (Exception e){
                                System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());
                            }                                        
                        }else if (move==32) {
                            try{
                              bd.movePeg32();  
                            }catch (Exception e){
                                System.out.println("\n\n*** Bad Input, please try again! \n" + e.getMessage());
                            } 

                        } if (bd.gameFINISH()){
                            

                            

                            System.out.println("\n\n\n\n\n\n\n\n");
                            bd.printBoard();
                            System.out.println("Congratulations!!  You have completed the game!!\n\n");
                            System.out.println("The optimum number of moves was "+optimum); 
                            System.out.println("It took you "+count+" moves to finish.\n\n\n");

                        }

                    }
                } else if (ma == 'a' || ma == 'A') {
                    String q = JOptionPane.showInputDialog("How many discs would you like to use?");
                    // Parse input into integer
                    int discNum = Integer.parseInt(q);
                    bd.board(discNum);
                    bd.pushPeg();
                    try{

                    bd.initSolve(discNum);
                    
                    } catch (Exception e){
                        System.out.println(e.getMessage());
                        
                    }
                }              
             }
            else if (yn == 'n' || yn == 'N'){                      
                System.out.println("       Thankyou for Playing");
                System.out.println("^**____*.Have a Nice Day.*____**^");
                finished = true;
            }                   
        } while (!finished);
    }
}
    

BOARD CLASS
JAVA Code:
public class board{
    
    /** Creates a new instance of board */
    public board() {
        super();        
    } 
    peg peg1 = new peg();    
    peg peg2 = new peg();
    peg peg3 = new peg();
    public static int discNUM = 0;
    public static boolean gameFinish = false;
    
    public void board(int discNum){ 
        discNUM = discNum; 
    } 

    
    
    public void pushPeg(){        
        for(int i = discNUM; i > 0; i--) {
            peg1.push(i);
            
            
        }
    }    
    
    
    public void printBoard(){
       
        System.out.print("\n\n\n\n\n\n\n\n|");
        peg1.print();        
        System.out.print("|");
        peg2.print();
        System.out.print("|");
        peg3.print();
        System.out.print("\n\n\n\n\n\n\n");
        if(peg3.topNum() == 1 && peg2.topNum() == peg1.topNum()){ 
            gameFinish = true; 
        } 
        //do some debugging 
        System.out.println(peg1.topNum() + "" + peg2.topNum() + "" + peg3.topNum());            
    }
    
    public void movePeg12() throws Exception {
        int a =0;
        a = peg2.topNum();
        int b = peg1.pop();
        if (b >a){
            peg1.push(b);
            System.out.print("**12Illegal Move**\nCannot stack a larger number onto a smaller one!");
            throw new Exception ("**!12Illegal Move**\nCannot stack a larger number onto a smaller one!");
            
            }else{
                peg2.push(b);
                }        
    }
    public void movePeg13() throws Exception{
        int a =0;
        a = peg3.topNum();
        int b = peg1.pop();
        if (b >a){
            peg1.push(b);
            System.out.print("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            throw new Exception ("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            
            }else{
                peg3.push(b);
                }        
    }        

    public void movePeg21() throws Exception{
        int a =0;
        a = peg1.topNum();
        int b = peg2.pop();
        if (b >a){
            peg2.push(b);
            System.out.print("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            throw new Exception ("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            
            }else{
                peg1.push(b);
                }              
    }
    public void movePeg23() throws Exception{
        int a =0;
        a = peg3.topNum();
        int b = peg2.pop();
        if (b > a){
            peg2.push(b);
            System.out.print("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            throw new Exception ("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            
            }else{
                peg3.push(b);
                }              
    }
    public void movePeg31() throws Exception{
        int a =0;
        a = peg1.topNum();
        int b = peg3.pop();
        if (b > a){
            peg3.push(b);
            System.out.print("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            throw new Exception ("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            
            }else{
                peg1.push(b);
                }              
    }
    public void movePeg32() throws Exception{
        int a =0;
        a = peg2.topNum();
        int b = peg3.pop();
        if (b > a ){
            peg3.push(b);
            System.out.print("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            throw new Exception ("**Illegal Move**\nCannot stack a larger number onto a smaller one!");
            
            }else{
                peg2.push(b);
                }              
    }
    
//   
    
    public boolean gameFINISH(){
        int a = peg1.topNum();
        int b = peg2.topNum();
        int c = peg3.topNum();
        if (a==b && c == 1){
            
            return true;
        } 
           return false; 
    }      
    
    public void initSolve(int discNo){
        solve(discNo, peg1, peg3, peg2);
    }
    private void solve(int pegHeight, boardage.peg peg1, boardage.peg peg2, boardage.peg peg3) {
        try{
             int count = 0;
        
                if(pegHeight == 1) {
                    // Push off one onto another
                    peg2.push(peg1.pop());  printBoard();count++;
                    // we're done at this point 
                }else {
                    // Move discs
                    solve(pegHeight -1, peg1, peg3, peg2);
                    peg2.push(peg1.pop()); printBoard();
                    solve(pegHeight -1, peg3, peg2, peg1);
            }
        }catch (Exception e) {
              System.out.println(e + "*** Error!! ");
        }
    }
}


PEG CLASS
JAVA Code:
package boardage;
import linkage.*;

// Operators exceeded exception class
class UnderflowException extends Exception {
    public UnderflowException() {
        super("*******ERROR*******\n       Excessive operators\n....Please Try Aagain....");
        }
}

public class peg extends llist{
    private int top;
    
    public peg() {
        super();
        top = 0;
        
    }
    public int countPeg = 0;

    public int topNum(){
        return getTopInt();
    }
    
    public boolean pegEmpty(){
        return empty();
    } 
    public void push(int n) {
        addItem(n);
        countPeg++;
        top = n;
    }
    
    public int pop() throws Exception {
        try {
            countPeg--;
            return removeItem();
        }
        catch (EmptyListException e) {
            countPeg++;
            throw new UnderflowException();
        }
    }
    
    public void print() {
        printList();
    }   

    public int countPeg(){ 
        return countPeg; 
    }  
        
}


UNDERFLOW EXCEPTION CLASS
JAVA Code:
package boardage;

/**
 *
 * @author itmpm
 */
public class UnderflowException extends Exception {

    public UnderflowException() {
        super("Stack underflow");
    }
}

LLIST CLASS
JAVA Code:
package linkage;

/**
 *
 * @author dammit11
 */
public class llist {
  protected llnode head; // the first item in the list


      public llist() { 
        head=null;
      }



    public void addItem(int newVal) {
       llnode newNode= new llnode(newVal,head);
       head = newNode;
    }

    public boolean empty() {
        return head == null;
    }
    
    public int removeItem() throws EmptyListException {
        if (empty())
            throw new EmptyListException();
        else {
            int returnVal = head.dataVal();
            head = head.nextNode();
            return returnVal;
        }   
    }
//    public void printList() {
//        if (head==null)
//          System.out.print("");
//        else {
//          llnode runner=head;
//
//          while (runner!=null) {
//              
//            System.out.print(runner.dataVal() + " ");
//            
//            runner=runner.nextNode();
//          }
//        }
//        System.out.println();
//    }
    public void printList() { 
    printNode(head); 
    System.out.println(); 
} 

public void printNode(llnode node) { 
  if (node != null) { 
    printNode(node.nextNode()); 
    System.out.print(node.dataVal() + " "); 
  } 
}
public int getTopInt(){ 
        if(head == null){ 
            return (boardage.board.discNUM + 1); 
        }else{ 
            return head.dataVal(); 
        } 
    }
    public static String backwards(llnode head) {
        if (head == null)
            return null;
        if (head.next == null)            
            return Integer.toString(head.data);
        else
            return backwards(head.next) + "" + Integer.toString(head.data);
    }    
        
}


LLNODE CLASS
JAVA Code:
package linkage;


public class llnode {
    public int data;
    public llnode next;
    public llnode() {
        next=null;
    }
    public llnode(int val, llnode oldHead) {
        data=val;
        next=oldHead;
    }
    public int dataVal() {
        return data;
    }
    public llnode nextNode() {
        return next;
    }    
}


EMPTYLIST EXCEPTION CLASS
JAVA Code:
package linkage;

/**
 *
 * @author itmpm
 */
public class EmptyListException extends Exception {

    public EmptyListException() {
        super("List is empty");
    }
}

  #4  
Old 13-May-2008, 17:22
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,233
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Trouble integrating console code into GUI


Two UnderflowException classes?

Do you still want to work from the direction started in the first post, as the starting point?
(the one with the 'visualassignment2' package)

EDIT:
Oh, and is there a restriction, with the assignment, that the Java API's Stack, and LinkedList classes could not be used? No big deal, just curious; otherwise it'll have to be what's already done.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #5  
Old 13-May-2008, 17:33
Barman007 Barman007 is offline
New Member
 
Join Date: May 2008
Posts: 10
Barman007 is on a distinguished road

Re: Trouble integrating console code into GUI


Umm yep, one underflow exception is for my board package and the empty list exception is for in my linkage package. Sorry im still a bit new fi there is a better way to do that.

Well the only reason I added a start button in there was because I couldnt think of how to get my game code working on the gui. So im just into getting it running any way I can. It would be cool if the thing just started with a welcome message on the texarea screen asking if theyd like a new game [Y/N] like in my non gui version. But I just didnt know how to do it. The GUI turned out to be a bigger monster for me than I first expeced. I thought I could do it no worries, but it owned me lol.

And nope no restriction on assignment. I just coded those classes myself from examples my lecturer gave us. He said I was supposed to try using circular linked lists in my board class for full marks, but ive got no idea what he means there. Im one of the very few in the class who actually managed to get linked lists working in my peg class, most of the class is just using stacks and pop and push.
  #6  
Old 13-May-2008, 20:44
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,233
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Trouble integrating console code into GUI


This is still incomplete, but thought I'd pass along what is done so far. Compile and run it, but note that there may be issues, but some output shows in the console window, not the GUI window, just yet.
JAVA Code:
package visualassignment2;


 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import boardage.*;
 import java.io.*;

  class Error extends Exception {
    public Error() {
        super("*******ERROR*******\n");
        }
}

class badInput extends Exception {
    public badInput() {
        super("Wrong Input type...  Please try again!\n");
        }
}

 public class Main extends JFrame implements ActionListener
 {
     // Declared variables
     private static final String[] titles = { "Peg 1 to 2",
		 									  "Peg 1 to 3",
		 									  "Peg 2 to 1",
		 									  "Peg 2 to 3",
		 									  "Peg 3 to 1",
		 									  "Peg 3 to 2",
		 									  "START GAME" };

     private JLabel jLabel1;
     private JLabel jLabel3;
     private JTextField input;
     private JTextArea displayScreen;
     private JScrollPane jScrollPane1;
     private JProgressBar jProgressBar1;
     private JButton[] gameButtons = new JButton[7];
     private JPanel  contentPane;
        private board   bd;
	 int count = 0;
	 int discNum = 0;
	 int optimum = 0;
     // End of variables declaration

        //Constructor
     public Main()
     {
          super();
          initializeComponent();
          this.setVisible(true);
                bd = new board();
                getDiscCount();
                getMode();

     }

	private void getMode()
	{
		Object[] choices= {"Manual", "Auto"};
		Object o = JOptionPane.showInputDialog(null, "Manual or Auto mode?",
												null, JOptionPane.QUESTION_MESSAGE,
												null, choices, choices[0]);
		if (o.toString().equals(choices[0]))
		{
			bd.pushPeg();
			System.out.println("Manual selected");
		}
		else if (o.toString().equals(choices[1]))
		{
			System.out.println("Auto selected");
			processAutomatic();
		}
	}

	private void getDiscCount()
	{
		String d = JOptionPane.showInputDialog("How many discs would you like to use?");
		discNum = Integer.parseInt(d);
		bd.board(discNum);
	 	optimum = (int)Math.pow(2,discNum)-1 ;
		String winMoves = "The optimum number of moves to win in is " + optimum;
		JOptionPane.showMessageDialog(null, winMoves );
	}

        //This method is called from within the constructor to initialize the form.
     private void initializeComponent()
     {
          jLabel1 = new JLabel();
          jLabel3 = new JLabel();
          input = new JTextField();
          displayScreen = new JTextArea();
          jScrollPane1 = new JScrollPane();
          jProgressBar1 = new JProgressBar();

          contentPane = (JPanel)this.getContentPane();

          //
          // jLabel1
          // setting image location
          jLabel1.setIcon(new ImageIcon("K:\\Portable Start Menu\\Documents\\BInfoTech\\2nd Year\\Java\\visualassignment2\\build\\hanoititle.jpg"));
          //
                // jLabel3
          // Labels the input on the display
          jLabel3.setText("Input");
                //
          // jTextField1
          // This is where the user input goes
                input.setText("Type here");
          input.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e)
               {
                    jTextField1_actionPerformed(e);
               }

          });

          input.addKeyListener(new KeyAdapter() {
               public void keyPressed(KeyEvent e)
               {
                    jTextField1_keyPressed(e);
               }

          });
          //
          // jTextArea1
          //sets wether the main display for instructions and current gamestate is editable or not
          displayScreen.setEditable(false);
                // Add display area with scroll bars
          //
          // jScrollPane1
          // scrolls textarea1 when needed
          jScrollPane1.setViewportView(displayScreen);
          // jProgressBar1
          // sets the color of the progress bar
          jProgressBar1.setForeground(new Color(246, 5, 21));
          //

          for ( int i = 0; i < gameButtons.length; ++i )
          {
			  gameButtons[i] = new JButton();

			  if ( i < gameButtons.length - 1 )
			  {
			  	gameButtons[i].setBackground(new Color(255, 255, 255));
			  	gameButtons[i].setForeground(new Color(0, 0, 0));
			  }

			  gameButtons[i].addActionListener(this);
			  gameButtons[i].setText(titles[i]);
		  }

          //
          // contentPane
          //
          contentPane.setLayout(null);
          contentPane.setBackground(new Color(155, 155, 209));
          addComponent(contentPane, jLabel1, -1,0,526,282);
          addComponent(contentPane, jLabel3, 11,475,65,18);
          addComponent(contentPane, input, 9,452,228,22);
          addComponent(contentPane, jScrollPane1, 9,289,505,155);
          addComponent(contentPane, jProgressBar1, 11,280,503,9);
          addComponent(contentPane, gameButtons[0], 247,450,83,28);
          addComponent(contentPane, gameButtons[1], 246,485,83,28);
          addComponent(contentPane, gameButtons[2], 338,450,83,28);
          addComponent(contentPane, gameButtons[3], 338,485,83,28);
          addComponent(contentPane, gameButtons[4], 430,450,83,28);
          addComponent(contentPane, gameButtons[5], 430,485,83,28);
          addComponent(contentPane, gameButtons[6], 66,486,132,25);
          //
          // Main
          //
          this.setTitle("The Towers of Hanoi");
          this.setLocation(new Point(112, 32));
          this.setSize(new Dimension(538, 555));
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          this.setResizable(false);
          input.setEnabled(false);
          gameButtons[6].setEnabled(false);
     }




     /** Add Component Without a Layout Manager (Absolute Positioning) */
     private void addComponent(Container container,Component c,int x,int y,int width,int height)
     {
          c.setBounds(x,y,width,height);
          container.add(c);
     }

     //
     // TODO: Add any appropriate code in the following Event Handling Methods
     //
     private void jTextField1_actionPerformed(ActionEvent e)
     {
          System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
          // TODO: Add any handling code here

     }

          private void jTextField1_keyPressed(KeyEvent e)
     {
          System.out.println("\njTextField1_keyPressed(KeyEvent e) called.");
          // TODO: Add any handling code here

     }

     public void actionPerformed(ActionEvent e)
     {
		String command = e.getActionCommand();
		boolean validMove = true; // initially, assume all good moves.

		if ( command.equals( titles[0] ) )
		{
			try{
			  bd.movePeg12();
			}catch (Exception ee){
			   validMove = false;
			   displayScreen.setText("\n\n*** Bad Input, please try again! \n");
			}
           System.out.println("\nButton1 clicked!.");
		}
		else if ( command.equals( titles[1] ) )
		{
			try{
			  bd.movePeg13();
			}catch (Exception ee){
			   validMove = false;
			   displayScreen.setText("\n\n*** Bad Input, please try again! \n");
			}
           System.out.println("\nButton2 clicked!.");
		}
		else if ( command.equals( titles[2] ) )
		{
			try{
			  bd.movePeg21();
			}catch (Exception ee){
			   validMove = false;
			   displayScreen.setText("\n\n*** Bad Input, please try again! \n");
			}
           System.out.println("\nButton3 clicked!.");
		}
		else if ( command.equals( titles[3] ) )
		{
			try{
			  bd.movePeg23();
			}catch (Exception ee){
			   validMove = false;
			   displayScreen.setText("\n\n*** Bad Input, please try again! \n");
			}
           System.out.println("\nButton4 clicked!.");
		}
		else if ( command.equals( titles[4] ) )
		{
			try{
			  bd.movePeg31();
			}catch (Exception ee){
			   validMove = false;
			   displayScreen.setText("\n\n*** Bad Input, please try again! \n");
			}
           System.out.println("\nButton5 clicked!.");
		}
		else if ( command.equals( titles[5] ) )
		{
			try{
			  bd.movePeg32();
			}catch (Exception ee){
			   validMove = false;
			   displayScreen.setText("\n\n*** Bad Input, please try again! \n");
			}
           System.out.println("\nButton6 clicked!.");
		}
		else if ( command.equals( titles[6] ) )
		{
           System.out.println("\nButton7 clicked!.");
		}

		if ( validMove )
		{
			processManual();
		}
     }
/*
     private void oldCodeStuff()
     {
           final boolean finished = false;
          do  {

           displayScreen.setText("Would you like to start a new Towers of Hanoi game? [Y/N]");
            char yn = input.getText().charAt(0);

            if (yn == 'Y'  || yn == 'y'){
                //new instance of the board every game
                board bd = new board();
                displayScreen.setText("M)anual or A)uto mode?");
                char ma = input.getText().charAt(0);
                if(ma == 'm' || ma == 'M'){
                    int count = 0;
//                    String d = JOptionPane.showInputDialog("How many discs would you like to use?");
                    displayScreen.setText("How many discs would you like to use?");
                    // Parse input into integer
                    String d = input.getText();
                    int discNum = Integer.parseInt(d);
                    bd.board(discNum);
                    int optimum = (int)Math.pow(2,discNum)-1 ;
                    System.out.println("\n\n\n\n\n\nThe optimum number of moves to win in is "+optimum+"\n\n");
                    bd.pushPeg();
                    while(!bd.gameFINISH()){
                        //printing the current game state
                        bd.printBoard();

//                        System.out.println("So far you have made "+count+" moves.");
//                        System.out.println("Make your move!\nPlease choose peg to move from and then which peg to move to.");
//                        System.out.println("E.g 23 -- would move a disk from peg 2 to peg 3\n Your move.....\n\n");
                        String f = JOptionPane.showInputDialog("So far you have made "+count+" moves.\nPlease choose peg to move from and then which peg to move to.\nE.g 23 -- would move a disk from peg 2 to peg 3");
                        // Parse input into integer
                        int move = Integer.parseInt(f);
                        count++;

                        if (bd.gameFINISH()){




                            System.out.println("\n\n\n\n\n\n\n\n");
                            bd.printBoard();
                            System.out.println("Congratulations!!  You have completed the game!!\n\n");
                            System.out.println("The optimum number of moves was "+optimum);
                            System.out.println("It took you "+count+" moves to finish.\n\n\n");

                        }

                    }
                } else if (ma == 'a' || ma == 'A') {
                    displayScreen.setText("How many discs would you like to use?");
                    // Parse input into integer
                    String q = input.getText();
                    int discNum = Integer.parseInt(q);

                    bd.board(discNum);
                    bd.pushPeg();
                    try{

                    bd.initSolve(discNum);

                    } catch (Exception ee){
                        displayScreen.setText("\n\n*** Bad Input, please try again! \n");

                    }
                }
             }
            else if (yn == 'n' || yn == 'N'){
                System.out.println("       Thankyou for Playing");
                System.out.println("^**____*.Have a Nice Day.*____**^");

            }
        } while (!finished);
     }
*/
	private void notifyWin()
	{
		String conGratMessage = "Congratulations!!  You have completed the game!!\n\n" +
								"The optimum number of moves was: " + optimum +
								"It took you " + count + " moves to finish.";

		JOptionPane.showMessageDialog(null, conGratMessage );
	}

	private void processManual()
	{
		count++;

		bd.printBoard();

		if (bd.gameFINISH())
		{
			notifyWin();
		}
		else
		{
			String statusMessage = "So far you have made " + count +
								   " moves.\nPlease choose another peg move";

			JOptionPane.showMessageDialog( null, statusMessage );
		}
	}

	private void processAutomatic()
	{
		bd.pushPeg();

		try
		{
			bd.initSolve(discNum);
		}
		catch (Exception ee)
		{
			displayScreen.setText("\n\n*** Bad Input, please try again! \n");
		}
	}

	public static void main(String[] args)
	{
		new Main();
	}
}
I can't explain it all at the immediate moment (have run out of time for the night), but feel free to ask questions, and I'll respond in another post either tomorrow afternoon or evening.

Oh, I did disable the 'start game' button and the input textbox in the GUI, but all the Peg buttons are there -- but a small task for you, those need widening to show all the text (or reduce the text already there) to fit.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #7  
Old 13-May-2008, 21:55
Barman007 Barman007 is offline
New Member
 
Join Date: May 2008
Posts: 10
Barman007 is on a distinguished road

Re: Trouble integrating console code into GUI


Wow youve done such a great job!! Thankyou so much. You've really pointed me in the right direction. I can see exactly what you've done and im going to spend the rest of the day(and night) working on the improvments you have made so hopefully by the time you come back to look at this tommorow i'll have a completed GUI working.

Im pretty much complete now and it would have taken me another three days to finish coding it by trial and error. Thankyou so much!! I'll post my finished code here maybe tomorrow so you can see how I put your handy work to use
  #8  
Old 14-May-2008, 06:05
Barman007 Barman007 is offline
New Member
 
Join Date: May 2008
Posts: 10
Barman007 is on a distinguished road

Re: Trouble integrating console code into GUI


Thanks once again. Ive pretty much been able to complete the whole GUI thanks to your helping hand. I was just wondering if you were able to help me out with a couple of last problems im having.

Firstly im having trouble printing out my board in the JTextPane, but even after I get the board printing out in there I want the board to print vertically not horizontally. Even if you knew how to just do that on the console would be a huge help.
Im also having problems implementing my progress bar to work in auto mode if you know anything about those. Ive played around with it but just cant get it going. It looks like its initialised, but I just cant get it to increment. I was trying to make it go from 0 to optimum by getting the optimum number and increment the bar every move based on how far its got to go.
Lastly im having trouble with the reset button to play another game, ive made up a method called withdraw() on my main class and it basically is just popping numbers out of the linked list to clear the board but its not quite working properly. I'll print my main i've been working on all day and the function I wrote in the board class.

package visualassignment2;
JAVA Code:
  import java.awt.*; 
 import java.awt.event.*;
 import javax.swing.text.*;
 import javax.swing.*;
 import boardage.*;   
 import java.io.*;
 import java.lang.Object.*;
 import java.util.StringTokenizer;


  class Error extends Exception {
    public Error() {
        super("*******ERROR*******\n");
        }
}
// Non operator exception class
class nonOperator extends Exception {
    public nonOperator(String x) {
        super("*******ERROR*******\n       " + x + " is not an operator\n....Please Try Aagain....");
        }
}

class badInput extends Exception {
    public badInput() {
        super("Wrong Input type...  Please try again!\n");
        }
}
 
 public class Main extends JFrame implements ActionListener
 { 
 	// Declared variables
        private static final String[] titles = { "Peg 1 to 2",
		 									  "Peg 1 to 3",
		 									  "Peg 2 to 1",
		 									  "Peg 2 to 3",
		 									  "Peg 3 to 1",
		 									  "Peg 3 to 2"};
 	private JLabel jLabel1; 
        private JLabel jLabel3;
        private JLabel jLabel4; 	 
 	private JTextPane display; 
 	private JScrollPane jScrollPane3;
        private JProgressBar progressBar;  	 
 	private JButton[] gameButtons = new JButton[6];
        private JButton b7;
        private JButton b8;
 	private JPanel  contentPane;
        private board   bd;
        boolean useManual = true;
        int count = 0;
	int discNum = 0;
	int optimum = 0;
        // End of variables declaration 
  
        //Constructor
 	public Main() 
 	{ 
 		super(); 
 		initializeComponent();  
 		this.setVisible(true);
                bd = new board();
                getDiscCount();
                getMode();
                
 	}
        private void getMode()
	{
		Object[] choices= {"Manual", "Auto"};
		Object o = JOptionPane.showInputDialog(null, "Manual or Auto mode?",
												null, JOptionPane.QUESTION_MESSAGE,
												null, choices, choices[0]);
		if (o.toString().equals(choices[0]))
		{			
                    
                        bd.pushPeg();
                    
			display.setText("\nManual mode selected\n\nPlease enter your move\n\n\n");                     
                        bd.printBoard();
                       
                                               
                                
                        
		}
		else if (o.toString().equals(choices[1]))
		{
			display.setText("Auto mode selected");
                        
		        processAutomatic();
		}
	}
        private void getDiscCount()
	{
            
                
            
		String d = JOptionPane.showInputDialog("How many discs would you like to use?");
		discNum = Integer.parseInt(d);
                
                    bd.board(discNum);
	 	optimum = (int)Math.pow(2,discNum)-1 ;
		String winMoves = "The optimum number of moves to win in is " + optimum;
		JOptionPane.showMessageDialog(null, winMoves );
                    
                
                
           
		
	}
  
 	
        //This method is called from within the constructor to initialize the form.
 	private void initializeComponent() 
 	{ 
 		jLabel1 = new JLabel(); 
                jLabel3 = new JLabel();
                jLabel4 = new JLabel(); 		 
 		display = new JTextPane(); 
 		jScrollPane3 = new JScrollPane();
                progressBar = new JProgressBar();
                b7 = new JButton();
                b8 = new JButton();
 		contentPane = (JPanel)this.getContentPane();          
                progressBar = new JProgressBar(0, optimum = (int)Math.pow(2,discNum)-1);
                progressBar.setValue(0);
                progressBar.setStringPainted(true);

  
 		// 
 		// jLabel1 
 		// setting image location
 		jLabel1.setIcon(new ImageIcon("K:\\Portable Start Menu\\Documents\\BInfoTech\\2nd Year\\Java\\visualassignment2\\build\\hanoititle.jpg")); 
 		//
                
                // jLabel4 
 		// 
 		jLabel4.setText("PROGRESS"); 
 		// 
 		 
 		//
                display.setBackground(new Color(255, 255, 255)); 
 		display.setForeground(new Color(0, 0, 0)); 
 		display.setEditable(false);
 		StyledDocument doc = display.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
		StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);                
		doc.setParagraphAttributes(0, 0, standard, true);
                
                display.setText("INSTRUCTIONS\n\nThe object is to move all the disks from the left to the right pole.\nYou can only move one disk at a time and you must follow size order\n(a bigger disk can't go on a smaller disk).\nIf using manual mode please use the 'P' buttons to make your moves.\n\n\n");
                
 		// 
 		// jScrollPane3 
 		// 
 		jScrollPane3.setViewportView(display); 
 		// 
 		// jProgressBar1 
 		// sets the color of the progress bar
 		progressBar.setForeground(new Color(246, 5, 21)); 
 		// 
 		
                for ( int i = 0; i < gameButtons.length; ++i )
          {
			  gameButtons[i] = new JButton();

			  if ( i < gameButtons.length - 1 )
			  {
			  	gameButtons[i].setBackground(new Color(255, 255, 255));
			  	gameButtons[i].setForeground(new Color(0, 0, 0));
			  }

			  gameButtons[i].addActionListener(this);
			  gameButtons[i].setText(titles[i]);
		  }
                b7.setText("RESET"); 
 		b7.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton7_actionPerformed(e); 
 			} 
  
 		}); 
                
                b8.setText("Instructions"); 
 		b8.addActionListener(new ActionListener() { 
 			public void actionPerformed(ActionEvent e) 
 			{ 
 				jButton8_actionPerformed(e); 
 			} 
  
 		}); 
 		// 
 		// contentPane 
 		// 
 		contentPane.setLayout(null); 
 		contentPane.setBackground(new Color(155, 155, 209)); 
 		addComponent(contentPane, jLabel1, -1,0,526,282);
                addComponent(contentPane, jLabel3, 11,475,65,18);
                addComponent(contentPane, jLabel4, 4,280,98,18); 		 
 		addComponent(contentPane, display, 1,299,523,145);
                addComponent(contentPane, jScrollPane3, 1,299,523,145);
                addComponent(contentPane, progressBar, 83,282,443,13);  		
 		addComponent(contentPane, gameButtons[0], 247,450,83,28); 
 		addComponent(contentPane, gameButtons[1], 246,485,83,28); 
 		addComponent(contentPane, gameButtons[2], 338,450,83,28); 
 		addComponent(contentPane, gameButtons[3], 338,485,83,28); 
 		addComponent(contentPane, gameButtons[4], 430,450,83,28); 
 		addComponent(contentPane, gameButtons[5], 430,485,83,28);
                addComponent(contentPane, b7, 20,472,90,28);
                addComponent(contentPane, b8, 133,472,90,28);
 		// 
 		// Main 
 		// 
 			this.setTitle("The Towers of Hanoi"); 
 		this.setLocation(new Point(112, 32)); 
 		this.setSize(new Dimension(538, 555)); 
 		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
 		this.setResizable(false);
                gameButtons[5].setEnabled(false);
 	} 
    
 	 
           
            
 	/** Add Component Without a Layout Manager (Absolute Positioning) */ 
 	private void addComponent(Container container,Component c,int x,int y,int width,int height) 
 	{ 
 		c.setBounds(x,y,width,height); 
 		container.add(c); 
 	}  	        
        	
                
 	public void actionPerformed(ActionEvent e)
     {
		String command = e.getActionCommand();
		boolean validMove = true; // initially, assume all good moves.

		if ( command.equals( titles[0] ) )
		{
			try{
			  bd.movePeg12();
			}catch (Exception ee){
			   validMove = false;
			   display.setText("\n\n*** Bad Input, please try again! \n");
			}
           
		}
		else if ( command.equals( titles[1] ) )
		{
			try{
			  bd.movePeg13();
			}catch (Exception ee){
			   validMove = false;
			   display.setText("\n\n*** Bad Input, please try again! \n");
			}
           
		}
		else if ( command.equals( titles[2] ) )
		{
			try{
			  bd.movePeg21();
			}catch (Exception ee){
			   validMove = false;
			   display.setText("\n\n*** Bad Input, please try again! \n");
			}
           
		}
		else if ( command.equals( titles[3] ) )
		{
			try{
			  bd.movePeg23();
			}catch (Exception ee){
			   validMove = false;
			   display.setText("\n\n*** Bad Input, please try again! \n");
			}
           
		}
		else if ( command.equals( titles[4] ) )
		{
			try{
			  bd.movePeg31();
			}catch (Exception ee){
			   validMove = false;
			   display.setText("\n\n*** Bad Input, please try again! \n");
			}
           
		}
		else if ( command.equals( titles[5] ) )
		{
			try{
			  bd.movePeg32();
			}catch (Exception ee){
			   validMove = false;
			   display.setText("\n\n*** Bad Input, please try again! \n");
			}
           
		}
                if ( validMove )
		{
			processManual();
		}
     }
 
         	private void jButton7_actionPerformed(ActionEvent e) 
 	{
                    
                    reset();
  
 	}
                
                private void jButton8_actionPerformed(ActionEvent e) 
 	{
                    display.setText("INSTRUCTIONS\n\nThe object is to move all the disks from the left to the right pole.\nYou can only move one disk at a time and you must follow size order\n(a bigger disk can't go on a smaller disk).\nIf using manual mode please use the 'P' buttons to make your moves.\n\n\n");
                    
  
 	}
                
        private void reset(){
            for(int i = 0; i < discNum; i++) {
            bd.withdraw();}
            count = 0;
            discNum = 0;
            optimum = 0;
            getDiscCount();
            getMode();
            
        }
                
                private void notifyWin()
	{
		    if (count==optimum){
                        display.setText("!!!!!WOOTAAAH!!!!!!\nYou finished in the optimum moves possible.\n\nYou have attained the rank of:\n\nTOWERS OF HANOI JEDI MASTER");
                    }
                    if (count-optimum<3&&count-optimum>0){
                        display.setText("\nYou finished the game a few moves over what you needed.\n\nNot to bad I guess, but try harder next time\n\nYou have attained the rank of:\n\nTOWERS OF HANOI CASUAL PLAYER");
                    }
                    if (count-optimum>3&&count-optimum<8){
                        display.setText("\nYou finished the game quite a few moves over what you needed.\n\nBetter luck next time ay\n\nYou have attained the rank of:\n\nTOWERS OF HANOI STABLE HAND");
                    }
                    if (count-optimum>8){
                        display.setText("\nYou finished the game majorly behind.\nI suggest you get in alot of practice.  You need it!\n\nYou have attained the rank of:\n\nTOWERS OF HANOI TOILET CLEANER");
                    }
                    String conGratMessage = "Congratulations!!  You have completed the game!!\n\n" +
								"The optimum number of moves was: " + optimum +
								"\nIt took you " + count + " moves to finish.\nPress reset to try again";

		JOptionPane.showMessageDialog(null, conGratMessage );
	}
        
        private void processManual(){
		
                count++;
		

		if (bd.gameFINISH())
		{
                    bd.printBoard();
			notifyWin();
		}
		else
		{
			
                    display.setText ("So far you have made " + count +  " moves.\nPlease choose another peg move");
                        bd.printBoard();
			
		}
	}
        
        private void processAutomatic()
	{
		bd.pushPeg();

		try
		{
			bd.initSolve(discNum);
                        
		}
		catch (Exception ee)
		{
			display.setText("\n\n*** Bad Input, please try again! \n");
		}
	}
        	
        public static void main(String[] args){ 
            JFrame.setDefaultLookAndFeelDecorated(true); 
 		JDialog.setDefaultLookAndFeelDecorated(true); 
 		try 
 		{ 
 			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                        //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
 		} 
 		catch (Exception ex) 
 		{ 
 			System.out.println("Failed loading L&F: "); 
 			System.out.println(ex); 
 		} 
 		new Main(); 
        } 
 }
 		 
 



Heres what I wrote in board class for the reset click event
JAVA Code:
 public void withdraw(){
        try{
            peg1.pop();
            peg2.pop();
            peg3.pop();
        }catch (Exception e){
            
        }
        
    }


Hey thanks again in advance if you actually get time to take a look at this again for me. My codes bit more messy now too, cause I got tired of making it tidy as I go, im just going to go through it tommorow and straighten it up again lol.
  #9  
Old 14-May-2008, 10:50
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,233
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Trouble integrating console code into GUI


Sure I can look at those later today.

Also, this is killing me a bit with the buttons, specifically:
JAVA Code:
        private JButton b7;
        private JButton b8;
Out of curiosity, is there any reason not to have added them to the JButton array?

Earlier I said:
Quote:
Originally Posted by turbopt
I can't explain it all at the immediate moment...

So, I can cover how the button creation and handling works together if there is/was some apprehension about breaking something. (I didn't get a chance to add all the commentary that I wanted before stopping last night, but comments will be included in the next run of change(s))
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #10  
Old 14-May-2008, 14:45
Barman007 Barman007 is offline
New Member
 
Join Date: May 2008
Posts: 10
Barman007 is on a distinguished road

Re: Trouble integrating console code into GUI


Ahh b7 and b8, the reason I didnt add them to the array was because I was having trouble with button P 3to2, its not working, so instead of trying to add b7 and b8, I was just going to take a look at it when I had time, but ended up spending all day working on other problems.

I've got class now and it is due tommorow so i'll add them to the button array when I get to class easy enough.

Now im pretty sure I just need to get my print functions returning strings to make them setText in my GUI, I was playing around with toString last night but was having a few problems.

Once I can get them returning string values I was hoping to be able put them into an array something like this to get it printing out vertically.........

JAVA Code:
public static String[][] display(Peg[] pegs) 
{ 
   // Find the highest peg 
   int maxHeight = 0; 
   for ( int i = 0; i < pegs.length; i++ ) 
   { 
      if ( pegs[i].getHeight() > maxHeight ) 
      { 
         maxHeight = pegs[i].getHeight(); 
      } 
   } 

   // Create and fill the array to hold the output 
   String[][] output = new String[pegs.length][maxHeight]; 
   for ( int i = 0; i < pegs.length; i++ ) 
   { 
      String[] pegOutput = peg.print().split("\s"); 
      for ( int j = (maxHeight-1), k = 0; (j >= 0) && (k < pegOutput.length); j--, k++ ) 
      { 
         output[i][j] = pegOutput[k]; 
      } 
   } 
   return output; 
}

And output it something like.....

JAVA Code:
String[][] output = display(myPegs); 
for ( int i = 0; i < output.length; i++) 
{ 
   for ( int j = 0; j < output[i].length; j++ ) 
   { 
      if ( output[i][j] != null ) 
      { 
         System.out.print(output[i][j]+"t"); 
      } 
      else 
      { 
         System.out.print(" t"); 
      } 
   } 
   System.out.println(); 
}


Sorry i've got so many questions but we havnt even been taught java, i've had to teach myself in the last 4 weeks. I learnt C# last year so im familiar with what I need to do, its just hard sometimes to find the right syntax. This is a class in data structures and algorithms, my stupid university thinks it good to teach you one language, then try to teach to more advanced stuff in a language your not familiar with. Maybe its character building lol.

Thanks again if you get a chance to take a look for me, much appreciated mate
 
 

Recent GIDBlogNot selected for officer school by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Need code to hide a console program from startup lockd C++ Forum 1 14-Aug-2007 18:03
How to sort random access file? wmmccoy0910 C Programming Language 12 04-Sep-2006 03:40
Here it is again! 35% - 40% off For Life! my-e-space Web Hosting Advertisements & Offers 0 20-Apr-2006 14:48
Guidelines for posting requests for help - UPDATED! WaltP C Programming Language 0 21-Apr-2005 02:44

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 20:05.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.