Java JFrame,错误无法对非静态字段进行静态引用

Java JFrame,错误无法对非静态字段进行静态引用,java,eclipse,swing,compiler-errors,jframe,Java,Eclipse,Swing,Compiler Errors,Jframe,我试图从SerialRead方法设置数据变量,但我得到“无法对非静态字段Etiqueta2进行静态引用”,Eclipse说我应该将Etiqueta2设置为静态,但它没有在Jlabel中显示数据 public class Final extends JFrame { //Crea Elementos de la interfaz JLabel Etiqueta=new JLabel(); JTextField Texto=new JTextField(); JBu

我试图从SerialRead方法设置数据变量,但我得到“无法对非静态字段Etiqueta2进行静态引用”,Eclipse说我应该将Etiqueta2设置为静态,但它没有在Jlabel中显示数据

public class Final extends JFrame
{

    //Crea Elementos de la interfaz
    JLabel Etiqueta=new JLabel();
    JTextField Texto=new JTextField();
    JButton Boton=new JButton();
    JLabel Etiqueta1=new JLabel();
    JLabel Etiqueta2=new JLabel();
    JButton Boton1=new JButton();




    public Final()
    {
        super();
        // Crea la interfaz

        setVisible(true);
        setLayout(null);
        setTitle("Lectura y escritura de datos");
        setSize(380,200);
        //Propiedades de los elementos del Frame
        // Etiqueta
        Etiqueta.setBounds(20,50, 100, 20);
        Etiqueta.setText("Enviar un digito");
        add(Etiqueta);
        // Caja de texto
        Texto.setBounds(120,50,100, 20);
        add(Texto);
        // Boton
        Boton.setBounds(250,50,100, 20);
        Boton.setText("Enviar");
        add(Boton);
        // Etiqueta 1
        Etiqueta1.setBounds(20,80, 100, 20);
        Etiqueta1.setText("Leer un digito");
        add(Etiqueta1);
        // Etiqueta2
        Etiqueta2.setBounds(120,80,100, 20);
        add(Etiqueta2);
        // Boton 1
        Boton1.setBounds(250,80,100, 20);
        Boton1.setText("Leer");
        add(Boton1);
        // Boton de cierre   
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                new SerialReader(in, Etiqueta2).execute();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }

    /** */
public static class SerialReader extends SwingWorker<Void, String> {   //Final frame = new Final();

    private InputStream in;
    private JLabel label;

    public SerialReader(InputStream in, JLabel label) {
        this.in = in;
        this.label = label;
    }

    @Override
    protected void process(List<String> chunks) {
        String data = chunks.get(chunks.size() - 1);
        label.setText(data);
    }

    @Override
    protected Void doInBackground() throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = this.in.read(buffer)) > -1) {
            String data = new String(buffer, 0, len);
            System.out.println(data);
            publish(data);
        }
        return null;
    }
}

    /** */
    public static class SerialWriter implements Runnable 
    {
          **** output code ****
    }

    public static void main ( String[] args )
    {

        try
        {
            (new Final()).connect("COM7");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
public类最终扩展JFrame
{
//克里亚国际酒店
JLabel Etiqueta=新的JLabel();
JTextField Texto=新的JTextField();
JButton-Boton=新JButton();
JLabel Etiqueta1=新的JLabel();
JLabel Etiqueta2=新的JLabel();
JButton Boton1=新JButton();
公开决赛()
{
超级();
//克里亚拉因弗塔兹酒店
setVisible(真);
setLayout(空);
setTitle(“曼陀斯学院”);
设置大小(380200);
//框架构件设计方案
//艾蒂克塔
立根(20,50,100,20);
Etiqueta.setText(“Enviar un digito”);
添加(Etiqueta);
//德克托咖啡馆
文本立根(120,50100,20);
添加(Texto);
//波顿
波顿立根数(250,50100,20);
Boton.setText(“Enviar”);
添加(Boton);
//Etiqueta 1
Etiqueta1.立根(20,80,100,20);
Etiqueta1.setText(“Leer un digito”);
添加(Etiqueta1);
//Etiqueta2
Etiqueta2.挫折(120,80100,20);
添加(Etiqueta2);
//波顿1号
Boton1.立根(250,80100,20);
Boton1.setText(“Leer”);
添加(Boton1);
//博顿·德·西尔
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
void connect(字符串portName)引发异常
{
CommPortIdentifier portIdentifier=CommPortIdentifier.getPortIdentifier(端口名);
if(portIdentifier.isCurrentlyOwned())
{
System.out.println(“错误:端口当前正在使用”);
}
其他的
{
CommPort CommPort=portIdentifier.open(this.getClass().getName(),2000);
if(串行端口的commPort实例)
{
SerialPort SerialPort=(SerialPort)commPort;
serialPort.setSerialPortParams(9600,serialPort.DATABITS_8,serialPort.STOPBITS_1,serialPort.PARITY_NONE);
InputStream in=serialPort.getInputStream();
OutputStream out=serialPort.getOutputStream();
新的SerialReader(in,Etiqueta2.execute();
(新线程(新SerialWriter(out))).start();
}
其他的
{
System.out.println(“错误:本例只处理串行端口。”);
}
}     
}
/** */
公共静态类SerialReader扩展SwingWorker{//Final frame=new Final();
私有输入流;
私人标签;
public SerialReader(InputStream-in,JLabel标签){
this.in=in;
this.label=标签;
}
@凌驾
受保护的无效进程(列表块){
字符串数据=chunks.get(chunks.size()-1);
label.setText(数据);
}
@凌驾
受保护的Void doInBackground()引发异常{
字节[]缓冲区=新字节[1024];
int len=-1;
而((len=this.in.read(buffer))>-1){
字符串数据=新字符串(缓冲区,0,len);
系统输出打印项次(数据);
发布(数据);
}
返回null;
}
}
/** */
公共静态类SerialWriter实现可运行
{
****输出代码****
}
公共静态void main(字符串[]args)
{
尝试
{
(新的Final()).connect(“COM7”);
}
捕获(例外e)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
如何在Etiqueta2标签上设置Text以显示数据变量

谢谢


EDIT3:我用swingworker更新了代码,执行并打印LN以查看控制台中的数据

SerialReader
Final
的静态内部类,因此无法访问
Final
中的任何非静态字段。由于您显然没有在
Final
之外使用
SerialReader
,所以只需将其设置为非静态(甚至可以是私有的内部类)。这同样适用于
SerialWriter

SerialReader
被声明为
static
,因此它不能访问外部
Final
类的实例字段,因为可以创建
SerialReader
的实例,而不需要先创建
Final
的实例

相反,您应该将要更新的
JLabel
的引用传递给
SerialReader

public static class SerialReader implements Runnable 
{   //Final frame = new Final();

    InputStream in;
    private JLabel label;

    public SerialReader ( InputStream in, JLabel label ) {
         this.label = label;
         //...
然后,您将使用它从run方法中进行更新

您可以简单地使类非静态,但这取决于您的需要

另一个问题是Swing不是线程安全的,因此实际上不建议从
run
方法中调用
JLabel
实例上的
setText

通常,我建议使用
SwingWorker
,因为它有一些方法,允许您
发布来自后台线程的
结果,并
在事件调度线程的上下文中处理这些结果,允许您安全地修改UI的状态,但在这种情况下,您可以使用
SwingUtilities.invokeLater

    public void run ()
    {
        //...
        try
        {
            while ( ( len = this.in.read(buffer)) > -1 )
            {
                //...
                SwingUtiltiies.invokeLater(new Runnable() {
                    public void run() {
                        Etiqueta2.setText(data);
                    }
                });
            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }            
    }
但是您可能需要将
数据
设置为最终版
,这可能会导致更多问题,在这种情况下,我只需要使用
SwingWorker

请仔细查看以了解更多详细信息

SwingWorker
示例。。。 “伪造”
InputStream
示例。。。
import java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.List;
导入java.util.Random;
导入java.util.concurrent.ExecutionException;
导入java。
public static class SerialReader extends SwingWorker<Void, String> {   //Final frame = new Final();

    private InputStream in;
    private JLabel label;

    public SerialReader(InputStream in, JLabel label) {
        this.in = in;
        this.label = label;
    }

    @Override
    protected void process(List<String> chunks) {
        String data = chunks.get(chunks.size() - 1);
        label.setText(data);
    }

    @Override
    protected Void doInBackground() throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = this.in.read(buffer)) > -1) {
            String data = new String(buffer, 0, len);
            publish(data);
        }
        return null;
    }
}
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;

        public TestPane() {
            setLayout(new GridBagLayout());
            label = new JLabel("...");
            add(label);
            new ClockWorker(label).execute();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public static class ClockWorker extends SwingWorker<Void, String> {

        protected static final DateFormat DF = new SimpleDateFormat("hh:mm.ss SSS a");

        private JLabel label;

        public ClockWorker(JLabel label) {
            this.label = label;
        }

        @Override
        protected void process(List<String> chunks) {
            label.setText(chunks.get(chunks.size() - 1));
        }



        @Override
        protected Void doInBackground() throws Exception {
            while (true) {
                publish(DF.format(new Date()));
                Thread.sleep(1);
            }
        }

    }

}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;

public class Final extends JFrame {

    //Crea Elementos de la interfaz
    JLabel Etiqueta = new JLabel();
    JTextField Texto = new JTextField();
    JButton Boton = new JButton();
    JLabel Etiqueta1 = new JLabel();
    JLabel Etiqueta2 = new JLabel("Banana");
    JButton Boton1 = new JButton();

    public Final() {
        super();
        // Crea la interfaz

        setVisible(true);
        setLayout(null);
        setTitle("Lectura y escritura de datos");
        setSize(380, 200);
        //Propiedades de los elementos del Frame
        // Etiqueta
        Etiqueta.setBounds(20, 50, 100, 20);
        Etiqueta.setText("Enviar un digito");
        add(Etiqueta);
        // Caja de texto
        Texto.setBounds(120, 50, 100, 20);
        add(Texto);
        // Boton
        Boton.setBounds(250, 50, 100, 20);
        Boton.setText("Enviar");
        add(Boton);
        // Etiqueta 1
        Etiqueta1.setBounds(20, 80, 100, 20);
        Etiqueta1.setText("Leer un digito");
        add(Etiqueta1);
        // Etiqueta2
        Etiqueta2.setBounds(120, 80, 100, 20);
        add(Etiqueta2);
        // Boton 1
        Boton1.setBounds(250, 80, 100, 20);
        Boton1.setText("Leer");
        add(Boton1);
        // Boton de cierre   
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    void connect(String portName) throws Exception {

        System.out.println("...");
        new SerialReader(new FakeInputStream(), Etiqueta2).execute();

//      CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
//      if (portIdentifier.isCurrentlyOwned()) {
//          System.out.println("Error: Port is currently in use");
//      } else {
//          CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
//
//          if (commPort instanceof SerialPort) {
//              SerialPort serialPort = (SerialPort) commPort;
//              serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
//
//              InputStream in = serialPort.getInputStream();
//              OutputStream out = serialPort.getOutputStream();
//
//              new SerialReader(in, Etiqueta2).execute();
//              (new Thread(new SerialWriter(out))).start();
//
//          } else {
//              System.out.println("Error: Only serial ports are handled by this example.");
//          }
//      }
    }

    /**
     *
     */
    public static class SerialReader extends SwingWorker<Void, String> {

        private InputStream in;
        private JLabel label;

        public SerialReader(InputStream in, JLabel label) {
            this.in = in;
            this.label = label;
        }

        @Override
        protected void process(List<String> chunks) {
            String data = chunks.get(chunks.size() - 1);
            label.setText(data);
        }

        @Override
        protected Void doInBackground() throws Exception {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = this.in.read(buffer)) > -1) {
                String data = new String(buffer, 0, len);
                System.out.println(data);
                publish(data);
            }
            return null;
        }

        @Override
        protected void done() {
            try {
                get();
            } catch (InterruptedException | ExecutionException ex) {
                ex.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {

        try {
            (new Final()).connect("COM7");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static class FakeInputStream extends InputStream {

        private Random rnd = new Random();

        @Override
        public int read() throws IOException {
            return 33 + rnd.nextInt(125-33); // Ascii characters
        }

    }
}