简体   繁体   English

为什么JLabel不能成为内部类声明

[英]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 为什么不能在Java Swing中的JLabel像JMenu或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 ;" 在上面的程序中,为什么必须将这一行放在“ private JLabel lbl”中?
Why Cant i use JLabel lbl = new JLabel("Label"); 为什么我不能使用JLabel lbl = new JLabel(“ Label”);

You can , but variables used in a closure need to be declared final. 您可以 ,但是需要将闭包中使用的变量声明为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: 在这种情况下,从匿名ActionListener实例中引用“ lbl”:

    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. 您不能将其设置为私有构造函数,因为您尝试在actionPerformed方法中在构造函数之外使用它。 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. 您可以通过将其声明为final来解决这个问题,但是我一直认为这是一个可疑的把戏,我不知道它是否一定能正常工作,还是只是在欺骗编译器。

i think you can, you just need to define it final 我认为可以,您只需要最终定义

you can define it as a local variable before addActionListner. 您可以在addActionListner之前将其定义为局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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