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.
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: