Setting label text

Can anybody tell me what is wrong with this code. The following error message is shown at the compile time.
local variable l is accessed from within inner class; needs to be declared final
How can I fix it.
import javax.swing.*;
import java.awt.event.*;
public class ButtonText{
public static void main(String args[]){
JButton b = new JButton("Press Me!");
b.setText("Me Press!");
JLabel l = new JLabel(b.getText());
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
l.setText(e.getActionCommand());
JFrame f = new JFrame();
JPanel p = new JPanel();
p.add(b);
p.add(l);
f.getContentPane().add(p);
f.pack();
f.setVisible(true);
}

You are accessing a local variable, the JLabel I, from an anonymous inner class created in your addActionListener() call. You need to put the word final in your declaration of the JLabel I, as follows:
final  JLabel l = new JLabel(b.getText());I have not tested this, and would need to research why this needs to be done. Probably to prevent the JLabel I from being lost when the method terminates.
You could also probably move your declaration of JLabel I to be an instance variable, and initialized it where you currently do.
� {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Need code example for setting a label text

    Hello,
    Lets say I have a label called testLabel and I would like to put it's text at the doInit() method of my view.
    How do I do that?

    Hi Roy,
    if you want to set the label directly without setting it thru context variable then its part of the dynamic programming of WD. So u can do that only in wdDoModifyView method. Obtain the reference of the label object from the view object and set the text property of it with the desired value.. like below
    public static void wdDoModifyView(IPrivateImageAppView wdThis, IPrivateImageAppView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
        //@@begin wdDoModifyView
        IWDLabel myLabel = (IWDLabel)view.getElement("testLabel");
        myLabel.setText("Hello this is a Label");
        //@@end
    this should solve ur problem...
    regards,
    Shubhadip

  • Setting the text on a label

    Ok, I am new to writing Java programs and I am having trouble setting the text on a label. I think I am following the syntax perfectly but my compiler wont accept it. This used to work for me then all of a sudden it didnt work.
    Here is the code that I was writing. I am trying to set the text of the Label lab1. What am I doing wrong?
    import java.awt.*;
    import java.applet.*;
    public class exer4 extends Applet
    Button but1;
    TextField txt1;
    TextField txt2;
    Label lab1;
         public void init()
         but1 = new Button("Click Me");
         add(but1);
         txt1 = new TextField(5);
         add(txt1);
         txt2 = new TextField(5);
         add(txt2);
         lab1 = new Label("This is a label");
         add(lab1);
    }

    Try this
    import java.awt.*;
    import java.applet.*;
    import java.util.*;
    public class pay extends Applet
    Button but1;
    TextField txt1;
    TextField txt2;
    Label lab1;
    public void init()
    lab1 = new Label("This is a label");
    Panel pan = new Panel();
    pan.add(lab1);
    add(pan);
    but1 = new Button("Click Me");
    add(but1);
    txt1 = new TextField(5);
    add(txt1);
    txt2 = new TextField(5);
    add(txt2);
    ps see you around

  • Set to new line for each label/text combination ?

    Dear All,
    Wish to enquire how to set to next line for each label/text combination in relation to the following code ? Please advise.
    import java.awt.*;
    public class ScanImageForm {
    public static void main(String args[]) {
         ScanImageForm scanImageForm = new ScanImageForm();
         scanImageForm.Display();
    public void Display() {
         Frame frame = new Frame();
         Panel panel = new Panel();
         frame.add(panel);
         Label labelVehNo = new Label("Vehicle No:");
         Label labelDateofLoss = new Label("Date of Loss:");
         Label labelImageType = new Label("Image Type:");
         Label labelImageDesc = new Label("Image Desc:");
         TextField textVehNo = new TextField();
         TextField textDateofLoss = new TextField();
         TextField textImageType = new TextField();
         TextField textImageDesc = new TextField();
         textVehNo.setColumns(10);          
         textDateofLoss.setColumns(10);
         textImageType.setColumns(10);
         textImageDesc.setColumns(30);
         panel.add(labelVehNo, BorderLayout.WEST);
         panel.add(textVehNo, BorderLayout.CENTER);
         panel.add(labelDateofLoss, BorderLayout.WEST);
         panel.add(textDateofLoss, BorderLayout.CENTER);
         panel.add(labelImageType, BorderLayout.WEST);
         panel.add(textImageType, BorderLayout.CENTER);
         panel.add(labelImageDesc, BorderLayout.WEST);
         panel.add(textImageDesc, BorderLayout.CENTER);
         frame.setSize(500, 500);
         frame.setVisible(true);

    if u want to set label and textfield side by side .
    then u have to set The layout is GridLayout().
    to ur example
    Panel p=new Panel(new GridaLayout(3,2))
    means three rows to columns.

  • How can i  change the column label text in a alv table display

    how can i change the column label text in a alv table display??
    A similar kinda of question was posted previuosly where the requirement was the label text was needed and following below code was given as solution :
    <i>*  declare column, settings, header object
    DATA: lr_column TYPE REF TO cl_salv_wd_column.
    DATA: lr_column_settings TYPE REF TO if_salv_wd_column_settings.
    DATA: lr_column_header type ref to CL_SALV_WD_COLUMN_HEADER.
    get column by specifying column name.
    lr_column = lr_column_settings->get_column( 'COLUMN_NAME1' ).
    set Header Text as null
    lr_column_header = lr_column->get_header( ).
    lr_column_header->set_text( ' ' ).</i>
    My specific requirement is i have an input field on the screen and i want reflect that value as the column label for one of the column in the alv table. I have used he above code with slight modification in the MODIFYVIEW method of the view since it is a process after input. The component gets activated without any errors but while run time i get an error stating
    <i>"The following error text was processed in the system CDV : Access via 'NULL' object reference not possible."</i>
    i have checked in debugging and the error occured at the statement :
    <i>lr_column = lr_column_settings->get_column( 'CURRENT_YEAR' ).</i>Please can you provide me an alternative for my requirement or correct me if i have done it wrong.
    Thanks,
    Suri

    I found it myself how to do it. The error says that it is not able to find the reference object i.e  it is asking us to refer to the table. The following piece of code will solve this problem. Have to implement this in WDDOMODIFYVIEW method of the view. This thing works comrades enjoy...
      DATA : lr_cmp_usage TYPE REF TO if_wd_component_usage,
             lr_if_controller  TYPE REF TO iwci_salv_wd_table,
             lr_cmdl   TYPE REF TO cl_salv_wd_config_table,
             lr_col    TYPE REF TO cl_salv_wd_column.
      DATA : node_year  TYPE REF TO if_wd_context_node,
             elem_year  TYPE REF TO if_wd_context_element,
             stru_year  TYPE if_alv_layout=>element_importing,
             item_year  LIKE stru_year-i_current_year,
             lf_string    TYPE char(x),
      DATA: lr_column TYPE REF TO cl_salv_wd_column.
      DATA: lr_column_header TYPE REF TO cl_salv_wd_column_header.
      DATA: lr_column_settings TYPE REF TO if_salv_wd_column_settings.
    Get the entered value from the input field of the screen
    node_year  = wd_context->get_child_node( name = 'IMPORTING_NODE' ).
    elem_year  = node_year->get_element( ).
      elem_year->get_attribute(
       EXPORTING
        name = 'IMPORT_NODE-PARAMETER'
       IMPORTING
        value = L_IMPORT_PARAM ).
      WRITE L_IMPORT_PARAM TO lf_string.
    Get the reference of the table
      lr_cmp_usage  =  wd_this->wd_cpuse_alv( ).
      IF lr_cmp_usage->has_active_component( ) IS INITIAL.
        lr_cmp_usage->create_component( ).
      ENDIF.
      lr_if_controller  = wd_this->wd_cpifc_alv( ).
      lr_column_settings = lr_if_controller->get_model( ).
    get column by specifying column name.
      IF lr_column_settings IS BOUND.
        lr_column = lr_column_settings->get_column( 'COLUMN_NAME').
    set Header Text as null
        lr_column_header = lr_column->get_header( ).
        lr_column_header->set_text( lf_string ).
    endif.

  • Newbie iPhone: How do I programatically set the text of a UIBarButtonItem?

    Hello,
    This is probably really more of a question on IBOutlets but here goes. I want to have an updateable label on my Toolbar. A label doesn't seem to "stick" on the toolbar so I figured I would drop a UIBarButtonItem on it and then just update the Title property of it to change the text as I needed. Problem is I can't figure out how to get a reference to the UIBarButtonItem in my code.
    With a pure label control, I can drag from the File's Owner to the label in my view to make it an outlet for my ViewController and then access the text property of the label in code. With the UIBarButtonItem, I can't make it an outlet. I know the button is more of an action thing but I don't need to respond to taps, I just want to change the text.
    Thanks for any help,
    Tom

    Tom,
    You should be able to assign the UIBarButtonItem to an outlet as long as:
    1) you have defined an instance variable in FilesOwner of UIBarButtonItem and prefixed it with "IBOutlet".
    2) FilesOwner is set to your custom view controller in the Interface Builder's Inspector panel. If it still thinks it's a standard UIViewController it won't pick up your custom outlets.
    All that being said, I'm not sure you can change the title without using a custom view. The default UIBarButtonItem has an initWithTitle: initializer that may be static (perhaps others know of a way to change it once set). But you can define a custom view for the button. That gives you the ability to add a UILabel and programmatically set the text of the label.
    Cheers,
    George

  • How to change a labels text which created at runtime?

    hi,
    i am creating label controls in runtime dynamically and adding them to a group component. this group component is in another custom component and i have lots of custom comp. in my app.
    my question is how can access (via id) and change a labels text whict created at runtime?
    i can change like this but i am setting id's and want to reach via id.
    var lbl:mx.controls.Label = mx.controls.Label(subMenu5.group_subMenu5.getElementAt(1));
    lbl.text = "good job";
    thank you, have a good day.

    First off, if you are already using a Spark Group, I would suggest you use a Spark Label instead of an MX Label. If you want to reference the Labels from the group, loop through the group's elements and check the if the element id matches the Label you want to assign text to.
    var lbl:Label;
    var n:int = myGroup.numElements;
    for (var i:int = 0; i < n; i++)
         lbl = myGroup.getElementAt(i) as Label;
         if (lbl && lbl.id == "myLabel")
              lbl.text = "newText";

  • Can't change the label text for the first time of  loading

    I have some problem to change the label text in the prerender method.
    I put a label on the form and set the text value to "Customer" on the text properities , and I would like to change the lable text to "Supplier" in the prerender method, I found some strange behaviour.
    If I type nothing on the label text of the properties , I can change the lable text on the prerender method on the first time of the form load .
    If I put something on the label text of the properties , the text label can't be changed on the first time of form loaded, the lable can be changed if I refresh the form or reload the form.
    Could anyone help me to solve this kinds of problem ?
    Thanks

    This is a tough one to explain. Here is one explanation from the Delving Into Components tutorial:
    As with the JavaServer Pages implementation, when the server constructs a page from JSP source, the tag attribute settings in the JSP source take precedence over runtime settings. For example, if you set the text property for a Static Text component to "moon," the IDE adds text="moon" to the Static Text component's tag in the JSP file. Even if the page's prerender method has a staticText1.setText("sun") statement, the Static Text component shows "moon" when the application renders the page. If the page is rerendered, the staticText1.setText("sun") statement takes affect and the Static Text component shows "sun." If you visit another page and come back, the server once again constructs the page from the JSP source, the values set in the JSP tag attributes take precedence, and the page displays "moon."

  • How to set textfield.text on frame after goto

    This seems a little ridiculous to be asking this question coz
    it seems like it should be so simple but here goes anyway.
    STEPS TO RECREATE:
    Step 1 - create a class called simpleButt(see attached)
    Step 2 - create a MovieClip with two frame labels on
    different keyframes- ROLLOVER and ROLLOUT. on these different
    keyframes place a dynamic textfield with instance name -
    'buttonTitle'. give it different styling attributes on the ROLLOVER
    frame such as text colour, bold or even a glow filter.
    Step 3 - In the movie clip's linkage properties, give it the
    'simpleButt' class.
    Step 4 - With nothing on the stage, add the following two
    lines to frame actions:
    var newButt:simpleButt=new simpleButt("hello");
    this.addChild(newButt);
    Step 5 - compile!
    this should add a simple button to the stage and set the
    button's textfield's text property.
    However, after going to another frame on rollover, we lose
    the dynamic text - i assume because we have another instance of the
    textfield on a different keyframe because it has new styling
    properties on rollover. but if i try to set the text after going to
    the new frame, it doesn't seem to recognise the textfield yet.
    (uncomment lines in simpleButt to see what i mean)
    through trial and error i've found that if i wait two
    ENTERFRAMEs, the textfield object becomes available, but by this
    time the textfield flickers. is there an event i'm missing or
    function i could override where i could set the properties of an
    object on a frame after a gotoAndStop before it is rendered?
    cheers
    Craig

    STEP 2(where the textfield was created) is all done manually
    within the authoring environment - no actionscript. This is usually
    done by the design team here so to save time i'm trying to avoid
    replicating every style change they've made in code.

  • Can't set label

    In CS2 I used this line
    tell application "Adobe InDesign CS2"
    set properties of every text frame whose label starts with "dude" to {label:"sweet"} of document 1
    end tell
    But in CS3 a strange error occurs
    tell application "Adobe InDesign CS3"
    set properties of every text frame whose label starts with "dude" to {label:"sweet"} of document 1
    end tell
    Now the weird part is if you just look for page items or text frames that start with label "bla bla" it works perfect but you can't set the label to anything.

    Nevermind this fixed it
    tell application "Adobe InDesign CS3"
    tell document 1
    set label of every text frame whose label starts with "dude" to "sweet"
    end tell
    end tell
    Strange I had to dumb down the code for it to work. In CS2 it see the property approach always worked.

  • Business Graphics : Set label for a Simple Series

    I need to set label to simple series of Business graphics object. Since the Label property is not bindable; i am looking for the alternative way to achieve this. (Any attempt to pass the context would give error msg: Method bindLabel( String) is undefined for the type IWDSimpleSeries)
    I want to have a string value in each points in graph (Line Graph), not i legend.
    tips will be highly appreciated.
    Thanks,
         Vinod V

    Hi Vinod,
    The label property for IWDPoint should solve your purpose.
    IWDPoint API 'label' property - This property is used to specify an optional text to be displayed for a point in a business graphic.
    Refer SAP NetWeaver Library http://help.sap.com/saphelp_nw04s/helpdata/en/1f/20ef3d5e10af5ee10000000a114084/frameset.htm
    Kind Regards,
    Nitin
    Edited by: Nitin Jain on Apr 8, 2009 4:40 PM

  • Issue with label text wont change correctly.

    Hi All,
      I have an issue.  I usually program with C#, PHP, html etc.  trying to learn Adobe Flash now so i downloaded the trial version which has 30 days trial.  tried to create and follow the tutor for click ball which all of the code is the same but it doesnt work. 
    I triple check the code and its all right but it still not working.  so i commented out all of the code and has a simple code of changing the text of the label.  i set the text to "abcdefg" and but it only show "cdef".  i expanded the width of the label so width is not the issue.  trying to search for the limitation of the trial but i dont see any.  trying to test this before i buy it.  Does anybody know why?  again, coding is not an issue, it does change but not changing correctly.  i try to set to another value it always show partially only.  what is going on?
    Thanks you for your help in advance.

    Try embedding the font - might fix missing characters.
    1) Select the TextField on the Stage
    2) In Properties pane, next to font name selector, click Embed and play with the Dialog
    3) Don't forget to select suitable character ranges

  • Tab Set Label Colors - How do I change the selected tab label color?

    No matter what color I tell it to use for the Labels - Selected color I get white.  Is this a known bug in the system or am I not doing something correct.  I have a tab set component and a label based menu selector component on my display.  I've set up the labels and backgrounds for both components exactly the same but I can only get white for the selected tab set label.
    Edited by: Maureen LaComb on Feb 19, 2009 5:38 PM

    Hi, Maureen
    You can set the color of Tab Set by using the Following Steps.
    --> Select the Tab Set
    --> From the the Properties Window
    --> Select Appearance
    --> There are Two Tabs "Text" and "Color"
    --> From the Color Tab you can Select the Background Color
    --> Tab BackGrounds Or Labels from here you can select the color.
    But this setting will Apply to all the Tabs in a Tab Set, I think you can't set the Specific Setting for a single Tab in a Tab Set.
    Please Reply if any Issue,
    Kind Regards,
    Faisal

  • How to Set label of a button in arabic by writting code.

    Hi,
    I have created a button by writtin following code in controller.
    OAButtonBean oasb = (OAButtonBean)createWebBean(oapagecontext, OAWebBeanConstants.BUTTON_BEAN, null, "Add");
    if ( oapagecontext.getCurrentLanguage().equals("US"))
    oasb.setText("Add Previous Objectives");;
    else
    oasb.setText("إضافة أهداف المرحلة السابقة");
    Its creating a button with the given label. When i check from english login it shows label as "Add Previous Objectives" But when i check the same from arabic login it shows "???????????????"
    Please suggest me how can i set arabic text for the same button.
    Thanks in advance
    Murali

    Hi Murali,
    It seems that the problem is with your browser where you are running your page. Check that the Arabic font is installed on your web browser and your system.
    Regards,
    Amit Kr. Singh

  • Overwrite Label Text

    Hi,
    I want to overwrite a Label Text.
    The Text I want to overwrite comes from a bound Context Node.
    Before I want to overwrite it I need the current Text, because I want to change Labels dynamically - however to get the actual Text I use Method GET_TEXT of Class CL_WD_LABEL but this Method sets some Attributes (which seems to be an error for my understanding of OO Concepts) anyway it seems not possible to overwrite the Text with Method SET_TEXT after calling GET_TEXT method (GET_TEXT will call the Bound Attribute after 1st call).
    Any ideas?
    TIA,
    Sebastian

    Hi,
    I want to change n-Lables
    And I want to do it like that: Loop at every Labels of a View and Replace every Occurance of "Oracle" with "SAP" (for example)
    But if the Label I want to change the text for is bound to a Context Element with an DDIC-Type the GET_TEXT Method (which I need for dynamic text changes) will set Parameters in the Label class which will always will get the old text (on next GET_TEXT call) never mind what text I assigned with SET_TEXT.
    But without a GET_TEXT I will not get all "Oracle" lables and so I can't replace the Texts I want to.
    Hope I could explain my Prob
    Regards,
    Sebastian

Maybe you are looking for

  • How do you update?

    What do you do to update?  I'm very bored so I made a poll  :twisted:

  • Materialized view logs for Fast refreshes

    Hi, I created MV and MV logs on the base table/main table. I set the base table in NOLOGGING MODE. so ofcourse redo is not gonna generate during DML but i wanted to know that: Will NOLOGGING effect the MV logs for fast refreshes? I came up on conclus

  • Empty record issues

    Hey, I am using jdeveloper 11g release 2, I did set one of my attributes as DBSequence. Once i trigger the commit operation records are saved with data assigned on the form. checking the database the records are saved . funny enough i found an  added

  • Best place to keep iTunes database...internal vs. external drive?

    My new iMac has a much smaller internal hard drive than my old iMac, so I plan to move my actual iTunes content (songs, videos) to an external hard drive.  Is it better to have the iTunes Library Database (iTunes Library.itl) on my computer's interna

  • Creating a tree structure like Windows file explorer using Jdev

    Hi All, Is it possible to develop a tree structure like windows in JDEV and then same page I want to move to oracle apps. This tree I am creating for Showing Employee information. Like Parents & childs under it. i.e. Managers and employee reporting t