subanki
subanki

Reputation: 1429

Why can't JLabel be an inner class declaration

Why cant JLabel in java swing be declared inside the inner class like JMenu or JMenuBar

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class Chk extends JFrame 
{

private JLabel lbl ;

public Chk()
{

lbl = new JLabel("StatusBar");  
lbl.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(lbl,BorderLayout.SOUTH);


JMenuBar menubar=new JMenuBar();
JMenu file = new JMenu("File");
JMenu view = new JMenu("View");

JCheckBoxMenuItem sbar= new JCheckBoxMenuItem("Status-Bar");
sbar.setState(true);
sbar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{


if (lbl.isVisible())
{lbl.setVisible(false);}
else
{lbl.setVisible(true);}


}});




menubar.add(file);
view.add(sbar);
menubar.add(view);
setJMenuBar(menubar);

setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String args[])
{new Chk();}

}

in the above program why do i have to put this line "private JLabel lbl ;"
Why Cant i use JLabel lbl = new JLabel("Label");

Upvotes: 1

Views: 492

Answers (3)

jvdneste
jvdneste

Reputation: 1687

You can, but variables used in a closure need to be declared final.

    final JLabel lbl = new JLabel("StatusBar");
    lbl.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
    add(lbl, BorderLayout.SOUTH);

This should work.

In case you are wondering, the closure is the part where you create an instance of an anonymous inner class and refer to a variable declared in an enclosing scope. In this case 'lbl' is referenced from within an anonymous ActionListener instance:

    sbar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (lbl.isVisible()) {
                lbl.setVisible(false);
            } else {
                lbl.setVisible(true);
            }
        }
    });

Upvotes: 3

mhshams
mhshams

Reputation: 16972

i think you can, you just need to define it final

you can define it as a local variable before addActionListner.

Upvotes: 0

Paul Tomblin
Paul Tomblin

Reputation: 182878

You can't make it private to the constructor because you're attempting to use it outside of the constructor, in the actionPerformed method. You can sneak around that by declaring it final, but I've always thought that was a dubious trick and I don't know if it's guaranteed to work or if it's just fooling the compiler.

Upvotes: 0

Related Questions