A little help with getting varaibles from another class

hey,
so i have these two classes and they both are GUI's. the first main class is called GUI (very original) and he second is called adder. so when i click a button on GUI it creates and shows the adder GUI wich gets user input, when the user clicks the done button on the adder gui it does this this:
      * method to dispose of the gui without deleting the object
     public void close()
         addWindow.dispose();
      * method for when the done button is clicked
     private void buttonClicked()
     personName = ename.getText();
        personPin = epin.getText();
        personAddress = address.getText();
        close();
    }then we go to the GUI class and do this:
public void addPart2()
        lm.addElement(adder.personName + "-" + adder.personID + "-" + adder.personAddress + "-" + adder.personPin );
    }(all varibless are public by the way), so when i go and have a method directly call adderPart2 right after the adder gui is closed it comes up with all variables bieng null, but if i go in and manualy call the method without doing anything else it works, can anyone explainthis and/or hellp me?

so does anyone have a solution for this problem or at least know what is happening?
Thanks a-bundle,
Mike M

Similar Messages

  • Calling a TextFields get method from another class as a String

    This is my first post so be kind....
    I'm trying to create a login screen with Java Studio Creator. The Login.jsp has a Text Field for both the username and password. JSC automatically created get and set methods for these.
    public class Login extends AbstractPageBean
    private TextField usernameTF = new TextField();
    public TextField getUsernameTF() {
    return usernameTF;
    public void setUsernameTF(TextField tf) {
    this.usernameTF = tf;
    private PasswordField passwordTF = new PasswordField();
    public PasswordField getPasswordTF() {
    return passwordTF;
    public void setPasswordTF(PasswordField pf) {
    this.passwordTF = pf;
    My problem is in trying to call these methods from another class and return the value as a string.
    Any help on this matter would be greatly appreciated.

    the method returns the textfield, so you just need to get its text
    import java.awt.*;
    class Testing
      public Testing()
        Login login = new Login();
        System.out.println(login.getUsernameTF().getText());//<----
      public static void main(String[] args){new Testing();}
    class Login
    private TextField usernameTF = new TextField("Joe Blow");
    public TextField getUsernameTF() {
        return usernameTF;
    }

  • Problem getting arraylist from another class

    I am trying to call information about an arraylist from another class. I am using this code to call the size of an arraylist:
    import java.io.*;
    public class Test
        public static void main(String argv[]) throws IOException
    Echo03 thing = new Echo03();
    int y=thing.value();
    System.out.println(y);
    Echo03 thing2 = new Echo03();
    int x=thing2.percent.size();
    System.out.println(x);
    }from another file which starts like this:
    public class Echo03 extends DefaultHandler
    static ArrayList<String> percent = new ArrayList<String>();
    static ArrayList<String> text = new ArrayList<String>();
      int a;
    public int value(){
         return percent.size();
      public static void main(String argv[]) throws IOException
        {The second file is based on an example piece of code from the Java website. I havent posted the whole thing, but if it is relevant then please ask.
    Anyway when I run Echo03 by itself, the arraylist has a size of 2. But when I run it from the Test file, it says a size of 0. Is this because the data is not being transferred between the classes? Or is the Echo03 program not executing (and hence the arraylist is not filling up)?
    How can I fix this? I have tried 2 ways of calling the data (As seen in my Test file). Neither work.

    I didnt post the full bit of the code for the second one. Here it is:
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import java.util.ArrayList;
    import java.awt.*;
    import javax.swing.*;
    public class Echo03 extends DefaultHandler
    static ArrayList<String> percent = new ArrayList<String>();
    static ArrayList<String> text = new ArrayList<String>();
      int a;
      public static void main(String argv[]) throws IOException
            if (argv.length != 1) {
                System.err.println("Usage: cmd filename");
                System.exit(1);
            // Use an instance of ourselves as the SAX event handler
            DefaultHandler handler = new Echo03();
            // Use the default (non-validating) parser
            SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                // Set up output stream
       out = new OutputStreamWriter(System.out, "UTF8");
                // Parse the input
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse( new File(argv[0]), handler);
    for (int b=0; b<percent.size();b++){
         System.out.println(percent.get(b+1));
            } catch (Throwable t) {
            System.exit(0);
        static private Writer  out;
        public void startElement(String namespaceURI,
                                 String lName, // local name
                                 String qName, // qualified name
                                 Attributes attrs)
        throws SAXException
            if (attrs != null) {
    StringBuffer sb = new StringBuffer (250);        
    for (int i = 0; i < attrs.getLength(); i++) {
                    nl();
                    emit(attrs.getValue(i));
              sb.append (attrs.getValue(i));
    String sf = sb.toString ();
    percent.add(sf);
    System.out.println(" String: "+sf); a++;
        public void characters(char buf[], int offset, int len)
        throws SAXException
             emit(" ");
            String s = new String(buf, offset, len);
            if (!s.trim().equals("")) {text.add(s); emit(s);}
    //===========================================================
        // Utility Methods ...
        //===========================================================
        // Wrap I/O exceptions in SAX exceptions, to
        // suit handler signature requirements
        private void emit(String s)
        throws SAXException
            try {
                out.write(s);
                out.flush();
            } catch (IOException e) {
                throw new SAXException("I/O error", e);
        // Start a new line
        private void nl()
        throws SAXException
            String lineEnd =  System.getProperty("line.separator");
            try {
                out.write(lineEnd);
            } catch (IOException e) {
                throw new SAXException("I/O error", e);
    }

  • How to get variable from another class?

    I have 2 classes. In first I have int variable. In second class I need to get this variable value. How I can make it?
    import javax.microedition.lcdui.*;
    import java.io.*;
    import java.util.*;
    public class ChooseLessons extends Form implements CommandListener, ItemStateListener
         ChoiceGroup lessons;     // Choice Group of preferences
         Dictionary     dictionary;
         int volumeSize;
         ChooseLessons(Dictionary dictionary)
              int volumeSize = 15;
         public void commandAction(Command c, Displayable s)
              if (c == Dictionary.BEGIN_CMD) {
                   new TeachForm(dictionary, this);
    import javax.microedition.lcdui.*;
    import java.util.*;
    public class TeachForm extends Form implements CommandListener     
         Dictionary               dictionary;
         ChooseLessons          lessons;
         TeachForm(Dictionary dictionary, ChooseLessons lessons) {
              super(Locale.WORD);
              this.dictionary = dictionary;
              this.lessons = lessons;
              lessons.volumeSize(); // HERE I NEED VARIABLE VALUE FROM PREVIOUS CLASS
    }Edited by: Djanym on Mar 16, 2009 4:43 PM

    This is a classic problem that coders run into when trying to get their head around object-oriented programing. Since you have a class that should be modeled after a real world object, as far as that object is concerned, no one else needs to know the details of it - without asking nicely. This is where you should set up some getters and setters, which are methods that allow fields in a class to reveal themselves or allow their states to be changed in a orderly fashion.
    There are a number of fields that never need to be known outside of the class. Then there are some fields you would like to let people know about, but don't want them to have the ability to change them. In the example below, there are to getter methods allow return of the necessary fields. If you made these public, there is a possibility that someone utilizing this field may change it outside of its intended use, or access them without them being ready for public consumption.
    Class test {
    //These private variables are only visible from the class
    private int grade1 = 0;
    private int grade2 = 0;
    private int grade3 = 0;
    private float average = 0;
    private int gradeboost = 0;
    //This method sets the gradeboost field to one desired by the instructor
    void setboost(int boost) {
    gradeboost = boost;
    //These methods accept test scores and compute the average for three test
    //Notice that the calculated average may not be the true average of the three test scores
    //because of the possibility of gradeboost calculation being greater than 1
    void test1(int score) {
             grade1 = score;
             average = (grade1 + grade2 + grade3 + gradeboost)/3;
    void test2(int score) {
             grade2 = score;
             average = (grade1 + grade2 + grade3 + gradeboost)/3;
    void test3(int score) {
             grade3 = score;
             average = (grade1 + grade2 + grade3 + gradeboost)/3;
    //This is a getter method, which provides read access to the private variable average
    //If someone just had public access to the grades and wanted to take their own average
    //They would miss how the gradeboost field affects the final outcome.
    float getAverage() {
        return average;
    //Here is a getter method, which accepts an argument to determine which test score to return
    //Notice that this isn't the true testscore, but it has been modified by the gradeboost field.
    //If the user had public access to the true testscore, it wouldn't take into account the gradeboost calculation!!
    //This is how a getter can control exactly what a user has access to.
    float get testScore(int test) {
    float testresult = 0;
    if (test = 1) {
           testresult = (grade1+ gradeboost) / 3;
    if (test = 2) {
           testresult = (grade2+ gradeboost) / 3;
    if (test = 3) {
           testresult = (grade3+ gradeboost) / 3;
    return testresult;
    }

  • Help with getting values from request. Very Strange!!

    Hello,
    My very strange problem is the following.
    I have created three dynamic list boxes. When the user select
    the first list box, the second becomes populated with stuff
    from a database. The third becomes populated when the second
    is selected. Now, I have used hidden values in order for
    me to get the selected value from the first listbox. The
    following code is my first listbox:
    <SELECT NAME="resources" onChange="document.hiddenform.hiddenObject.value = this.option [this.selectedIndex].value; document.hiddenform.submit();">
    <OPTION VALUE =""> Resource</OPTION>
    <OPTION VALUE ="soil"> Soil </OPTION>
    <OPTION VALUE ="water"> Water </OPTION>
    <OPTION VALUE ="air"> Air </OPTION>
    <OPTION VALUE ="plants"> Plants </OPTION>
    <OPTION VALUE ="animals"> Animals </OPTION>
    </SELECT>
    I use the getRequest method to get the value of hiddenObject.
    At this time I am able to get the value of hiddenObject to populate
    the second list box.
    But, when the user selects an item from the second list box
    and the second form is also submitted,
    I lose the value of hiddenObject. Why is this??
    The code to populate my second listbox is the following:
    <SELECT NAME ="res_categories" onChange="document.hiddenform2.hiddenObject2.value = this.options[this.selectedIndex].value; document.hiddenform2.submit(); ">
    <OPTION VALUE ="" SELECTED> Category</OPTION>
    Here I access a result set to populate the list box.
    Please help!!

    Form parameters are request-scoped, hence the request.getParameter("hiddenObject"); call after the submission of the second form returns a null value because the hiddenObject parameter does not exist within the second request.
    A solution would be to add a hiddenObject field to your second form and alter the onChange event for res_categories to read
    document.hiddenform2.hiddenObject.value=document.1stvisibleformname.resources.option[document.1stvisibleformname.resources.selectedIndex].value;
    document.hiddenform2.hiddenObject2.value = this.options[this.selectedIndex].value;
    document.hiddenform2.submit();You will then come across a similar problem with your third drop-down if indeed you need to resubmit the form...
    A far better approach would be to create a session scoped bean, and a servlet to handle these requests. Then when the servlet is called, it would set the value of the bean property, thus making it available for this request, and all subsequent requests within the current session. This approach would eliminate the need for the clunky javascript, making your application far more stable.

  • Need help with getting variable from static

    Hello,
    What I am building is an application that prompts for username/password before it shows the main screen. Once they have successfully logged in, I need to assign the username that they used, in order to use it for a button event if the make any updates.
    Here is the code that I have tried to use.
    public String username;
    ///This set's the public variable username
    public void setUserName(String UserName){
    username = UserName;
    /////////////////Here is where they login, and assign the name to setUsername
    public static void main(String args[]) throws SQLException {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    JFrame frame = new JFrame();
    JTextField userName = new JTextField();
    JTextField passWord = new JTextField();
    Object[] options = {"OK","CANCEL"};
    Object[] msg = {"UserName:", userName, "Password:", passWord};
    final JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION){};
    JDialog dialog = op.createDialog(frame, "Please Login");
    dialog.show();
    int result = JOptionPane.OK_OPTION;
    try {
    result = ((Integer)op.getValue()).intValue();
    }catch(Exception uninitializedValue){}
    if(result == JOptionPane.OK_OPTION) {
    String userID = userName.getText();
    String passID = passWord.getText();
    Main myMain = new Main();
    myMain.setUserName(userID);
    if(!userID.equals("") && !passID.equals("")) {
    new Main().setVisible(true);
    }else {
    // user cancelled
    ////here is the button event that also will need the username
    private void selButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Connection conn = null;
    Statement stmt3 = null;
    Statement stmt4 = null;
    ResultSet rset3 = null;
    ResultSet rset4 = null;
    String usernum = null;
    String xemu = null;
    String loc = null;
    String ustat = null;
    String manager = null;
    String dept = null;
    String Add = "Add";
    String Update = "Update";
    String groupID = "9999";
    Vector columnNames = new Vector();
    Vector data = new Vector();
    String Manager_info[] = {"managerindex", "managers", "managername"};
    String Account_info[] = {"acctypeindex", "acctype", "acctypedesc"};
    String Group_info[] = {"groupnum", "groups", "groupcode"};
    String System_info[] = {"systemindex", "systems", "systemname"};
    String Dept_info[] = {"departindex", "departments", "departname"};
    String Xemu_info[] = {"xemuindex", "xemulator", "xemudesc"};
    String Location_info[] = {"locindex", "location", "locdesc"};
    String Ustatus_info[] = {"ustatusindex", "userstatus", "ustatusdesc"};
    Date myDate = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
    String today = formatter.format(myDate);
    System.out.println(username);
    I am trying to set the public username variable to what the person enters, however since I am creating a seperate instance of it, I don't believe it will work. Any help would be very much appreciated.
    Thanks.
    Josh

    I am developing in Netbeans. If I try to remove the static keyword from main(), netbeans canno't find a main to run. I have created the User class.
    Here is the main again to show what I have done.
    public static void main(String args[]) throws SQLException {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    User user = new User();
    JFrame frame = new JFrame();
    JTextField userName = new JTextField();
    JTextField passWord = new JTextField();
    Object[] options = {"OK","CANCEL"};
    Object[] msg = {"UserName:", userName, "Password:", passWord};
    final JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION){};
    JDialog dialog = op.createDialog(frame, "Please Login");
    dialog.show();
    int result = JOptionPane.OK_OPTION;
    try {
    result = ((Integer)op.getValue()).intValue();
    }catch(Exception uninitializedValue){}
    if(result == JOptionPane.OK_OPTION) {
    String userID = userName.getText();
    String passID = passWord.getText();
    user.setName(userID);
    user.setPassword(passID);
    if(!userID.equals("") && !passID.equals("")) {
    //Auth.setUserName(userID);
    //Auth.setPassword(passID);
    new Main().setVisible(true);
    }else {
    // user cancelled
    This set's the variables
    Here is the beginning of the evt that I am using to try and get the data.
    private void selButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Connection conn = null;
    Statement stmt3 = null;
    Statement stmt4 = null;
    ResultSet rset3 = null;
    ResultSet rset4 = null;
    String usernum = null;
    String xemu = null;
    String loc = null;
    String ustat = null;
    String manager = null;
    String dept = null;
    String Add = "Add";
    String Update = "Update";
    String groupID = "9999";
    Vector columnNames = new Vector();
    Vector data = new Vector();
    User user = new User();
    String User = user.getName();
    System.out.println(User);
    String Manager_info[] = {"managerindex", "managers", "managername"};
    String Account_info[] = {"acctypeindex", "acctype", "acctypedesc"};
    String Group_info[] = {"groupnum", "groups", "groupcode"};
    String System_info[] = {"systemindex", "systems", "systemname"};
    String Dept_info[] = {"departindex", "departments", "departname"};
    String Xemu_info[] = {"xemuindex", "xemulator", "xemudesc"};
    String Location_info[] = {"locindex", "location", "locdesc"};
    String Ustatus_info[] = {"ustatusindex", "userstatus", "ustatusdesc"};
    Date myDate = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
    String today = formatter.format(myDate);
    String [] str = {
    "EmpID", "Account", "System", "Type", "Status", "UserID", "Group"
    This gives me a null on the println, how can I get the data that was entered in main()?
    Thanks,
    Josh

  • Help with getting input from the console

    Hey Experts , wish you are good ? .... i have a problem and wish you figure it out for me , well tell me how can store the input values in a text file and pass the file from the command line ? , i have compiled the program so well , but i could not using text file , thats the code :
    import java.util.Scanner ;
    class TestScanner {
    public static void main (String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter an interger : ");
    int intValue = scanner.nextInt();
    System.out.println(" You entered an interger " + intValue);
    System.out.print("Enter a double value : ");
    double doubleValue = scanner.nextDouble();
    System.out.println("You entered a double value " + doubleValue);
    System.out.print("Enter a string without space: ");
    String string = scanner.next();
    System.out.println("You entered the string " + string);
    }and i created a file with value like that :
    file name is input
    5
    23.55
    Java
    true
    i just want to know the correct order to compile it .
    thanks in advance

    The Java Tutorials: [_Basic I/O_|http://java.sun.com/docs/books/tutorial/essential/io/index.html]
    db

  • Help with getting links from HTML page

    Hello all. I found the sun tutorial for getting HREF values from a tags in an HTML document at <http://java.sun.com/developer/TechTips/1999/tt0923.html>. My question now is how would a person add the ability to get the text of the link to this code?
    For example:
    Provided the HTML code:<a href="link.html">example</a>Returned is: href=link.html text=example

    I think the TechTip you've linked too is quite old (1999). I would write a simple SAXParser that uses TagSoup (http://www.ccil.org/~cowan/XML/tagsoup/) as its input source. In your handler, simply set a flag and reset a StringBuffer to collect the contents of any <a>...</a> element. Simplified:
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if ("a".equals(localName)) {
                currentHref = attributes.getValue("href");
                if (currentHref != null && currentHref.length() > 0) {
                    inLink = true;
                    //reset the string buffer
                    buffer.setLength(0);
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (inLink) buf.append(ch, start, length);
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if ("a".equals(localName) && inLink) {
                inLink = false;
                //add link to the stack
                links.add(new Link(currentHref, buffer.toString()));
        }Completely untested, of course... .Good luck...

  • Need help with custom event from Main class to an unrelated class.

    Hey guys,
    I'm new to Flash and not great with OOP.  I've made it pretty far with google and lurking, but I've been pulling my hair out on this problem for a day and everything I try throws an error or simply doesn't hit the listener.
    I'm trying to get my Main class to send a custom event to an unrelated class called BigIcon.  The rest of the code works fine, it's just the addEventListener and dispatchEvent that isn't working.
    I've put in the relevant code in below.  Let me know if anything else is needed to troubleshoot.  Thank you!
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                placeIcons();
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 4; i++)
                    for (j = 0; j < 5; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i,j);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
            function twitchUp(e:Event)
                this.y +=  10;

    Ned Murphy wrote:
    You should be getting an error for the Main.as class due to missing a line to import the Event class...
    import flash.events.Event;
    My apologies, I should attempt to compile my example code before I ask for help...
    Alright, this compiles, gives me no errors, shows my 'book' and 'flowers' icons perfectly when ran, and prints 'addEventListener' to the output window as expected.  I get no errors when I press the button, 'dispatchEvent' is output (good), but the 'twitchUp' function is never called and 'EventTriggered' is never output. 
    How do I get the 'twitchUp' event to trigger?
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import flash.events.*;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            var iconString_array:Array = new Array(2);
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                buildStringArray();
                placeIcons();
            function buildStringArray():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    iconString_array[i] = new Array(3);
                    for (j = 0; j < 3; j++)
                        if (Math.random() > .5)
                            //'flowers' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "flowers";
                        else
                            //'book' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "book";
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    for (j = 0; j < 3; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i*50,j*50);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
                trace("dispatchEvent");
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.*;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
                trace("addEventListener");
            function twitchUp(e:Event)
                this.y +=  10;
                trace("EventTriggered");
    Output:
    [SWF] Untitled-1.swf - 40457 bytes after decompression
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    dispatchEvent
    [UnloadSWF] Untitled-1.swf
    Test Movie terminated.

  • Need a little help with a Jbutton not working out the way I planned

    The following code is to fulfill an assignment I am working on. The problem I am having is with the btnCalc. For some reason when the button is used, the results I get is from another button. I think the variables are set right for the program to function properly but I am really hung up on this. Do anyone have any suggestions?
    import java.awt.*;                     //Contains classes for creating GUI
    import java.awt.event.*;                //For listener events
    import javax.swing.*;                     // Imports the Main Swing Package
    import javax.swing.event.*;
    import javax.swing.text.*;           // Positions text box
    import java.text.NumberFormat;          // For number format such as currency
    import java.text.*;                     // Imports the Main Text Package
    import java.util.*;                     // Utility Package
    public class MPC extends JFrame implements ActionListener           //Creates Class for MPC
    //double dblLoanAmount, dblInterestRate, dblMonthlyPayment;
    TextField txtTotalMort;
         //JButton fixRates = new JButton("Choose Fixed Rates");
         JLabel lblTotalMort = new JLabel("How much is the loan?"); // Label for dblLoanAmount amount
         JTextField txtYears = new JTextField(10);
         JLabel lblPayment = new JLabel("Your monthly payment is "); // Label for Payment
         JTextField txtPayment = new JTextField(10);
         JLabel lblYears = new JLabel("How many years?");
                             // add(lblYears);
                   JTextField txtYearsInput = new JTextField(10);
                             //a dd(txtYears);
         JLabel lblInterestRate = new JLabel("What is the interest rate?");
                             //add(lblInterestRate);
                   JTextField txtInterestRate = new JTextField(10);
                             //add(txtInterestRate);
         //JLabel lblPayment = new JLabel("Your monthly payment is:");
                             //add(lblPayment);
                   //JTextField txtPayment = new JTextField(10);
                             //txtPayment.setEditable(false);
                                  //add(txtPayment);
         JButton btnCalc = new JButton("Calculate");
                             //add(btnCalc);
                             //btnCalc.addActionListener(this);
    JButton year7InterestRateBtn = new JButton("7 years at 5.35%");     // Mortgage Term and Interest Rate
    JButton year15InterestRateBtn = new JButton("15 years at 5.50%");
    JButton year30InterestRateBtn = new JButton("30 years at 5.75%");
    JButton reset = new JButton("Clear All");
    JTextArea boxSpace = new JTextArea(100,200);          // Morgtage table size
    JScrollPane scroll = new JScrollPane(boxSpace);     // ScrollPane
              public MPC()     // Method
         super("MPC");     // Frame Title
              JMenuBar mb = new JMenuBar();     // Menu Bar
    setJMenuBar(mb);
                        setSize(325, 500);          // Frame Size
                        JPanel pane = new JPanel();
                        pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); //Grid box configuration
                        Container grid = getContentPane();
                        grid.setLayout(new GridLayout(8,2,8,8));     // Grid Layout
                        pane.add(grid);                                        // Adds grid
                        pane.add(scroll);                                   // Adds scrollPane
                   grid.setBackground(Color.white);
                        Setting color of text and backgrounds
                   txtYears.setBackground(Color.white);
              txtYears.setForeground(Color.black);
                   txtYears.setFont(new Font("Arial", Font.PLAIN, 10));
                        txtPayment.setBackground(Color.white);
                   txtPayment.setForeground(Color.black);
              txtPayment.setFont(new Font("Arial", Font.PLAIN, 10));
                   boxSpace.setBackground(Color.white);
                   boxSpace.setForeground(Color.black);
                   boxSpace.setFont(new Font("Arial", Font.PLAIN, 10));
              grid.add(lblYears);
              grid.add(txtYearsInput);
              grid.add(lblInterestRate);
              grid.add (txtInterestRate);
              grid.add(lblTotalMort);          // Adds the Mortgage Amount Label
              grid.add(txtYears);               // Adds the Mortgage Amount Text Field
              grid.add(lblPayment);           // Adds the Payment Label
              grid.add(txtPayment);           // Adds the Monthly Payment Text Field
                   txtPayment.setEditable(false);          // Disables editing in this Text Field
              grid.add(btnCalc);
         grid.add(year7InterestRateBtn);               // Adds 1st Loan and Rate Button
              grid.add(year15InterestRateBtn);          // Adds 2nd Loan and Rate Button
              grid.add(year30InterestRateBtn);          // Adds the Exit Button
              grid.add(reset);                               // Adds the New Calc Button
              setContentPane(pane);                          // Enables the Content Pane
              setVisible(true);                               // Sets JPanel to be Visable
              reset.addActionListener(this);                          // Adds Action Listener to the New Calc Button
              txtYearsInput.addActionListener(this);
              txtInterestRate.addActionListener(this);
              btnCalc.addActionListener(this);
         year7InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
              year15InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
              year30InterestRateBtn.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
              txtYears.addActionListener(this);                              // Adds Action Listener to the Mortgage Amount Text Field
              txtPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
              public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
         Object command = e.getSource(); // Enables command to get data
         int intYears = 0;          // Declares intYears
                   double dblLoanAmount, dblInterestRate, interestRate, intRate;
         if (command == year7InterestRateBtn)                                   // Activates the 1st Loan Button
    intYears = 0;                                        // Sets 1st value of Array
         if (command == year15InterestRateBtn)                                   // Activates the 2nd Loan Button
         intYears = 1;                                        // Sets 2nd value of Array
              if (command == year30InterestRateBtn)                                   // Activates the 3rd Loan Button
                   intYears = 2;                                        // Sets 3rd value of Array
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    dblLoanAmount = 0;                                   // Declares and Initializes dblLoanAmount
                   dblInterestRate = 0;                                        // Declares and Initializes dblInterestRate
              double [][] dblTrmLoanRate = {{7, 5.35}, {15, 5.50}, {30, 5.75},};           // Array Data for Calculation
    try
    dblLoanAmount = Double.parseDouble(txtYears.getText()); // Gets user input from txtYears Text Field
    catch (NumberFormatException nfe)                          // Checks for correct user input
                             JOptionPane.showMessageDialog(null, "You must enter a valid number.", "MPC", JOptionPane.INFORMATION_MESSAGE);
    return;
              interestRate = dblTrmLoanRate [intYears][1];
                   //dblInterestRate=interestRate;
                   intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate
         double intYearsMonths = dblTrmLoanRate [intYears] [0];                    // Calculates Loan Term in Months
    int months = (int)intYearsMonths * 12;                          // Devides by months
    double interestRateMonthly = (intRate / 12); // Devides Rate
              double payment = dblLoanAmount * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculates monthly payment
         double dblRmnLoan = dblLoanAmount;                              //Left over balance
         double txtPaymentInterest = 0;                                   // Payment
         double txtPaymentPrincipal = 0;                                   // Payment of principal
    NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US); // Curreny format
         txtPayment.setText(currency.format(payment));
              boxSpace.setText("Month\tPrincipal\tInterest\tBalance Left\n");
              for (;months > 0 ; months -- )
              txtPaymentInterest = (dblRmnLoan * intRate);
                        txtPaymentPrincipal = (payment - txtPaymentInterest);          // Calculates monthly payment
                   dblRmnLoan = (dblRmnLoan - txtPaymentPrincipal);
                        boxSpace.setCaret (new DefaultCaret());                    // Scroll position
                        boxSpace.append(String.valueOf(months) + "\t" +               // Table data
                        currency.format(txtPaymentPrincipal) + "\t" +
                   currency.format(txtPaymentInterest) + "\t" +
                   currency.format(dblRmnLoan) + "\n");
    if(command == reset)
                             Clears fields
                        txtYearsInput.setText(null);
                        txtInterestRate.setText(null);
              txtYears.setText(null);
                        txtPayment.setText(null);
         boxSpace.setText(null);
                        public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
              new MPC();
    }

    This portion to be exact. All the buttons work for me except this one. I need to calculate user input and also use the fixed data that can be found in the dblTrmLoanRate array. When I choos to use user input instead, the program either crashes or for some reason uses the year7InterestRateBtn instead.
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    I was going to leave out the remed portion but thought it might help you with the navigation. I am sorry I did not use code tags, but I am going to go find out what those are and use them in the future.

  • Need a little Help with my new xfi titanium

    +Need a little Help with my new xfi titanium< A few questions here.
    st question? Im using opt out port on the xfi ti. card and using digital li've on a windows 7 64 bit system,? I would like to know why when i use 5. or 7. and i check to make sure each speakear is working the rear speakers wont sound off but the sr and sl will in replace of the rear speakers. I did a test tone on my sony amp and the speaker are wired correctly becasue the rear speakers and the surrond? left and right sound off when they suppose too. Also when i try to click on? the sl and sr in the sound blaster control panel they dont work but if i click on the rear speakers in the control panel the sl and sr sound off. Do anyone know how i can fix this? So i would like to know why my sl and sr act like rears when they are not?
    2nd question? How do i control the volume from my keyboard or from windows period when using opt out i was able to do so with my on board? sound max audio using spidf? Now i can only control the audio using the sony receiver.
    Thank you for any help..

    /Re: Need a little Help with my new xfi titanium? ?
    ZDragon wrote:
    I'm unsure about the first question. Do you even have a 7. system and receiver? If you just have 5., you should be able to remap the audio in the THX console.
    I do have a sony 7. reciever str de-995 its an older one but its only for my cpu. At first i didnt even have THX installed because it didnt come with the driver package for some reason until i downloaded the daniel_k support drivers and installed it. But it doesnt help in anyway.
    I have checked every where regarding the first question and alot of people are having problems getting sound out of there rear channels and the sound being re-mapped to the surround right and the surround left as if there rear left and rear right.
    I read somewhere that the daniel_k support drivers would fix this but it didnt for me and many others.
    For the second question i assumed it would be becasue of the spidf pass through and that my onboard sound card was inferior to the xfi titaniums. But i wasnt sure and i was hopeing that someone would have a solution for that problem because i miss controlling the volume with my keyboard.

  • Need a little help with syncing my iPod.

    I got a new macbook pro for cristmas and a few cds. After i tried to sync my ipod to itunes i put a symbol next to each song that i got from other cds saying that they were downloading but they werent. Also the cds i downloaded to my ipod for the first time didnt appear at all. Need help.

    /Re: Need a little Help with my new xfi titanium? ?
    ZDragon wrote:
    I'm unsure about the first question. Do you even have a 7. system and receiver? If you just have 5., you should be able to remap the audio in the THX console.
    I do have a sony 7. reciever str de-995 its an older one but its only for my cpu. At first i didnt even have THX installed because it didnt come with the driver package for some reason until i downloaded the daniel_k support drivers and installed it. But it doesnt help in anyway.
    I have checked every where regarding the first question and alot of people are having problems getting sound out of there rear channels and the sound being re-mapped to the surround right and the surround left as if there rear left and rear right.
    I read somewhere that the daniel_k support drivers would fix this but it didnt for me and many others.
    For the second question i assumed it would be becasue of the spidf pass through and that my onboard sound card was inferior to the xfi titaniums. But i wasnt sure and i was hopeing that someone would have a solution for that problem because i miss controlling the volume with my keyboard.

  • How can i get data from another database SQL Server use database link from

    I have a database link from Oracle connect to SQL Server database with user cdit connect default database NorthWind.How can I get data from another database(this database in this SQL Server use this database link)?

    hi,
    u should see following documentation:
    Oracle9i Heterogeneous Connectivity Administrator's Guide
    Release 1 (9.0.1)
    Part Number A88789_01
    in it u just go to chapter no. 4 (using the gateway),,u'll find ur answer there.
    regards
    umar

  • Getting a variable value from another class

    Is there any way to get the value of a variable from another class? I have a file that calls another that does some checking then gives a true or false. The place the checking is done is inside an ActionListener I want to use that value in the file that calls the second. Any help would be great.

    in 'another class', implement a method,
    public boolean isCheckedOutOK( Object obj )
    do the comparison in that method (use a suitable argument)

  • Best way To get data from another application using NDDE lbrary

    My vb.net application gets data from another application using NDDE Library. I got stocks prices (open,high,low,close,volume,change......(about 15 records for each stock)) (about 200 stocks) . I don't know if there is a problem in my code.
    This is my code:
    l : is the list of stocks.
    This Sub connects to server and requests the data :
    Public Shared Sub GetQuotes()
    Try
    client1 = New DdeClient(server, topic)
    client1.Connect()
    For i As Integer = 0 To l.Count - 1
    client1.StartAdvise("QO." & l(i).t & ".TAD$last", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$open", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$high", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$low", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$pclose", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$volume", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$date", 1, True, 60000)
    client1.StartAdvise("QO." & l(i).t & ".TAD$time", 1, True, 60000)
    Next
    Catch ex As Exception
    MsgBox(ex.Message)
    End Try
    End Sub
    and then I get the data from Client_advise sub (called each time a value changed )and fill the list. What I know is that client advise gets only one record for single stock each time is called..
    Example: for stock AAPL. 1st time enters client_Advise I get open price for AAPL, 2nd time I get high price for AAPL,3rd time I get low price..... and I update the value in the List (l)
    This the client_Advise Sub:
    Private Shared Sub client1_Advise(ByVal sender As Object, ByVal e As NDde.Client.DdeAdviseEventArgs) Handles client1.Advise
    For q As Integer = 0 To l.Count - 1
    If l(q).t = w(1) Then
    Dim item() As String = e.Item.Split("$")
    If l(q).Open = "#" Then
    l(q).Open = "0"
    End If
    If l(q).hi = "#" Then
    l(q).hi = "0"
    End If
    If l(q).lo = "#" Then
    l(q).lo = "0"
    End If
    If l(q).Close = "" Or l(q).Close = "#" Then
    l(q).Close = "0"
    End If
    If l(q).pclose = "#" Then
    l(q).pclose = "0"
    End If
    If item(1) = "open" Then
    l(q).Open = Format(Val(e.Text), "0.00")
    ElseIf item(1) = "last" Then
    l(q).Close = Format(Val(e.Text), "0.00")
    ElseIf item(1) = "high" Then
    l(q).hi = Format(Val(e.Text), "0.00")
    ElseIf item(1) = "volume" Then
    l(q).Volume = Val(e.Text)
    ElseIf item(1) = "low" Then
    l(q).lo = Format(Val(e.Text), "0.00")
    ElseIf item(1) = "pclose" Then
    l(q).pclose = Format(Val(e.Text), "0.00")
    If l(q).pclose <> "" And l(q).pclose <> "#" And l(q).Close <> "" And l(q).Close <> "#" Then
    l(q).c = Format(l(q).Close - l(q).pclose, "0.00")
    l(q).cp = Format(((l(q).Close - l(q).pclose) / l(q).pclose) * 100, "0.00")
    End If
    l(q).flag1 = 2
    ElseIf item(1) = "date" Then
    l(q).Date1 = e.Text
    ElseIf item(1) = "time" Then
    l(q).Time = e.Text
    End If
    Exit For
    End If
    Next
    End Sub
    Am I doing something wrong which inreases CPU usage to 80 or 90 % ?
    Thanks in advance.

    Hi MikeHammadi,
    According to your description, you'd like to get data from another app using NDDE library.
    When using the NDDE library, the CPU usage is high. As the NDDE library is third-party library, it is not supported here. I suggest you checking if the problem is caused by the NDDE library.
    If you'd like to get data from another app. I suggest you could save the data in the dataBase, and then read it in another application if necessary.
    If you have any other concern regarding this issue, please feel free to let me know.
    Best regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • Logic Pro 9.1.0 32 bit Crashes on all projects created on Logic Pro 9.0.2

    Hi, Everytime I open a project on Logic 9.1.0 (32 bit mode), which was created on any previous version of logic (ranging from 8.0 to 9.0.2), it opens properly, but crashes after about 5 seconds. I try opening the projects on the copy of logic 9.0.2 t

  • Crystal Reports 2008 connecting to R/3

    I have a general question for Crystal Reports 2008 for use with R/3. Crystal Reports 2008 with SAP/R3 Enterprise 4.7 I installed a trial version of Crystal Reports 2008 and connected it to the R/3 instance using a oracle id which has admin rights so

  • How to use when-validate-item in the form personalization?

    Dear all, I want to use when-validate-item trigger in the form personalization on a specific item. while in the same time the when-validate-item is not included in the trigger event list. Please advice & Thanks in advance Ashraf Ashour

  • Istheir any way by which i can MODIFY the Primary Set of Books option inSOB

    Hi, Is thier any way , to change the primary/reporting set of books option , which is enabled in MULTIPLE REPORTING CURRENCY TAB in "Set of Books" winow in Financial applications. Once defined , I was not able to change the option. Rgds

  • Error in Testing SQL Query VO

    Hi, I have a a VO based on a Database Table 'XXCZ_TEST_V'(View in APPS schema) The table(view) present in APPS schema is based on several base Tables in XXCZ schema. When I test the Query in the Wizard it shows following error int he "Detailed Screen