Java 无法通过程序访问jlabel

Java 无法通过程序访问jlabel,java,swing,static,jlabel,private-members,Java,Swing,Static,Jlabel,Private Members,我是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 set

我是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方法,这对于“helloworld”类型的程序来说是很好的,但是如果您希望创建更强大的程序,您将希望创建,无需学习面向对象的概念以及如何在Java程序中应用它们。例如,对于该项目的开始,您应该创建至少一个具有非静态字段和方法的类,包括JLabel的字段(通过该字段,您将允许类的非静态方法访问该字段),并且您应该构建GUI,这意味着在主方法之外向容器添加组件,更像是在一些非静态的
init()
方法或构造函数中。主要方法应该只用于创建对象并将其设置为动作,而不是其他。但同样最重要的是,学习OOP概念以及它们与Java编程语言的关系。这是一本不错的书

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

例如:

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)方法访问


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

感谢装满鳗鱼的气垫船提供了很好的建议。我是Java新手,刚刚开始学习所有这些面向对象的东西。顺便说一下,这也是我关于Stackoverflow的第一个问题。谢谢你的回复。我明白我错在哪里,你的回答很有帮助