Results 1 to 6 of 6
  1. #1
    elvis0288 is offline Member
    Join Date
    Jan 2012
    Posts
    21
    Rep Power
    0

    Default problem communicating between GUIS

    hi my problem is that i have one gui that when press button you can create another gui, so my problem is that if i have multiples of this GUIs open i need to know which reference is which so if i want to send value from the main gui to one of the guis i can do it but i do not have any idea on how to do it... please help this is my code so far:

    this is what i have to do:
    Modify MDIGridBag.java and MDICraps.java as necessary so that the MDIGridBag
    instance has a button that causes the current “Sum of Craps Totals…”
    value to be sent to a particular instance of MDICraps.


    this is the main GUI

    Java Code:
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.swing.*;
    
    public class MDIGridBag extends JFrame implements ActionListener{
       private GridBagLayout gbLayout;
       private GridBagConstraints gbConstraints;
    //70
       private int crapsTotal;
       private JTextField crapsTotalText;
       private JComboBox comboBox;
       private FileInputStream infile;
       private DataInputStream dataInputStream;
       
    
      public MDIGridBag( ) {
          super("MDIGridBag");
          String textFromFile="";
    //80
          gbLayout = new GridBagLayout();
          setLayout( gbLayout );
       
          // instantiate gridbag constraints
          gbConstraints = new GridBagConstraints();
    
          // create GUI components
          String gamingRules[] = { "House Rules",
                                "Las Vegas Rules", "Atlantic City Rules"};
    //90
          comboBox = new JComboBox( gamingRules );
    
          JTextArea textArea = new JTextArea(getDataFromFile());
          
          String maxBet[] = { "$10000", "$12000", "$14000" };
          JList list = new JList( maxBet );
    
          String names[] =
             { "Play Craps", "Play Rock-Scissor-Paper", "Play Go-Fish"};
    //100
          JLabel crapsTotalLabel = new JLabel("Sum of Craps Totals "
                                               +"sent by Craps Games.");
          crapsTotalText = new JTextField( 5 );
          crapsTotalText.setEditable( false );
    
          JButton buttons[] = new JButton[ names.length ];
          for ( int i = 0; i < buttons.length; i++ ){
               buttons[ i ] = new JButton( names[ i ] );
               buttons[i].addActionListener(this);
    //110
          }
    
           // define GUI component constraints for textArea   
          gbConstraints.weightx = 1;  // relative weight of horizontal growth
          gbConstraints.weighty = 1;  // relative weight of vertical growth
          gbConstraints.fill = GridBagConstraints.BOTH;
          gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
          addComponent( new JScrollPane(textArea) );
    
    //120
          // buttons[0] -- weightx and weighty are 1: fill is BOTH
          gbConstraints.gridwidth = 1; // 1 column
          addComponent( buttons[ 0 ] );
    
          // buttons[1] -- weightx and weighty are 1: fill is BOTH
          gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
          addComponent( buttons[ 1 ] );  //goes next to previous component(RELATIVE)
    
          // buttons[2] -- weightx and weighty are 1: fill is BOTH
    //130
          gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
          addComponent( buttons[ 2 ] );   // last on current row (since REMAINDER)
    
          // comboBox -- weightx is 1: fill is BOTH   
          gbConstraints.weighty = 0;
          gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
          addComponent( comboBox );
         
          // list -- weightx and weighty are 1: fill is BOTH
    //140
          gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
          addComponent( list );
    
          gbConstraints.gridx = 0;  // can also specify particular column
          gbConstraints.gridy = 5;  // and a specific row
          gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
          addComponent( crapsTotalLabel );
    
          gbConstraints.gridx = 2;
    //150
          gbConstraints.gridy = 5;
          gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
          addComponent( crapsTotalText );
          crapsTotalText.setText(Integer.toString(crapsTotal));
          
          JButton sendtochild = new JButton("Send to Game");
          gbConstraints.gridy = 6;
          addComponent(sendtochild);
          
          
       }   // end MDIGridBag
    
      
       // addComponent is programmer-defined
     private void addComponent( Component c )
    //160
     {
          gbLayout.setConstraints( c, gbConstraints );
          add( c );      // add component
       }
    
     
     public void actionPerformed(ActionEvent e)
     {
         JOptionPane.showMessageDialog(null,
             "You pressed: " + e.getActionCommand() +
             ".  Program detected that the "
             + comboBox.getSelectedItem()
             + " option was selected from the pulldown menu.");
         if (e.getActionCommand() == "Play Craps")
         {
             JOptionPane.showMessageDialog(null,
                "Launching Craps Game in a new window, new window contains a link" +
                " back to parent.");
             playCrapsWindow();
    //180
         }  // end if
    
     } // end actionPerformed
    
     
      public void playCrapsWindow()
      {
         // Each instance of Craps launches in its own JFrame
         // See MDICraps constructor
        MDICraps myCraps = new MDICraps(this);
     }  // end playCrapsWindow
    
      
     public void addToCrapsTotal(int amountToAdd)
     {
      crapsTotal += amountToAdd;
      crapsTotalText.setText(Integer.toString(crapsTotal));
     }// end addToCrapsTotal
    
    //200 
     private String getDataFromFile()
     {
      String readInText = null;
      try {
          infile = new FileInputStream("data.dat"); //assoc file with file handle
          BufferedReader dataFile = new BufferedReader(new InputStreamReader(infile));
          readInText = dataFile.readLine();
          dataFile.close();
          }
    //210
      catch (FileNotFoundException e){
             System.out.println("File Not Found" + infile);
          }
      catch (IOException e){
             System.out.println("IOException");
          }
      return readInText;
     }// end getDataFromFile
    
    } // end MIDGridBag class definition
    this is the one that creates instances


    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*; // for file I/O
    
    public class MDICraps extends JFrame implements ActionListener {
       // constant variables for status of game
       final int WON = 0, LOST = 1, CONTINUE = 2;
    
       // other variables used in program
       boolean firstRoll = true;   // true if first roll
       int sumOfDice = 0;          // sum of the dice
       int myPoint = 0;   // point if no win/loss on first roll
       int gameStatus = CONTINUE;  // game not over yet
       int bankRoll = 50;          // start with $50 bankroll
    
       // graphical user interface components
       JLabel die1Label, die2Label, sumLabel, pointLabel, gameResultLabel;
       JTextField firstDie, secondDie, sum, point, gameResult;
       JButton roll;
    
       JLabel bankRollLabel;
       JTextField bankRollText;
       JButton save;
       MDIGridBag creator;
       JButton sendToCreatorButton;
       // output file
       BufferedWriter outFile;
    
       // setup graphical user interface components
     //  public void init()
    public MDICraps(MDIGridBag creatorLink)
       {
           super("Craps Game");
           creator = creatorLink; // link for comm with caller
           // new standalone frame to display components in
    //       JFrame frame = new JFrame("Craps Game");
    //       Container c = frame.getContentPane();
           setLayout( new FlowLayout() );
    
          die1Label = new JLabel( "Die 1" );
          add( die1Label );
          firstDie = new JTextField( 10 );
          firstDie.setEditable( false );
          add( firstDie );
    
          die2Label = new JLabel( "Die 2" );
          add( die2Label );
          secondDie = new JTextField( 10 );
          secondDie.setEditable( false );
          add( secondDie );
    
          sumLabel = new JLabel( "Sum is" );
          add( sumLabel );
          sum = new JTextField( 10 );
          sum.setEditable( false );
          add( sum );
    
          pointLabel = new JLabel( "Point is" );
          add( pointLabel );
          point = new JTextField( 10 );
          point.setEditable( false );
          add( point );
    
          roll = new JButton( "Roll Dice" );
          roll.addActionListener( this );
          add( roll );
    
          // save to file
          save = new JButton( "Save Bankroll to file" );
          save.addActionListener( this );
          add( save );
    
          sendToCreatorButton = new JButton( "Send Bankroll to Creator Applet" );
          sendToCreatorButton.addActionListener( this );
          add( sendToCreatorButton );
    
    
          bankRollLabel = new JLabel( "Bankroll" );
          add( bankRollLabel );
          bankRollText = new JTextField( 10 );
          bankRollText.setEditable( false );
          add( bankRollText );
          bankRollText.setText(Integer.toString(bankRoll));
    
    
          gameResultLabel = new JLabel( "Game Status" );
          add( gameResultLabel );
          gameResult = new JTextField( 30 );
          gameResult.setEditable( false );
          add( gameResult );
          gameResult.setText("Click Roll Dice to play.");
    
         setSize(400,200);
         setVisible(true); 
    
       } // end MDICraps( )
    
    
       // call method play when button is pressed
       public void actionPerformed( ActionEvent e )
       {
          // choose what action to perform based on the source
          // of the ActionEvent
    
          if (e.getSource() == roll){          
              play();
          }
    
          if (e.getSource() == save){
              saveBankRollToFile();
              roll.setEnabled(true);
          }
          if (e.getSource() == sendToCreatorButton){
               creator.addToCrapsTotal(bankRoll);
               bankRoll = 0;
               bankRollText.setText(Integer.toString(bankRoll));
               sendToCreatorButton.setEnabled(false); // only allows send
               gameResult.setText("Notice that the \"Send Bankroll ...\" button has been disabled.");
          }
       }
    
      // save value of bankroll to file
      public void saveBankRollToFile(){
    
           String outputFileName = new String("bankroll.txt");
    
          // erases prior contents of file and writes current bankroll amount
      try {
          outFile = new BufferedWriter(new FileWriter(outputFileName));
        } // end try
    
        catch (IOException e) {
           System.out.println("IO Problem!");
           e.printStackTrace();
        }  // end catch
    
        try {
            outFile.write(String.valueOf(bankRoll));
            gameResult.setText("Bankroll written to bankroll.txt.");
            outFile.close();
        } // end try
        catch (IOException e){
           System.out.println(e.toString());
        } // end catch
    
      } // end openFiles
    
    
       // process one roll of the dice
       public void play() {
    
          if ( firstRoll ) {             // first roll of the dice
             sumOfDice = rollDice();
    
             switch ( sumOfDice ) {
                case 7: case 11:         // win on first roll
                   gameStatus = WON;
                   point.setText( "" );  // clear point text field
                   break;
                case 2: case 3: case 12: // lose on first roll
                   gameStatus = LOST;
                   point.setText( "" );  // clear point text field
                   break;
                default:                 // remember point
                   gameStatus = CONTINUE;
                   myPoint = sumOfDice;
                   point.setText( Integer.toString( myPoint ) );
                   firstRoll = false;
                   break;
             }
          }
          else {   // not first roll
             sumOfDice = rollDice();
    
             if ( sumOfDice == myPoint ) {   // win by making point
                gameStatus = WON;
             }
             else
                if ( sumOfDice == 7 ) {      // lose by rolling 7
                   gameStatus = LOST;
                }
          }
    
    
          if ( gameStatus == CONTINUE ){
    
             gameResult.setText( "Click Roll Dice again to continue play." );
    
             }
          else {
             if ( gameStatus == WON ) {
    
             gameResult.setText( "Player wins. " +
                   "Click Roll Dice to play again." );
                bankRoll += 5;
             }
             else {
    
              gameResult.setText( "Player loses. " +
                   "Click Roll Dice to play again." );
                bankRoll -= 5;
             }
    
             firstRoll = true;
    
             bankRollText.setText(Integer.toString(bankRoll));
          }
    
       }
    
       // roll the dice
       public int rollDice()
       {
          int die1, die2, workSum;
    
          die1 = 1 + ( int ) ( Math.random() * 6 );
          die2 = 1 + ( int ) ( Math.random() * 6 );
          workSum = die1 + die2;
           // display new values to TextFields in content pane
          firstDie.setText( Integer.toString( die1 ) );
          secondDie.setText( Integer.toString( die2 ) );
          sum.setText( Integer.toString( workSum ) );
          bankRollText.setText(Integer.toString(bankRoll));
    
          return workSum;
       }
    }
    if you want to run this is the test class

    Java Code:
    /*
     * MDIGridBagTest.java
     *
     * Created on January 26, 2006, 8:28 PM
     *
     */
    import javax.swing.*;
    
    /**
     *
     * @author CAPT Paul Young
     */
    public class MDIGridBagTest {
        
       public static void main (String args[]){
            MDIGridBag myMDIGridBag = new MDIGridBag();
            myMDIGridBag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myMDIGridBag.setSize(400, 200); //width,height in pixels
            myMDIGridBag.setVisible(true);  //otherwise, won't be seen!
       }// end main
        
    }// end MDIGridBagTest

  2. #2
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default Re: problem communicating between GUIS

    One possible solution is that you store the references to an ArrayList as you create them and assign them with a unique ID yourself or override the hashCode() method that will return a unique Code for every different GUI.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,236
    Rep Power
    19

    Default Re: problem communicating between GUIS

    Sorry, but where does hashCode() come into this?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    elvis0288 is offline Member
    Join Date
    Jan 2012
    Posts
    21
    Rep Power
    0

    Default Re: problem communicating between GUIS

    so if it is no hashcode what should i do??

  5. #5
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default Re: problem communicating between GUIS

    Quote Originally Posted by DarrylBurke View Post
    Sorry, but where does hashCode() come into this?

    db
    Well the HashCode() method from the Object class may not come into scenario for many. I prefer One separate class for a GUI Window. For identifying different objects from the same class hashCode can be used. But I know the much easier method will be to user some custom identifier with every object.

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

    Default Re: problem communicating between GUIS

    Your question is a bit vague. How are you going to decide which object to send the message to? By a String? By its religion? Once you figure that out, you'll know how to solve this. If by String, then store all the MDIcraps in a HashMap<String, MDICraps>, if by the order created, then store them in an ArrayList<MDICraps>.

Similar Threads

  1. GUIs in RCP
    By noodle_variation_187-X in forum Eclipse
    Replies: 0
    Last Post: 08-24-2011, 03:59 PM
  2. Problem with GUIS
    By sunde887 in forum New To Java
    Replies: 1
    Last Post: 02-17-2011, 07:18 AM
  3. Replies: 0
    Last Post: 10-18-2010, 05:18 AM
  4. Can you create two GUIs?
    By SNPTT in forum New To Java
    Replies: 4
    Last Post: 05-18-2010, 11:08 AM
  5. guis and php
    By paddala in forum Advanced Java
    Replies: 1
    Last Post: 02-18-2010, 02:43 AM

Posting Permissions

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