Facing problem inside the implementation of ActionListener

Hi, I don't understand what the problem is. Please go through the following code. The explanation of the problem is documented.
Any kind of help is appreciated.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
* Class Test is intended for receiving a String input from the user and
* manipulating the input string later in some other methods. So the input
* string has to be stored for later use.
* Whenever an action takes place in JTextField or JButton (OK button) component,
* the corresponding ActionListener's actionPerformed() method assigns the
* user input to 'userInput' referene variable. This was assured when I placed
*              JOptionPane.showMessageDialog(frame, userInput);
* right after the assignment statement. But when I cut and pasted the above
* statement right after the getUserInput() method call (in constructor's body)
* it showed null string.
* WHY & HOW this happens?
* I could have implemented this application with the help of JOptionPane's
* showInputDialog() method. But I just want to know what the problem is if
* I have tried in this way.
public class Test {
     * String that the user types
    private String userInput;
     * Text field that contains the user input.
    private JTextField inputTextField;
     * Frame that contains all other components
    private JFrame frame;
    public Test() {
        prepareFrame();
        getUserInput();
        // shows null, why?????
        JOptionPane.showMessageDialog(frame, userInput);
        // some other methods goes here that uses the input string....
        // methodA();
        // methodB();
     * Creates the frame and sets some of its properties.
    private void prepareFrame() {
        frame = new JFrame("Experiment with ActionListener");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 300);
        frame.setVisible(false);
     * Receives user input and stores the reference to user input in userInput.
    private void getUserInput() {
        // Create sub-components
        JLabel promptLabel = new JLabel("Enter a string: ");
        inputTextField = new JTextField(20);
        JButton okButton = new JButton("OK");
        JButton cancelButton = new JButton("Cancel");
        // Add listeners
        inputTextField.addActionListener(new TextFieldHandler());
        okButton.addActionListener(new OkButtonHandler());
        cancelButton.addActionListener(new CancelButtonHandler());
        // Create a panel to contain the sub-components
        JPanel panel = new JPanel();
        // Add the sub-components to the panel
        panel.add(promptLabel);
        panel.add(inputTextField);
        panel.add(okButton);
        panel.add(cancelButton);
        frame.add(panel, BorderLayout.NORTH);
        frame.validate();
        frame.setVisible(true);
     * Event handler for text field that contains user input.
    private class TextFieldHandler
            implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            userInput = event.getActionCommand();
            // works fine if the user input is shown here.
            // JOptionPane.showMessageDialog(frame, userInput);
     * Event handler for OK button
    private class OkButtonHandler
            implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            userInput = inputTextField.getText();
            // works fine if the user input is shown here.
            // JOptionPane.showMessageDialog(frame, userInput);
     * Event handler for Cancel button
    private class CancelButtonHandler
            implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
    public static void main(String[] args) {
        new Test();
}

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
public class T {
    private String userInput;
    private JTextField inputTextField;
    private JFrame frame;
    public T() {
        prepareFrame();
        getUserInput();
        // shows null, why?????
        // userInput is null because it has not been given a value
        // you can give it a value in the declaration as a member
        // variable above or here in your class constructor
        System.out.println("userInput = " + userInput);
        JOptionPane.showMessageDialog(frame, userInput);
        // some other methods goes here that uses the input string....
        // methodA();
        // methodB();
    private void prepareFrame() {
        frame = new JFrame("Experiment with ActionListener");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 300);
        frame.setVisible(false);
    private void getUserInput() {
        // Create sub-components
        JLabel promptLabel = new JLabel("Enter a string: ");
        inputTextField = new JTextField(20);
        JButton okButton = new JButton("OK");
        JButton cancelButton = new JButton("Cancel");
        // Add listeners
        inputTextField.addActionListener(new TextFieldHandler());
        okButton.addActionListener(new OkButtonHandler());
        cancelButton.addActionListener(new CancelButtonHandler());
        // Create a panel to contain the sub-components
        JPanel panel = new JPanel();
        // Add the sub-components to the panel
        panel.add(promptLabel);
        panel.add(inputTextField);
        panel.add(okButton);
        panel.add(cancelButton);
        frame.add(panel, BorderLayout.NORTH);
        frame.validate();
        frame.setVisible(true);
    private class TextFieldHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            // userInput is given a value here so it is no longer null
            userInput = event.getActionCommand();
            // works fine if the user input is shown here.
            System.out.println("userInput = " + userInput);
            JOptionPane.showMessageDialog(frame, userInput);
    private class OkButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            // userInput is given a value here so it is no longer null
            userInput = inputTextField.getText();
            // works fine if the user input is shown here.
            System.out.println("userInput = " + userInput);
            JOptionPane.showMessageDialog(frame, userInput);
    private class CancelButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
    public static void main(String[] args) {
        new T();
}

Similar Messages

  • Facing problem with the code for sending an .xls attachment via email, a field value contains leading zeros but excel automatically removes these from display i.e. (00444 with be displayed as 444).kindly guide .

    Facing problem with the code for sending an .xls attachment via email, a field value contains leading zeros but excel automatically removes these from display i.e. (00444 with be displayed as 444).kindly guide .

    Hi Chhayank,
    the problem is not the exported xls. If you have a look inside with Notepad or something like that, you will see that your leading zeros are exported correct.Excel-settings occurs this problem, it is all about how to open the document. If you use the import-assistant you will have no problems because there are options available how to handle the different columns.
    Another solution might be to get familiar with ABAP2XLS-Project. I got in my mind, that there is a method implemented, that will help you solving this problem. But that is not a five minute job
    ~Florian

  • I have purchased my iPhone 4S from USA. Its a Factory unlocked phone. I am facing problem with the hardware. Is there any support that apple provides to send the phone from India to USA to get it replaced? Also if there is any travelers Policy?

    I have purchased my iPhone 4S from USA. Its a Factory unlocked phone. I am facing problem with the hardware. Is there any support that apple provides to send the phone from India to USA to get it replaced? Also if there is any travelers Policy?

    No and no.

  • TS1559 my wifi is grayed out... No one can fixed it...there is a problem with hardware. IC problem inside the phone. Apple have any facility like service after sales etc. Multi billion company but no priority for customers ?

    my wifi is grayed out... No one can fixed it...there is a problem with hardware. IC problem inside the phone. Apple have any facility like service after sales etc. Multi billion company but no priority for customers ? Just try to look at google search you can find lot of people who have same problem with iphone 4s. It is surly manufacturing default. Is that apple reputation lounching New virsion Iphone with diffective hardware.

    Plz dont give me idea setting>reset>reset network configration .... I already did it..... give me proper solution... who can replace default hardware from my iphone?????????????????????

  • How can i use index in select query.. facing problem with the select query.

    Hi Friends,
    I am facing a serious problem in one of the select query. It is taking a lot of time to fetch data in Production Scenario.
    Here is the query:
      SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelat LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelatrprctr
        WHERE rldnr  = c_telstra_accounting
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          And rzzlstar in r_lstar                            
          AND rpmax  = c_max_period.
    There are 5 indices present for Table ZTFTELAT.
    Indices of ZTFTELAT:
      Name   Description                                               
      0        Primary key( RCLNT,RLDNR,RRCTY,RVERS,RYEAR,ROBJNR,SOBJNR,RTCUR,RUNIT,DRCRK,RPMAX)                                          
      005    Profit (RCLNT,RPRCTR)
      1        Ledger, company code, account (RLDNR,RBUKRS, RACCT)                                
      2        Ledger, company code, cost center (RLDNR, RBUKRS,RCNTR)                           
      3        Account, cost center (RACCT,RCNTR)                                        
      4        RCLNT/RLDNR/RRCTY/RVERS/RYEAR/RZZAUFNR                        
      Z01    Activity Type, Account (RZZLSTAR,RACCT)                                        
      Z02    RYEAR-RBUKRS- RZZZBER-RLDNR       
    Can anyone help me out why it is taking so much time and how we can reduce it ? and also tell me if I want to use index number 1 then how can I use?
    Thanks in advance.

    Hi Shiva,
    I am using two more select queries with the same manner ....
    here are the other two select query :
    ***************1************************
    SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelpt LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelptrprctr
        WHERE rldnr  = c_telstra_projects
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          and rzzlstar in r_lstar             
          AND rpmax  = c_max_period.
    and the second one is
    *************************2************************
      SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelnt LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelntrprctr
        WHERE rldnr  = c_telstra_networks
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          and rzzlstar in r_lstar                              
          AND rpmax  = c_max_period.
    for both the above table program is taking very less time .... although both the table used in above queries have similar amount of data. And i can not remove the APPENDING CORRESPONDING. because i have to append the data after fetching from the tables.  if i will not use it will delete all the data fetched earlier.
    Thanks on advanced......
    Sourabh

  • Facing Problems with the Installation of Dreamweaver CS3

    Hello,
    I am facing some problem while installing Dreamweaver CS3 ..
    tried number of times but to no avail.. every time the same error
    message pops up "You can only install one product at a time. Please
    complete the other installation before attempting to install Adobe
    Dreamweaver CS3"
    I am pretty sure I am not installing any other Adobe product
    in parallel. I already have Adobe Flash CS3 on my system and its
    working pretty fine for me but I am not able to get around with
    Dreamweaver. Please let me know what I need to do to run this
    software on my system successfully.

    Adobe Install Problems 800-642-3623

  • I am using iphone4s with version 7.1.2 version, I am Facing Problems with the sound system

    I am using iphone 4s with version 7.1.2
    The problem i am facing with my phone is sound system not working for apps and music

    Hi manu1982,
    If you are having issues with sound from your iPhone I would suggest troubleshooting using the steps in this article -
    iPhone: No sound or distorted sound from speaker
    http://support.apple.com/kb/ts5180
    Thanks for using Apple Support Communities.
    Best,
    Brett L

  • I am Facing Problem with the WSDl File which is in the local SAP Server

    Hi All,
               Can you please give me solution of my Problem. Here i am working with the WSDl which is create from the SAP Local System. Now i want to take the wsdl file URL from the local server to my system.Here i Struck. can you please help me .
    thanks
    Siva...

    Here i Followed  Url &sap-user=XXX&sap-password=YYY to the WSDL-URL with XXX and YYY being your username and password and you will be authenticated.
    Later i Struck. Actual my requirement is I have two views i want to take a value from the first view and then return value displayed in the second view. All input/output parameters are the taken from the WSDL file. Can you please Help me.

  • Upgrading from weblogic 8.1 to 10gr3 facing problem with the Building

    Internal compiler error
    java.lang.NullPointerException at org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding.binarySearch(ReferenceBinding.java:108)
         at org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding.getMethods(ParameterizedTypeBinding.java:542)
         at org.eclipse.jdt.internal.compiler.lookup.Scope.findMethod(Scope.java:1069)
         at org.eclipse.jdt.internal.compiler.lookup.Scope.getMethod(Scope.java:2072)
         at org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:428)
         at org.eclipse.jdt.internal.compiler.ast.CastExpression.resolveType(CastExpression.java:460)
         at org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.resolve(LocalDeclaration.java:187)
         at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:428)
         at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:195)
         at org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:402)
         at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1084)
         at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1165)
         at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:366)
         at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:102)
         at org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:626)
         at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:392)
         at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:362)
         at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.compile(BatchImageBuilder.java:174)
         at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:299)
         at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:59)
         at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:269)
         at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:177)
         at com.bea.wstudio.javabuilderx.JavaBuilderX.build(JavaBuilderX.java:66)
         at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:624)
         at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37)
         at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:166)
         at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:197)
         at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:247)
         at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37)
         at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:249)
         at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:302)
         at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:334)
         at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:137)
         at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:235)
         at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
         Utilities/src/com/att/edb/dppco/util     ErrKey.java     line 0     1247660099328     104158
    i am using jdk160_05 as standard VM
    checked with jrockit_160_05 as an Standard VM, when building i am getting the same above error
    can anybody help me on this

    hmm so are you compiling your old 8.1 code in WLS 10.3 and getting the error during compilation?
    I found similar issue reported before:-
    Re: Running Eclipse with Jrockit issues

  • I am facing problems managing the local storage on my iPad !

    SO i wanted to download asphalt 7 on my iPad 16gb with 1.9gb left ! And the size of the game is 1.27gb but when i tried to install it, a message appeared saying that THERE IS NOT ENOUGH LOCAL STORAGE TO DOWNLOAD ASPHALT 7 HEAT !!  so i went toSettings>General>Usage>Storage>Show All Apps n i started deleting apps and  the free space increased to about 2.4gb but still the message appeared !! PLS HELP !!

    The 1.27GB is the download file compressed size (like .zip or .dmg). When the file is installed/uncompressed it can be 2-3 times larger.
    How much space is your Other using? You may be able to reduce.
    How Do I Get Rid Of The “Other” Data Stored On My iPad Or iPhone?
    http://tinyurl.com/85w6xwn
    With an iOS device, the “Other” space in iTunes is used to store things like documents, settings, caches, and a few other important items. If you sync lots of documents to apps like GoodReader, DropCopy, or anything else that reads external files, your storage use can skyrocket. With iOS 5/6, you can see exactly which applications are taking up the most space. Just head to Settings > General > Usage, and tap the button labeled Show All Apps. The storage section will show you the app and how much storage space it is taking up. Tap on the app name to get a description of the additional storage space being used by the app’s documents and data. You can remove the storage-hogging application and all of its data directly from this screen, or manually remove the data by opening the app. Some applications, especially those designed by Apple, will allow you to remove stored data by swiping from left to right on the item to reveal a Delete button.
     Cheers, Tom

  • I am facing problems downloading the Adobe Acrobat trial

    Question;Ihave an HP WINDOWS 7 PAVILION DV6-701.ATEMPTED TO DOWNLOAD A FREE TRIAL ADOBIE ACROBAT AND GOT AN ERROR 6.ANY SUGESTOINS.

    Spenn2 when exactly are you receiving this Error 6?  Is it during the installation process or while downloading?  Is it possible to post a screenshot regarding the error message you are receiving?

  • Facing problem geting the logic...

    Hi..
    I have a table called fare which contains..
    RATE
    PERKM FROMKM TOKM
    0 0 15
    2 16 100
    1 101 300
    Now i want to create a procedure with distance as IN parameter and fareamount as OUT parameter...
    I tired creating logic for it..I succeeded but whenever a user enters new record into the fare table..the below logic doesn't work..
    3 301 400
    PROCEDURE get_fare_amount (
    v_i_ndistance IN route_master.ndistance%TYPE,
    v_o_nfareamount OUT fare_Master
    AS
    CURSOR c1
    IS
    SELECT nrateperkm, nfromkm, ntokm
    FROM fare_master
    WHERE v_i_ndistance >= nfromkm AND nactive = 0;
    nrate NUMBER;
    fromkm NUMBER;
    tokm NUMBER;
    tot NUMBER (2) := 0;
    BEGIN
    FOR temp IN c1
    LOOP
    IF v_i_ndistance >= temp.nfromkm AND v_i_ndistance <= temp.ntokm
    -- if distance between fromkm n tokm..
    THEN
    IF tot = 2
    -- if totat records scanned is 2.. to get rate and km for previous record..
    THEN
    -- For first 100 kms use rate 2 perkm and for remaining kms us 1rs perkm.
    v_o_nfareamount :=
    ( ((v_i_ndistance - tokm) * temp.nrateperkm)
    + (nrate * (tokm))
    ELSE
    v_o_nfareamount := v_i_ndistance * temp.nrateperkm;
    END IF;
    END IF;
    tot := tot + 1; -- To get the record count
    -- To store values of last parsed record to variables
    nrate := temp.nrateperkm;
    tokm := temp.ntokm;
    END LOOP;
    DBMS_OUTPUT.put_line ( 'Total Fare for '
    || v_i_ndistance
    || ' kms :-'
    || ' Rs.'
    || v_o_nfareamount
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
    DBMS_OUTPUT.put_line ('NO DATA FOUND');
    WHEN OTHERS
    THEN
    DBMS_OUTPUT.put_line (SQLERRM);
    END get_fare_amount;

    I found a few things you could look at, but there might be more:
    The OUT parameter is not defined.
    ,v_o_nfareamount  OUT fare_Masterfare_master is a relational table. You probably wanted to specify FARE_MASTER.SOME_COLUMN%TYPE.
    refer to this:
    http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/type_attribute.htm#LNPLS01352
    Also,
    -- One cannot pass an OUT parameter onto another procedure within the same procedure
        DBMS_OUTPUT.put_line ( 'Total Fare for '  || v_i_ndistance
                                                  || ' kms :-'
                                                  || ' Rs.'
                                                  || v_o_nfareamount
                                                  ); If you wish to display your OUT variable, then do so outside the procedure, for example:
    set serveroutput on
    declare
      v_on fare_master.some_column%type;
      v_in route_master.ndistance%type := 10;
    begin
      get_fare_amount(v_in, v_out);
      dbms_output.put_line ( 'Total Fare for '  || v_in
                                                  || ' kms :-'
                                                  || ' Rs.'
                                                  || v_on
    end;
    /

  • Problem in the character conversion

    Hi Guys,
    I am facing problem in the character conversion
    I am posting data from SAP to third party system using XI , by converting whole input message to a String .I am using SOAP adapter to communicate XI to third party system.
    Thirdparty system needs String to be wrapped in CDATA so that it will not choke by looking at the special characters. I did Wrap the output string in CDATA, using ABAP mapping but when I do that XI is converitng  arrow brackets < and >. into &lt and u2018&gtu2019   my assumption is it is double encoding.
    example -
    before map -  <AppSystemInfo>
    after mapping  it is converted as -  <![CDATA[ &ltAppSystemInfo&gt]]>
    Edited by: Vamsi on Jun 17, 2010 10:00 PM
    Edited by: Vamsi on Jun 17, 2010 10:01 PM

    Did you try to see the output?
    bcz if you are trying this in mapping testing it will show you like this as this conversion if for xml, so xml will not do anything wrong with the special characters, so for that special characters will be converted like that.
    Once try to run end to end interface and try to see at receiver side that how data looks like.
    Thanks,
    Hetal

  • Translation problem in the portal screen

    Hi Experts,
    We are facing problem in the portal screen where some texts are displaying in-correct languages.
    Basically all the text should come in Chinese if we login in Chinese language, but it is coming in English
    For e.g. In Follow on Documents screen u2013 Value (filed label) is coming in English instead of Chinese,
    Similarly some Chinese text is wrongly translated.
    Help us how to do the translation or should we need to apply any OSS notes for this?
    Should we need to use translation SOTR_EDIT to do the translation?if then how to do it?
    Regards
    Paul

    Hi,
    What is the SRM version ? Please also check the language setting in your browser.
    For wrong translation, you can correct it in the translation tools like SE63.
    Regards,
    Masa

  • Facing problem in ABAP program "HINCALC0"

    hi all,
               i m facing problem in the  ABAP program "HINCALC0". when i m run this hr program we face problem in processing problem is " No entry in table T512W for key 40 /4OD for time 30.04.2009". plz suggest me hw can i rectify this problem.
    thanks

    Hi,
    As mohan said, you will need to create wage type /4OD. Some of the standand Function/PCR calculating amount and trying to push into /4OD which in not available in the system.
    Regards,
    Karunakar

Maybe you are looking for