为什么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();}
}
在上面的程序中,为什么我必须加上这一行“private JLabel lbl ;”
为什么我不能使用 JLabel lbl = new JLabel("Label");
最佳答案
可以,但闭包中使用的变量需要声明为 final。
final JLabel lbl = new JLabel("StatusBar");
lbl.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(lbl, BorderLayout.SOUTH);
这应该有效。
如果您想知道,闭包是您创建匿名内部类实例并引用在封闭范围内声明的变量的部分。在这种情况下,“lbl”是从匿名 ActionListener 实例中引用的:
sbar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (lbl.isVisible()) {
lbl.setVisible(false);
} else {
lbl.setVisible(true);
}
}
});
关于java - 为什么 JLabel 不能是内部类声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3450378/