无法跨程序访问 jlabel

Unable to access jlabel across the program

我是 Java 的新手,因此提出了这个基本问题。

我在整个程序中访问字段(在本例中为 jlabel)时遇到问题。我的代码如下:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class accessvariable {

    public static void main(String[] args) {

        //basic setup of display frame
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        JPanel panel=new JPanel();

        //text field to take user input
        JTextField txt= new JTextField(10);

        //adding action listener for text field
        txt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (true) { //if condition not checking anything here, just to make it enter the loop
                    JLabel j =new JLabel("Access successful"); //a jlabel created inside this 
                    System.out.println("inside j : "+j.getText()); //statement to check whether jlabel is accessible from here
                }
            }
        });

        System.out.println("outside j : "+j.getText()); //statement to check whether jlabel is accessible from here

        //basic setup for final display
        panel.add(txt);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

错误在这一行:

System.out.println("outside j : "+j.getText());

如果我注释掉这一行,它就可以正常工作。内部 j 显示正确。但是如果我不评论它,我会收到这个错误:

Exception in thread "Exception in thread "main" java.lang.Error: Unresolved compilation problem: j cannot be resolved"

为了纠正这个问题,我将 j 设为实例变量,如下所示:

private JLabel j; 

但是上面的代码产生了一个新的错误:

Cannot make a static reference to the non-static field j

我知道问题出在这一行:

System.out.println("outside j : "+j.getText());

如何解决上述问题,如果它正常工作,当我在文本字段中输入一些文本时,输出应该如下所示:

inside j : Access successful
outside j : Access successful

等等。停止。重新开始。

你的程序只不过是一个静态的 main 方法,这对 "Hello World" 类型的程序来说很好,但是如果你想创建更强大的东西,你会想要,不 需要 了解面向对象的概念以及如何在 Java 程序中应用它们。例如,对于这个项目的开始,您应该至少创建一个具有非静态字段和方法的 class,包括一个用于 JLabel 的字段(通过它您将允许 [=29] 的非静态方法=] 访问该字段),你应该构建你的 GUI,这意味着将组件添加到容器中,在 main 方法之外,更像是在一些非静态 init() 方法或构造函数中。主要方法应该只用于创建您的对象并将它们设置为动作,除此之外别无其他。但同样最重要的是,学习 OOP 概念以及它们与 Java 编程语言的关系。一本不错的书是 Bruce Eckel's "Thinking in Java"

另一个现在受到重创的概念是 scope,包括变量作用域。如果你有一个变量,这里是 JLabel 变量,j,不仅在方法内部埋藏和声明,而且在埋藏在匿名内部 ActionListener class 内部的方法中,它几乎是其他 class 代码不可能与此变量交互。如果它是一个实例字段,那么它在包含它的 class 的所有非静态部分中都是可见的。

例如:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings("serial")
public class AccessVariable extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private JLabel myLabel = new JLabel();
    private JTextField textField = new JTextField(10);

    public AccessVariable() {
        add(textField);
        add(myLabel);

        textField.addActionListener(new MyListener());
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private class MyListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            myLabel.setText("Text is: " + text);

            textField.requestFocusInWindow();
            textField.selectAll();
        }
    }

    private static void createAndShowGui() {
        AccessVariable mainPanel = new AccessVariable();

        JFrame frame = new JFrame("Access Variable");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

老兄,看看变量j的作用域就知道了。 当你声明 j 为私有成员变量时,它肯定不能直接从静态( main )方法访问。

最好在循环外声明它并再次检查代码执行情况