简体   繁体   中英

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");

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);
            }
        }
    });

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.

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

you can define it as a local variable before addActionListner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM