Catch-22: need to assign a local variable within an anonymous class

static boolean showMessage(Window parent, String button0, String button1)
    throws HeadlessException {
          final Window w = new Window(parent);
          Panel p = new Panel(new GridBagLayout());
          final Button b[] = new Button[]{new Button(button0), (button1 != null) ? new Button(button1) : (Button)null};
          boolean rval[]; //tristate: null, true, false
          w.setSize(100, 50);
          w.setVisible(true);
          //add b[0
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.gridx = 0;
          gbc.gridy = 3;
          p.add(b[0], gbc);
          //add b[1]
          if (button1 != null) {
               gbc.fill = GridBagConstraints.HORIZONTAL;
               gbc.gridx = 1;
               gbc.gridy = 3;
               p.add(b[1], gbc);
          w.add(p);
          w.pack();
        w.setVisible(true);
        //actionListener for button 0
          b[0].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         if (e.getSource() == b[0]) {
                              w.setVisible(false);
                              rval = new boolean[1];
                              rval[0] = true;
          //actionListener for button 1
          if (button1 != null) {
               b[1].addActionListener(new ActionListener() {
                         public void actionPerformed(ActionEvent e) {
                              if (e.getSource() == b[1]) {
                                   w.setVisible(false);
                                   rval = new boolean[1];
                                   rval[0] = false;
        while (true) {
             try {
                  if (rval[0] == true || rval[0] == false) //should trigger NullPointerException
                       return rval[0];
             } catch (NullPointerException e) { }
     }catch-22 is at
rval = new boolean[1];
rval = false;javac whines: "local variable rval is accessed from within inner class; needs to be declared final"
How do I assign to rval if it's declared final?
Or at the very least, how do I get rid of this error (by all means, hack fixes are okay; this is not C/C++, I don't have to use sanity checks)?
I'm trying to make a messagebox in java without using JOptionPane and I'm trying to encapsulate it in one method.
And I'm far too lazy to make a JNI wrapper for GTK.

dcminter wrote:
How do I assign to rval if it's declared final?You don't and you can't. You're not allowed to assign to the local variable of the outer class for extremely good reasons, so forget about trying.
Or at the very least, how do I get rid of this errorIf you don't want the side effect, then just use an inner class variable or a local variable.
If you want the side effect then use a named class and provide it with a getter and setter.
Finally, in this specific case because you're using an array object reference, you could probably just initialise the array object in the outer class. I.e.
// Outer class
final boolean[] rval = new boolean[1];
// Anonymous Inner class
rval[0] = true; // No need to intialize the array.
I declared it as an array so that it would be a tristate boolean (null, true, false) such that accessing it before initialization from the actionPerformed would trigger a NullPointerException.
Flowchart:
is button pressed? <-> no
|
V
Yes->set and return
Is there a way to accomplish this without creating a tribool class?

Similar Messages

  • Does a large amount of "local variable" within a vi cause problems?

    Hello -- I am using Labview 7.0 and have a vi where I am going to end up using about 100 "local variables" for indicators that are displaying data. Since I have a lot of true / false case structures I decided to use these local variables instead of having a mess of wiring all over the vi block diagram. It is intimidating though and I was wondering if it causes slowness in vi's?

    I actually only have about 8 indicators -- but I am in the process of creating control algorithms so I have to use many case structures if I want to keep the code all within Labview (simplicity). I am simply referencing the 8 or so indicator values many many times (100 X) I am attaching a copy of the vi like you asked but just take a look at the right hand side of the while loop on the right -- it shows an example of an algorithm I created today that has to reference the data from sensors. I would love to know what a better way to do this. Thanks!
    Attachments:
    ucb drill control daq 1_7.vi ‏666 KB

  • Accessing member variable within an anonymous inner class

    I'm getting a compiler error with the following snippet which resides in a constructor (error below):
            final String fullNamesArr[] = new String[ lafsArr.length ];
            String lafNamesArr[] = new String[ lafsArr.length ];
            JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
            for ( int i = 0 ; i < lafsArr.length ; i++ )
                StringTokenizer tokenizer;
                fullNamesArr[ i ] = lafsArr[ i ].getClassName();
                tokenizer = new StringTokenizer( fullNamesArr[ i ] );
                while ( tokenizer.hasMoreTokens() )
                    lafNamesArr[ i ] = tokenizer.nextToken( "." );
                namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
                lafMenu.add( namesMenuItemArr[ i ] );
                namesMenuItemArr[ i ].addActionListener(new ActionListener()
                        public final void actionPerformed(final ActionEvent e)
                            String actionCommand = e.getActionCommand();
                            int iCount = 0;
                            for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                                if ( fullNamesArr[ index ].contains( actionCommand ))
                                    iCount = index;
                                    break;
                            System.out.println( "Setting LAF to '" +
                                                fullNamesArr[ iCount ] + "'" );
                            try
                                UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                            catch ( UnsupportedLookAndFeelException ulafe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Not a valid LAF class." );
                            catch ( ClassNotFoundException cnfe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Class not found." );
                            catch ( InstantiationException ie )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Can't instantiate class." );
                            catch ( IllegalAccessException iae )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Illegal access." );
    DBBuilder.java:1280: cannot resolve symbol
    symbol : method contains (java.lang.String)
    location: class java.lang.String
    if ( fullNamesArr[ index ].contains( actionCommand ))
    ^
    1 error
    BUILD FAILED
    My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
    TIA,
    Jeff

    My question: Why can I access fullNamesArr in other
    spots in the anon-inner class,but not with the
    String.contains() method? BTW, the carrot is under
    the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

  • Assigning value to variable within Range

    The Problem:
    Range of values permitted is 10 < x < 30. x starts at 20. Variable x increments by 5, on a button click, until it reaches 30, at which point it should decrement by 5, until it reaches 10, before moving up the range again... and so on.
    I'm sure this is quite simple, but it's been bugging me for hours... the following simple increments by 5.
    How would I include range constraint. please some help.
    void jButton_mouseClicked(MouseEvent e) {
    int r = aBall.radius();
    aBall.rad = r + 5;
    repaint();
    }

    You're right, perhaps, nasch_.
    When I was starting out, I learned a lot from looking at code and then figuring out how to adapt it. Perhaps I have denied the OP this opportunity.
    To learn more from the code I posted, OP, don't just copy and paste it. As nasch_ was pointing out, you absolutely must learn how to translate requirements in English (or language of your choice) into code. If-statements ar crucial elements. Look at the code and figure out how it matches your requirements. Think about what you have to do logically - When the size would be less than 10, you need to grow instead of shrink... etc. Write out (or at least think out) every scenario that your code has to react to. Size would be in range, size would be too large, size would be too small, ball is growing, ball is shrinking, etc. Make every possible combination and figure out how you must react.
    When your logic is hammered out like that, in natural language, start converting to logic. You see that your code has to remember whether your Ball is growing or shrinking. Your Ball should know it's minimum and maximum size (which my code ignores, making it less flexible). Turn your scenarios into If-statements. Your first code could have way too many If-elses, but get it to work, and then refine it by combining and nesting statements.
    Don't ever just copy and paste code. You won't learn how to do anything yourself. Learn from code you see. Take this opportunity to not just solve the immediate problem, but to realize that this is an area of your skills that needs improvement and follow through on improving it.
    -- end soapbox

  • Need to change the local change request to development class for Process Ch

    Hello ,
    I have created a Tranport request for Process chain but its saved as local change request .
    Please suggest how to change that .
    Thanks ,
    Rahul

    Hi
    1.First delete the request which you collected the process chain as local object becuase you will not able to collect the process chian again.
    2. Goto Tranport connector to collect the process chain again.
    3. Select grouping option as necessary objects.
    4. Drag and drop the process chain to the right hand side
    5. After collecting the process chain, click on the package icon and give the package created for development class.
    6. The system will ask for Transport request and save the PC in the Transport Request.
    Hope it helps.
    Regards
    Sadeesh

  • Local variable fail when using SIT

    Dear all,
    I am using SIT (Simulink Interface Toolkit) to obtain data generated by the model of  Simulink.  I need to use the local variable of the indicator to get the data out.
    The interface with the mappings seems to work fine. The problemn is that the local variable of the waveform (this waveform is an indicater which mapped to the output signal of simulink and it can displays the signal from simulink)didn't work. I cann't obtain any data from the local variable, but the waveform which the local variable belonges to seems to work fine.
    I also found an interesting thing that, when I hightlighting the execution process, the local variable  seems like didn't work at all, because there is no data flows from it.
    The software version is Matlab simulink R2011b, Labview 2011.
    Below is a simple test model in simulink. It is a sine signal.
    Below is the local variable from the waveform which mapped to the signal of simulink. To check there is any data in the local variable, I put a waveform to check.

    Dataflow.
    The local variable of the waveform is going to be empty to start.  The writing of the local variable called Waveform to the indicator called Local Variable is going to happen right away.  Only later does the waveform get any data.  But by then the first part has already exectued never to be run again.
    I would recommend looking at the online LabVIEW tutorials
    LabVIEW Introduction Course - Three Hours
    LabVIEW Introduction Course - Six Hours

  • Local variable can't be accessed from inner class ???????? Why ??????

    Plesae help, help, help. I have no idea what to do with this bug.........
    <code>
    for ( int i = 0; i <= 2; i++ ) {
    for ( int j = 0; j <= 2; j++ ) {
    grids[i][j] = new MyButton ();
    grids[i][j].setBorder(but);
    getContentPane().add(grids[i][j]);
    MyButton sub = grids[i][j];
    sub.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if ( sub.getState() == 0 ) {
         sub = new MyButton( (Icon) new ImageIcon(imageFile));
         if ( imageFile.equals("cross.jpg") ) {
              sub.changeState(1);
         else {
              sub.changeState(2);
    </code>
    The compiler complains that "sub" is in the inner class, which is the ActionListener class, must be declared final. Please tell me what to do with it. I want to add an ActionListener to each MyButton Object in the array. Thanks ......

    OK, now I changed my code to this :
    for ( int i = 0; i <= 2; i++ ) {
      for ( int j = 0; j <= 2; j++ ) {
        grids[i][j] = new MyButton ();
        grids[i][j].setBorder(but);
        getContentPane().add(grids[i][j]);
        grids[i][j].addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if ( grids[i][j].getState() == 0 ) {
               grids[i][j] = new MyButton( (Icon) new ImageIcon(imageFile));
              if ( imageFile.equals("cross.jpg") ) {
               grids[i][j].changeState(1);
              else {
              grids[i][j].changeState(2);
    [/cpde]
    Thanks for your advice !!!!!!
    Now the compiler says that i and j are local variables accessed from inner classes, needs to be declared final. How can I solve this then ???

  • Passing local variable to subsequence

    I have a sequence that sets a local variable, Locals.LowPassFreqGhz = 1.800. 
    Then it runs 5 subsequences.
    The Local is set to a new value and then the same 5 subsequences are run again.
    Now I have new model numbers where the pair is different and soon will have models where there will be groups of 4 frequencies instead of two. Therefore I would like to put the 5 seqs into a subseq and pass the freq based on a select statement. In my limited understanding and knowledge of TestStand I think the subsequence would have its own Local.variables. How should I pass this local to a subsequence, convert to a File.global?
    thanx,
    jvh 
    Solved!
    Go to Solution.

    there is another way also to  
    Teststand give us an option of "Propagation" of a  variable to subseqeunce.
    we need to  create a local variable both in main and sub sequence with same name and use "Propogate to subsequence" in main seqeunce and " allowpropagation from caller" in sub seqeunce.
    This option of propagation one can see by right click of a variable in variables pane. This allows us to get the values of variables in main seqeuence to sub seqeunce.
    But need to remember that both variable names in main and sub sequence should be the same.
    Regards,
    Praveen.

  • Local variable accessed within inner class

    Hey everybody,
    My program keeps telling me that it wont work because one of my methods is calling a local variable inside an inner class. Does anyone know what this means and how to fix it?
    Heres the code:
    public class SliderExample extends JPanel{
    int value=0;
    public SliderExample(int imw, int imh, Image img, BufferedImage buf, Graphics2D biCon){
    super(true);
    this.setLayout(new BorderLayout());
    JSlider slider= new JSlider(JSlider.HORIZONTAL,0,imw,25);
    slider.setMinorTickSpacing(10);
    slider.setMajorTickSpacing(100);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    JButton redraw= new JButton("Scroll");
    redraw.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ev){
    reDraw(slider,img,buf,biCon,imw,imh);
    add(slider,BorderLayout.CENTER);
    add(redraw,BorderLayout.AFTER_LINE_ENDS);
    public void reDraw(JSlider slid, Image im, BufferedImage bf, Graphics2D biC, int iw, int ih){
    value=slid.getValue();
    Graphics g= getGraphics();
    g.drawImage(im,value,0,iw,ih,this);
    g.drawImage(bf,value,0,iw,ih,this);
    biC.drawImage(bf,value,0,iw,ih,this);
    Any ideas???
    THanks,
    Rick

    Its getting them from another class thats calling the mothod to construct the slider bar with dedraw button. Thats a pretty big class but I will post the code where I called the method:
    public class Process extends JFrame implements MouseListener, MouseMotionListener{
    private int [][] points;
    private int [] lengths={0};
    private int [] bin;
    private String imstr;
    private String imsav;
    private int imgw=658;
    private int imgh=512;
    private int xArrayPos=0;
    private int yArrayPos=0;
    private int xpos=0;
    private int ypos=0;
    private int xprev;
    private int yprev;
    private int xadd;
    private int yadd;
    private String filstr;
    Image image;
    SimpleGUI gui;
    BufferedImage buffer;
    Graphics2D biContext;
    Graphics2D g2;
    BufferedImage last;
    Graphics2D lastContext;
    public Process(){
    JFrame slideFrame = new JFrame("Please slide to scroll image");
    slideFrame.setContentPane(new SliderExample(imgw, imgh,image,buffer,biContext));
    slideFrame.pack();
    slideFrame.setVisible(true);
    Thats what anything having to do with that function in the other class that calls the Slider Class.
    Do you know how I can fix this??
    Thanks,
    Rick

  • "abstract" modifier for local variable

    Again, I am studying the SCJP 6 and have a question on avaiable access modifier in local variable (within the method).
    The book said the ONLY access modifier allowed for variable within the method is "final", and for method-local inner class is "abstract" or "final". But for fun I tried to write this code:
    public class NewClass1 {
        public static void method1(){
            abstract String a = "hello";
            System.out.println(a);
        public static void main(String[] args){
            method1();
    }can it compiles and runs fine. Also when I change to this below, I can even "change" the value of a refer to, the behaviour seems ignoring the final access modifier:
    public class NewClass1 {
        public static void method1(){
            abstract final String a = "hello";
            a = "free to change the value";
            System.out.println(a);
        public static void main(String[] args){
            method1();
    }So my question are:
    1. Can local variable use the access modifier "abstract"?
    2. If yes, what is the meaning of it?
    Edited by: roamer on 2009?11?16? ??9:55

    it compiles and runs fine
    As I said in the post they were compiled and ran without any error or exception.
    Yes, when "compiling", I got the compilation error which is same to your message^^
    let's see if I got the same error again in my home.I've seen your future, and it's got a compiler error in it.

  • "What are anonymous local variables."

    What are anonymous local variables and what are anonymous classes in java . If possible give one working example using anonymous classes and anonymous local variables .

    What are anonymous local variables and what areYou tell me. I never heard of such a thing.
    anonymous classes in java . If possible give oneClasses being declared without actually giving them a name. Sort of ugly.
    void myMethod() {
      ActionListener al = new ActionListener() { // Anonymous inner class
        public void ActionPerformed(ActionEvent e) {
          doMAgic();
      this.add(al);
    }

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • Non-final variable inside an inner class - my nemisis

    I have an issue with accessing variables from an inner method. This structure seems to allow access to the text objects but not to the button object. This comes from a bit of example code that just illustrates a simple form window with text fields and buttons that read them.
    At the start of the class I have text objects defined like this:
    public class SimpleGUI extends Composite {
    Text nameField;
    Text junkField;
    // Constructors come next, etc...
    Later within this class there is a method to create some GUI stuff, and then to create a button and when pressed access and print the text to the console
    protected void createGui(){
    junkField = new Text(entryGroup,SWT.SINGLE); //Ross
    junkField.setText("Howdy");
    Button OKbutton = new Button(buttons,SWT.NONE);
    OKbutton.setText("Ok");
    OKbutton.addSelectionListener(
    new MySelectionAdapter() {
    public void widgetSelected(SelectionEvent e) {
    System.out.println("Name: " + nameField.getText());
    System.out.println("Junk: " + junkField.getText());
    And that all works fine. So within the inner class, the object junkField can be accessed nicely.
    However if I try to do the same with the button (I want to change the label on the button after it's pressed) I get errors for trying to access a non-final object in an inner class.
    I tried to handle the button similar to the text, adding this after the text defs:
         Button myButton;
    and under the println's in the inner class I wanted:
    if OKbutton.getText.equals("OK") {  OKbutton.setText("NotOK")}
    That's when I get an issue with "cannot refer to a non-final variable inside an inside class defined in a different method"
    Now, if I move the button declaration into the createGui method, and declare it with "final Button myButton" it works.
    Why does the button need different treatment than the text?
    Is this a suitable method to make my button change it's label when pressed, or is this sloppy?

    Button is a local variable. The anonymous inner class object you create can continue to exist after the method ends, but the local variables will not. Therefore, as the error message says, you must make that local button variable final if you want to refer to it inside the anon inner class. If it's final, a copy of its value can be given to the inner class--there's no need to treat it as "variable."

  • How do I use a variable within a sql statement

    I am trying to use a local variable within an open SQL step but I keep getting an error.
    My sql command looks like this "SELECT BoardDetailID FROM BoardDetails WHERE SerialNumber = " +  locals.CurrentSerialNo
    If I replace the locals.CurrentSerialNo with an actual value such as below the statement works fine.
    "SELECT BoardDetailID FROM BoardDetails WHERE SerialNumber = " +  " 'ABC001' " 
    Can someone tell me how to correctly format the statement to use a variable?

    Hi,
    Thanks for the reply. I have changed the required variable to a string, but with no success. I have reattached my updated sequence file and an image of the error.
    When looking at the Data operation step I see that the sql statement is missing everything after the last quotation mark.
    Thanks again,
    Stuart
    Attachments:
    Database Test Sequence.seq ‏10 KB
    TestStand error.JPG ‏37 KB

  • Static variables in anonymous classes ..

    How can i access a static variable from an anonymous class ..
    class A{
    outerMeth(){
    Interface anon=new Interface(){
    static int i;
    // how can i acess 'i' ..
    thanx in advance ..

    sorry .. not a valid question ..
    static var are not allowed in anonymous/inner classes ..
    sorry ..
    ignore this one ..

Maybe you are looking for

  • Falha no Processo de Aprovação

    Olá Bom dia! Estou com hum Problema no Processo de aprovação de Cotação de Vendas, Pedido de venda, onde: SBO 9 PL 11 Meu Modelo de aprovação tem um seguinte Regra: Todo Documento Gerado abaixo de hum "valor Unitário" 'X' temque ir para aprovação. Ex

  • Cloud Suiten

    Hallo Viele Nutzer finden das Cloud Angebot von Adobe nur überrissen und teuer. Warum führ man nicht wie früher verschiedene Suiten in der Cloud ein? Ich brauche keine Master Collection Version. Alle auf ein Abo zu Vergewaltigung und dann noch die hö

  • JAAS and Active Directory Problem

    I am attempting to use the JAAS Tutorial code to authenticate against a Windows 2000 domain controller. The code as is works against a domain controller that I set up, but when I attempt to authenticate against a client's domain, I receive an excepti

  • Please help me ( advanced graphical user interface)

    I have to finish this problem until 5 pm. Java How to program (Deitel & Deitel) - Third edition page 696 please help me 13-7 : write a program that displays a circle of random size and calculates and displays the area, radius, diameter and circumfere

  • Burned photos to dvd - they printed fuzzy

    I have many photos on my mac that I need to print and back up. I have my library backed up on an external hard drive but I would feel better to have them on cd's as well. I burned a dvd of some photos ( I didn't have a cd) . I took it to the store to