Parameter passing problem !!!


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: Parameter passing problem !!!

  1. #1
    Join Date
    Nov 2004
    Posts
    9

    Parameter passing problem !!!

    Hi,

    I have a simple problem with passing a variable from one class to another. Basically the variable is calculated in a listerner event, passed from that class to another and displayed.

    I have the program running and compiling, although the end result is not what it should be. I always get the end result of 0 instead of a calculated result. The user must choose a type either adult, child, student then enter a number in the text field then click confirm which will bring up result with how much it will cost.

    First class CalculcatePanel
    Code:
    public class CalculatePanel extends JPanel{   
       
    public int totalcost;
    public int ticketcost;
    public int number;
    public JTextField TicketText;
    public JButton TicketButton; 
    public String typechosen;
    public String[] type = {"Select", "Adult", "Child", "Student"};
    public JComboBox typecombo;
        
        /** Creates a new instance of addpanel */
        public void addPanel() {         
           
            JPanel typeinfo = new JPanel(); 
            typeinfo.setBorder(BorderFactory.createLoweredBevelBorder());        
            typeinfo.setBackground (Color.yellow); 
            typeinfo.setPreferredSize(new Dimension(200,200));  
            
            typecombo = new JComboBox(type);
            typecombo.addItemListener(new TypeInfoComboBox()); 
            
            TicketText = new JTextField (5);
            TicketText.addActionListener(new TicketButton());  
            
            add(typecombo);
            add(TicketText);       
        }
        
    public class TypeInfoComboBox implements ItemListener  {
         
        public void actionPerformed(ActionEvent e) {}
        
            public void itemStateChanged( ItemEvent event ) 
            {
                typechosen = (String) typecombo.getSelectedItem();
                
            if (typechosen == "Adult")
             {
                 ticketcost = 5;                              
             }        
            else if (typechosen == "Child")
            {
                 ticketcost = 3;                              
            }         
            else if (typechosen == "Student")
            {
                ticketcost = 4;            
            }         
        }  
    } 
     
    public class TicketButton implements ActionListener 
         {    
            public void actionPerformed(ActionEvent e) 
                {
                String text = TicketText.getText();
                number = Integer.parseInt(text);  
                
                //total cost calculated here 
                totalcost = ticketcost * number;      
                JOptionPane.showMessageDialog(null, "Total Booking Cost Will be : " + totalcost);            
                }
    }
    //method getcost to pass totalcost variable to class ConfirmBooking         
    public int getcost()
       {   
          //i also put the calculation here to see if this worked but it didnt 
          totalcost = ticketcost * number; 
          return totalcost;     
       }
    }
    Second Class ConfirmBooking
    Code:
    public class ConfirmBooking {   
        
        /** Creates a new instance of ConfirmBooking */
        public void ConfirmBooking() {      
           
            CalculatePanel cost = new CalculatePanel();       
            
            JOptionPane.showMessageDialog(null, "Your Booking Has Been Confirmed.\n\nPayment Of " 
            + cost.getcost() + " Has been Transacted.\nThankyou for booking with us", 
            "***** Congratulations *****",+JOptionPane.INFORMATION_MESSAGE);
            System.exit( 0 ); // Exits Program 
        }    
    }
    Third Class Panel - main frame
    Code:
    public class Panel extends JFrame
    {   
    public JPanel cost;
        
    public static void main(String[] args) 
    {
        Panel frame = new Panel();     
    }
    public Panel() {      
            
            JButton     okButton;         
            //set up main frame   
            JFrame frame = new JFrame();        
            frame.setTitle("");   
            frame.setLocation(100,100);       
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);         
            //set up panel with compound border      
            
            CalculatePanel cost;
            cost = new CalculatePanel();
            cost.addPanel();        
            
            JPanel okPanel = new JPanel();        
            okButton = new JButton("CONFIRM");
            okButton.addActionListener(new confirmButton());
            okPanel.add(okButton);         
            okPanel.add(cost);      
           
            frame.getContentPane().add(okPanel, BorderLayout.CENTER);       
            frame.pack();
            frame.setVisible(true);          
    }
    private class confirmButton implements ActionListener  
    {     
        public void actionPerformed(ActionEvent e) 
        {
            ConfirmBooking confirm;
            confirm = new ConfirmBooking();
            confirm.ConfirmBooking();        
        }    
      }
    }
    Anybody got any ideas.

    Thanks

  2. #2
    Join Date
    Sep 2004
    Posts
    150
    Yes,

    This code is never executed. Thus your number value stays at 0 forever. Since you you then multiply by 0, your totalcost is 0.

    Code:
    public class TicketButton implements ActionListener 
         {    
            public void actionPerformed(ActionEvent e) 
                {
                String text = TicketText.getText();
                number = Integer.parseInt(text);  
                
                //total cost calculated here 
                totalcost = ticketcost * number;      
                JOptionPane.showMessageDialog(null, "Total Booking Cost Will be : " + totalcost);            
                }
    }



    A previous Java release would've blown up on you for trying to use a variable that was never initialized (number). But apparently in 1.5 they graciously gave it a default value of 0. Thus you didn't see the problem.

    - It is always a good idea to suspect multiplication by 0 when you get a 0 answer in your calculations in any program.

    Now, for the solution: This ActionListener is not sufficient for a JTextField. In other words it doesn't do anything. You have to add a DocumentListener, and setting one of them up is a chore. Because I played with the idea on your code. You will also have to handle things such as invalid data, as when I made the documentListener it would blow up when you typed a letter in the field and the parseInt tried to parse it (people will do this). A try/catch block will be necessary at that point.

    Anyway, that's where the problem lies. I didn't post code because I had to change so much it would probably confuse you. So just know that you need to get a better listening device.

    I would suggest moving that (the code that parses for an int) elsewhere. It would be best if it could be done when the "confirm" button is pressed. That way you know the text has been entered.

    With a documentlistener, it's going to give them an annoying popup everytime they enter a single character the way you have it setup.

  3. #3
    Join Date
    Nov 2004
    Posts
    9
    Hi,

    to start with ive changed the way i compare strings which looks much better now..

    As for the text field listerner..I have set up a document listerner and it compiles but i still get the same 0 answer which would show i still have a problem with the listerner. Can you check it over, cos i cant see whats wrong with it.

    The class with the doucment listener in is as follows:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.JOptionPane;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    
    public class BookingCost extends JPanel implements ItemListener, DocumentListener, ActionListener {
        
        public String[] type = {"Select", "Adult", "Child", "Student"};
        public String typechosen;
        public JComboBox typecombo, numbercombo;
        public int ticketcost, number, totalcost;
        public JLabel typeresult; 
        
        public int screen1 = 50;
        public int screen2 = 75;
        public int screen3 = 100;   
        
        public JTextField tickettext;
        public JButton ticketbutton;    
        
        /** Creates a new instance of BookingInfo */
        public void BookingType() {         
            
            JPanel typeinfo = new JPanel(); //(new FlowLayout(FlowLayout.CENTER,30000,5));       
            typeinfo.setBorder(BorderFactory.createLoweredBevelBorder());        
            typeinfo.setBackground (Color.yellow); 
            typeinfo.setPreferredSize(new Dimension(150,90)); 
            JLabel costlabel1 = new JLabel ("Select Ticket Type");
            costlabel1.setFont(new Font("Serif", Font.BOLD, 14));
            costlabel1.setForeground(Color.black);
            
            typecombo = new JComboBox(type);
            typecombo.addItemListener(this); 
            
            typeinfo.add(costlabel1);
            typeinfo.add(typecombo);
            typeresult = new JLabel();        
            
            typeinfo.setVisible(true); 
            add(typeinfo);
            
            JPanel numberinfo = new JPanel(); //(new FlowLayout(FlowLayout.CENTER,30000,5));       
            numberinfo.setBorder(BorderFactory.createLoweredBevelBorder());        
            numberinfo.setBackground (Color.yellow); 
            numberinfo.setPreferredSize(new Dimension(150,90)); 
            JLabel numberlabel1 = new JLabel ("Tickets Needed");
            numberlabel1.setFont(new Font("Serif", Font.BOLD, 14));
            numberlabel1.setForeground(Color.black); 
            
            tickettext = new JTextField (5);        
            
            Document document = tickettext.getDocument();
            document.addDocumentListener( this );
    
            ticketbutton = new JButton("BOOKING COST");
            ticketbutton.addActionListener(this);
            
            numberinfo.add(numberlabel1);
            numberinfo.add(tickettext);      
            numberinfo.add(ticketbutton);
            add(numberinfo);        
     } 
        
    public void itemStateChanged( ItemEvent event ) 
            {
                typechosen = (String) typecombo.getSelectedItem();           
             
                    if ( typechosen.equals("Adult"))
                     {
                         ticketcost = 5;                               
                     }        
                    else if ( typechosen.equals("Child"))
                    {
                         ticketcost = 3;                                   
                    }         
                    else if ( typechosen.equals("Student")) 
                    {
                         ticketcost = 4;                        
                    }         
            }  
    
    public void actionPerformed(ActionEvent e) 
            {                     
                JOptionPane.showMessageDialog(BookingCost.this, "Total Booking Cost Will be : " + totalcost);    
            }
      
    // Handle insertions into the text field  
    public void insertUpdate( DocumentEvent event )
    	{
    		String	sString	= tickettext.getText();            
    
    		try	{
    			number = Integer.parseInt(sString);    
                            totalcost = ticketcost * number;  
                            ticketbutton.setEnabled( true );
    		}
    		catch( NumberFormatException e )
    		{
    			ticketbutton.setEnabled( false );
    		}
    	}
    
    	// Handles deletion from the text field
    	public void removeUpdate( DocumentEvent event )
    	{
    		// Prevent the user	from entering a blank field
    		if(	tickettext.getText().length() == 0 )
    			ticketbutton.setEnabled( false );
    		else
    		{
    			// Do the same error checking as insertUpdate()
    			insertUpdate( event );
    		}
    	}
    
    	// Handle changes to the text field
    	public void changedUpdate( DocumentEvent event )
    	{}
            
    //method getcost to pass totalcost variable to class ConfirmBooking         
    public int getcost()
       {  
          return totalcost;     
       }
    }
    The bits in bold are for the document listener and have just been added.

    Anybody got any ideas...

  4. #4
    Join Date
    Sep 2004
    Posts
    150
    Hmm

    It looks like your code has changed significantly since your last effort. It looks better in a lot of ways, but I can't figure out how to get it to work with the other classes and it doesn't seem to stand on its own..

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center