从 Java 事件中访问全局对象

发布于 2024-11-24 07:36:42 字数 4571 浏览 2 评论 0原文

我的 Java 经验很少,而且我似乎找不到任何可以解释如何解决我的问题的东西;几个小时以来我一直在尝试不同的事情。

我正在使用 Phidg​​ets RFID Java 库 (http://www.phidgets.com/programming_resources.php) 和 JLayer,目的是根据传感器范围内的 RFID 标签播放不同的 mp3 文件。一旦 RFID 标签不再处于范围内,比赛就需要停止。

mp3 类:

// Import the JLayer classes
import javazoom.jl.player.*;

// Import the Java classes
import java.io.*;

public class mp3 {

    private Player player;
    private InputStream is;

    /** Creates a new instance of MP3Player */
    public mp3() 
    {
        //
    }

    public void play( String filename )
    {
        try
        {
            // Create an InputStream to the file
            is = new FileInputStream( filename );
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

        try
        {
            player = new Player( is );
            PlayerThread pt = new PlayerThread();
            pt.start();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

    public void stop()
    {
        player.close();
    }

    class PlayerThread extends Thread
    {
        public void run()
        {
            try
            {
                player.play();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }
}

以及发生其他所有事情的类:

import com.phidgets.*;
import com.phidgets.event.*;

public class ParrotDJ
{        

    public static final void main(String args[]) throws Exception {

            RFIDPhidget rfid;

            mp3 song = new mp3();

    System.out.println(Phidget.getLibraryVersion());

    rfid = new RFIDPhidget();
    rfid.addAttachListener(new AttachListener() {
        public void attached(AttachEvent ae)
        {
            try
            {
                ((RFIDPhidget)ae.getSource()).setAntennaOn(true);
                ((RFIDPhidget)ae.getSource()).setLEDOn(true);
            }
            catch (PhidgetException ex) { }
            System.out.println("attachment of " + ae);
        }
    });
    rfid.addDetachListener(new DetachListener() {
        public void detached(DetachEvent ae) {
            System.out.println("detachment of " + ae);
        }
    });
    rfid.addErrorListener(new ErrorListener() {
        public void error(ErrorEvent ee) {
            System.out.println("error event for " + ee);
        }
    });

    rfid.addTagGainListener(new TagGainListener()
    {

        public void tagGained(TagGainEvent oe)
        {
            //System.out.println(oe);
                            if(oe.getValue().equals("0107ee6ed5") || oe.getValue().equals("0107ee75d5"))
                            {
                                System.out.println("Amanda Palmer - Leeds United");
                                song.play("leedsunited.mp3");

                            }else if(oe.getValue().equals("0107ee82c7") || oe.getValue().equals("0107ee89f0"))
                            {
                                System.out.println("Paolo Nutini - 10/10");
                                song.play("1010.mp3");

                            }else if(oe.getValue().equals("0107ee8644") || oe.getValue().equals("0107ee6ff2"))
                            {
                                System.out.println("Mozart - Eine Kleine Nachtmusik");
                                song.play("einekleinenachtmusik.mp3");
                            }
        }

    });
    rfid.addTagLossListener(new TagLossListener()
    {
        public void tagLost(TagLossEvent oe)
        {
            //System.out.println(oe);
                            System.out.println("Stop");
                            song.stop();

        }
    });
    rfid.addOutputChangeListener(new OutputChangeListener()
    {
        public void outputChanged(OutputChangeEvent oe)
        {
            System.out.println(oe);
        }
    });

    rfid.openAny();
    System.out.println("waiting for RFID attachment...");
    rfid.waitForAttachment(1000);

    System.out.println("Serial: " + rfid.getSerialNumber());
    System.out.println("Outputs: " + rfid.getOutputCount());

    System.out.println("Outputting events.  Input to stop.");
    System.in.read();
    System.out.print("closing...");
    rfid.close();
    rfid = null;
    System.out.println(" ok");
    if (false) {
        System.out.println("wait for finalization...");
        System.gc();
    }
}
}

我想有一个合乎逻辑的解决方案,我只是在努力理解事件驱动的东西和 Java 的面向对象。我查找了构建器模式,但我现在不知道如何将其应用于这种情况。

提前致谢。

My Java experience is minimal, and I can't seem to find anything that explains to me how to solve my problem; I've been trying different things for hours.

I'm using the Phidgets RFID Java library (http://www.phidgets.com/programming_resources.php) and JLayer, with the aim of playing different mp3 files depending on which RFID tag is within range of the sensor. Playing needs to stop as soon as the RFID tag is no longer in range.

The mp3 class:

// Import the JLayer classes
import javazoom.jl.player.*;

// Import the Java classes
import java.io.*;

public class mp3 {

    private Player player;
    private InputStream is;

    /** Creates a new instance of MP3Player */
    public mp3() 
    {
        //
    }

    public void play( String filename )
    {
        try
        {
            // Create an InputStream to the file
            is = new FileInputStream( filename );
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

        try
        {
            player = new Player( is );
            PlayerThread pt = new PlayerThread();
            pt.start();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

    public void stop()
    {
        player.close();
    }

    class PlayerThread extends Thread
    {
        public void run()
        {
            try
            {
                player.play();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }
}

And class where everything else happens:

import com.phidgets.*;
import com.phidgets.event.*;

public class ParrotDJ
{        

    public static final void main(String args[]) throws Exception {

            RFIDPhidget rfid;

            mp3 song = new mp3();

    System.out.println(Phidget.getLibraryVersion());

    rfid = new RFIDPhidget();
    rfid.addAttachListener(new AttachListener() {
        public void attached(AttachEvent ae)
        {
            try
            {
                ((RFIDPhidget)ae.getSource()).setAntennaOn(true);
                ((RFIDPhidget)ae.getSource()).setLEDOn(true);
            }
            catch (PhidgetException ex) { }
            System.out.println("attachment of " + ae);
        }
    });
    rfid.addDetachListener(new DetachListener() {
        public void detached(DetachEvent ae) {
            System.out.println("detachment of " + ae);
        }
    });
    rfid.addErrorListener(new ErrorListener() {
        public void error(ErrorEvent ee) {
            System.out.println("error event for " + ee);
        }
    });

    rfid.addTagGainListener(new TagGainListener()
    {

        public void tagGained(TagGainEvent oe)
        {
            //System.out.println(oe);
                            if(oe.getValue().equals("0107ee6ed5") || oe.getValue().equals("0107ee75d5"))
                            {
                                System.out.println("Amanda Palmer - Leeds United");
                                song.play("leedsunited.mp3");

                            }else if(oe.getValue().equals("0107ee82c7") || oe.getValue().equals("0107ee89f0"))
                            {
                                System.out.println("Paolo Nutini - 10/10");
                                song.play("1010.mp3");

                            }else if(oe.getValue().equals("0107ee8644") || oe.getValue().equals("0107ee6ff2"))
                            {
                                System.out.println("Mozart - Eine Kleine Nachtmusik");
                                song.play("einekleinenachtmusik.mp3");
                            }
        }

    });
    rfid.addTagLossListener(new TagLossListener()
    {
        public void tagLost(TagLossEvent oe)
        {
            //System.out.println(oe);
                            System.out.println("Stop");
                            song.stop();

        }
    });
    rfid.addOutputChangeListener(new OutputChangeListener()
    {
        public void outputChanged(OutputChangeEvent oe)
        {
            System.out.println(oe);
        }
    });

    rfid.openAny();
    System.out.println("waiting for RFID attachment...");
    rfid.waitForAttachment(1000);

    System.out.println("Serial: " + rfid.getSerialNumber());
    System.out.println("Outputs: " + rfid.getOutputCount());

    System.out.println("Outputting events.  Input to stop.");
    System.in.read();
    System.out.print("closing...");
    rfid.close();
    rfid = null;
    System.out.println(" ok");
    if (false) {
        System.out.println("wait for finalization...");
        System.gc();
    }
}
}

I imagine there's a logical solution, I'm just struggling to get my head around event-driven stuff, and Java's object orientation. I looked up builder patterns, but I can't grasp how to apply that to this situation right now.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尘曦 2024-12-01 07:37:25

如果您想从匿名类的方法中访问局部变量,如下所示:

  rfid.addTagGainListener(new TagGainListener() {

            public void tagGained(TagGainEvent oe) {

其中 new TagGainListener() {} 创建一个匿名类。

您需要将该变量声明为final,只要您不想修改它,就不会有任何问题。所以修改后的代码将是:

import com.phidgets.*;
import com.phidgets.event.*;

public class ParrotDJ {

    public static final void main(String args[]) throws Exception {

        RFIDPhidget rfid;

        //  you need to make it final to access to it from anonymous classes as there rfid.addTagGainListener(new TagGainListener() {
        final mp3 song = new mp3();

        System.out.println(Phidget.getLibraryVersion());

        rfid = new RFIDPhidget();

        rfid.addAttachListener(new AttachListener() {
            public void attached(AttachEvent ae) {
                try {
                    ((RFIDPhidget) ae.getSource()).setAntennaOn(true);
                    ((RFIDPhidget) ae.getSource()).setLEDOn(true);
                } catch (PhidgetException ex) {
                }
                System.out.println("attachment of " + ae);
            }
        });

        rfid.addDetachListener(new DetachListener() {
            public void detached(DetachEvent ae) {
                System.out.println("detachment of " + ae);
            }
        });

        rfid.addErrorListener(new ErrorListener() {
            public void error(ErrorEvent ee) {
                System.out.println("error event for " + ee);
            }
        });

        rfid.addTagGainListener(new TagGainListener() {

            public void tagGained(TagGainEvent oe) {
                //System.out.println(oe);
                if (oe.getValue().equals("0107ee6ed5") || oe.getValue().equals("0107ee75d5")) {
                    System.out.println("Amanda Palmer - Leeds United");
                    song.play("leedsunited.mp3");

                } else if (oe.getValue().equals("0107ee82c7") || oe.getValue().equals("0107ee89f0")) {
                    System.out.println("Paolo Nutini - 10/10");
                    song.play("1010.mp3");

                } else if (oe.getValue().equals("0107ee8644") || oe.getValue().equals("0107ee6ff2")) {
                    System.out.println("Mozart - Eine Kleine Nachtmusik");
                    song.play("einekleinenachtmusik.mp3");
                }
            }

        });
        rfid.addTagLossListener(new TagLossListener() {
            public void tagLost(TagLossEvent oe) {
                //System.out.println(oe);
                System.out.println("Stop");
                song.stop();

            }
        });
        rfid.addOutputChangeListener(new OutputChangeListener() {
            public void outputChanged(OutputChangeEvent oe) {
                System.out.println(oe);
            }
        });

        rfid.openAny();
        System.out.println("waiting for RFID attachment...");
        rfid.waitForAttachment(1000);

        System.out.println("Serial: " + rfid.getSerialNumber());
        System.out.println("Outputs: " + rfid.getOutputCount());

        System.out.println("Outputting events.  Input to stop.");
        System.in.read();
        System.out.print("closing...");
        rfid.close();
        rfid = null;
        System.out.println(" ok");
        if (false) {
            System.out.println("wait for finalization...");
            System.gc();
        }
    }
}

If you want to access a local variable from whitin a method of an anonymous class as the one in here:

  rfid.addTagGainListener(new TagGainListener() {

            public void tagGained(TagGainEvent oe) {

where new TagGainListener() {} creates an anonymous class.

You'll need to declare that variable final, and you won't have any problem as long as you don't want to modify it. So the modified code would be:

import com.phidgets.*;
import com.phidgets.event.*;

public class ParrotDJ {

    public static final void main(String args[]) throws Exception {

        RFIDPhidget rfid;

        //  you need to make it final to access to it from anonymous classes as there rfid.addTagGainListener(new TagGainListener() {
        final mp3 song = new mp3();

        System.out.println(Phidget.getLibraryVersion());

        rfid = new RFIDPhidget();

        rfid.addAttachListener(new AttachListener() {
            public void attached(AttachEvent ae) {
                try {
                    ((RFIDPhidget) ae.getSource()).setAntennaOn(true);
                    ((RFIDPhidget) ae.getSource()).setLEDOn(true);
                } catch (PhidgetException ex) {
                }
                System.out.println("attachment of " + ae);
            }
        });

        rfid.addDetachListener(new DetachListener() {
            public void detached(DetachEvent ae) {
                System.out.println("detachment of " + ae);
            }
        });

        rfid.addErrorListener(new ErrorListener() {
            public void error(ErrorEvent ee) {
                System.out.println("error event for " + ee);
            }
        });

        rfid.addTagGainListener(new TagGainListener() {

            public void tagGained(TagGainEvent oe) {
                //System.out.println(oe);
                if (oe.getValue().equals("0107ee6ed5") || oe.getValue().equals("0107ee75d5")) {
                    System.out.println("Amanda Palmer - Leeds United");
                    song.play("leedsunited.mp3");

                } else if (oe.getValue().equals("0107ee82c7") || oe.getValue().equals("0107ee89f0")) {
                    System.out.println("Paolo Nutini - 10/10");
                    song.play("1010.mp3");

                } else if (oe.getValue().equals("0107ee8644") || oe.getValue().equals("0107ee6ff2")) {
                    System.out.println("Mozart - Eine Kleine Nachtmusik");
                    song.play("einekleinenachtmusik.mp3");
                }
            }

        });
        rfid.addTagLossListener(new TagLossListener() {
            public void tagLost(TagLossEvent oe) {
                //System.out.println(oe);
                System.out.println("Stop");
                song.stop();

            }
        });
        rfid.addOutputChangeListener(new OutputChangeListener() {
            public void outputChanged(OutputChangeEvent oe) {
                System.out.println(oe);
            }
        });

        rfid.openAny();
        System.out.println("waiting for RFID attachment...");
        rfid.waitForAttachment(1000);

        System.out.println("Serial: " + rfid.getSerialNumber());
        System.out.println("Outputs: " + rfid.getOutputCount());

        System.out.println("Outputting events.  Input to stop.");
        System.in.read();
        System.out.print("closing...");
        rfid.close();
        rfid = null;
        System.out.println(" ok");
        if (false) {
            System.out.println("wait for finalization...");
            System.gc();
        }
    }
}
野心澎湃 2024-12-01 07:37:08

除了摘要之外,我不确定具体问题是否清楚。但根据我的猜测,您在访问内部类方法中的类中定义的对象时遇到了问题。
主要问题是无法访问非“最终”字段,因为 Java 不知道该字段的状态。如果这些字段被设为最终字段,您应该能够在事件方法中访问外部类字段

I am not sure if the specific question is clear except as per the summary. But based on my guess, it looks like you are having issues accessing the object defined in the class within inner class methods.
The main issue is the fields not being "final" cannot be accessed as Java does not know the state of the field. If the fields were made final, you should be able to access the outer class fields in event methods

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文