简体   繁体   English

我如何以小程序和应用程序的形式运行某些内容?

[英]How do I run something as an applet and application?

I'm working on this project and I need it run as an applet and an application. 我正在从事这个项目,我需要它作为小程序和应用程序运行。 This is what I have but I stuck on where to go because I can't find anything on the internet. 这就是我所拥有的,但是由于无法在互联网上找到任何东西,所以我坚持去哪里。 Are there any resources or does someone have some quick advice to give me? 有没有资源或有人可以给我一些快速建议?

public class Project extends JApplet {

public void init() {

    try {
        URL pictureURL = new URL(getDocumentBase(), "sample.jpg");
        myPicture = ImageIO.read(pictureURL);
        myIcon = new ImageIcon(myPicture);
        myLabel = new JLabel(myIcon);
    } catch (Exception e) {
        e.printStackTrace();
    }
    add(label, BorderLayout.NORTH);

    add(bio);
    add(bio, BorderLayout.CENTER);

    pane.add(play);
    getContentPane().add(pane, BorderLayout.SOUTH);
    play.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try{
                FileInputStream FIS = new FileInputStream("sample.mp3");
                player = new Player (FIS);
                player.play();
            } catch (Exception e1) {
                e1.printStackTrace();
            }}});
}

public static void main(String args[]) {
    JFrame frame = new JFrame("");
    frame.getContentPane().add();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.show();
}

private JPanel pane = new JPanel();
private TextArea bio = new TextArea("Bio");
private JButton play = new JButton("Play");
private Image myPicture;
private ImageIcon icon;
private JLabel label;
private Player player;

}

When trying to run something as an applet and as an application, there are several caveats. 尝试将某些内容作为小程序和应用程序运行时,有一些警告。

Applets have a certain life cycle that must be obeyed. 小程序具有一定的生命周期 ,必须遵守。 One can add the applet to the content pane of the JFrame and manually call init() , but in general, if the applet expects its start() or stop() methods to be called, things may become tricky... 可以将小程序添加到JFrame的内容窗格中,然后手动调用init() ,但是通常,如果小程序希望调用其start()stop()方法,事情可能会变得棘手...

More importantly: The way how resources are handled is different between applets and applications. 更重要的是:小程序和应用程序之间处理资源的方式不同。

Handling files in applets (eg with a FileInputStream ) may have security implications, and will plainly not work in some cases - eg when the applet is embedded into a website. 处理applet中的文件(例如,使用FileInputStream )可能会带来安全隐患,并且在某些情况下(例如,当applet嵌入到网站中时)显然不起作用。 (Also see What Applets Can and Cannot Do ). (另请参阅小程序可以做什么和不能做什么 )。

Conversely, when running this as an application, calling getDocumentBase() does not make sense. 相反,当将其作为应用程序运行时,调用getDocumentBase()没有任何意义。 There simply is no "document base" for an application. 应用程序根本就没有“文档库”。


Nevertheless, it is possible to write a program that can be shown as an Applet or as an Application. 但是,可以编写一个可以显示为小程序或应用程序的程序。 The main difference will then be whether the main JPanel is placed into a JApplet or into a JFrame , and how data is read. 然后,主要区别将在于是将主JPanel放置在JApplet还是JFrame ,以及如何读取数据。

One approach for reading data that works for applets as well as for applications is via getClass().getResourceAsStream("file.txt") , given that the respective file is in the class path. 假设相应的文件位于类路径中,则一种读取适用于applet和应用程序的数据的方法是通过getClass().getResourceAsStream("file.txt")

I hesitated a while, whether I should post an example, targeting the main question, or whether I should modify your code so that it works. 我犹豫了一下,是否应该针对主要问题发布示例,还是应该修改您的代码以使其正常工作。 I'll do both: 我都会做:

Here is an example that can be executed as an Applet or as an Application. 这是可以作为Applet或应用程序执行的示例。 It will read and display a "sample.jpg". 它将读取并显示“ sample.jpg”。 (This file is currently basically expected to be "in the same directory as the .class-file". More details about resource handling, classpaths and stream handling are beyond the scope of this answer) (目前,基本上,该文件应该与“ .class-file位于同一目录中。”关于资源处理,类路径和流处理的更多详细信息不在此答案的范围内)

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class AppletOrApplicationExample extends JApplet
{
    @Override
    public void init()
    {
        add(new AppletOrApplicationMainComponent());
    }

    public static void main(String args[])
    {
        JFrame frame = new JFrame("");
        frame.getContentPane().add(new AppletOrApplicationMainComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

class AppletOrApplicationMainComponent extends JPanel
{
    public AppletOrApplicationMainComponent()
    {
        super(new BorderLayout());

        InputStream stream = getClass().getResourceAsStream("sample.jpg");
        if (stream == null)
        {
            add(new JLabel("Resource not found"), BorderLayout.NORTH);
        }
        else
        {
            try
            {
                BufferedImage image = ImageIO.read(stream);
                add(new JLabel(new ImageIcon(image)), BorderLayout.NORTH);
            }
            catch (IOException e1)
            {
                add(new JLabel("Could not load image"), BorderLayout.NORTH);
            }
        }

        JTextArea textArea = new JTextArea("Text...");
        add(textArea, BorderLayout.CENTER);

        JButton button = new JButton("Button");
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                doSomething();
            }
        });
        add(button, BorderLayout.SOUTH);
    }

    private void doSomething()
    {
        System.out.println("Button was clicked");
    }
}


And here is something that is still a bit closer to your original code. 而且,这里的内容与原始代码还有一些距离。 However, I'd strongly recommend to factor out the actual application logic as far as possible. 但是,我强烈建议尽可能地考虑实际的应用程序逻辑。 For example, your main GUI component should then not be the applet itself, but a JPanel . 例如,你的主GUI组件应该再不是小应用程序本身,而是一个JPanel Resources should not be read directly via FileInputStream s or URLs from the document base, but only from InputStreams . 不应直接通过FileInputStream或URL从文档库中读取资源,而只能从InputStreams读取资源。 This is basically the code that you posted, with the fewest modifications that are necessary to get it running as an applet or an application : 这基本上是您发布的代码, 只需进行最少的修改即可使其作为applet或应用程序运行

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Module5Assignment2 extends JApplet
{
    public void init()
    {
        try
        {
            InputStream stream = getClass().getResourceAsStream("sample.jpg");
            if (stream == null)
            {
                System.out.println("Resource not found");
            }
            else
            {
                myPicture = ImageIO.read(stream);
                icon = new ImageIcon(myPicture);
                label = new JLabel(icon);
                add(label, BorderLayout.NORTH);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        add(bio);
        add(bio, BorderLayout.CENTER);

        pane.add(play);
        getContentPane().add(pane, BorderLayout.SOUTH);
        play.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    FileInputStream FIS = new FileInputStream("sample.mp3");
                    // player = new Player (FIS);
                    // player.play();
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }
            }
        });
    }

    public static void main(String args[])
    {
        JFrame frame = new JFrame("");
        // ******PRETTY SURE I NEED TO ADD SOMETHING HERE*************
        Module5Assignment2 contents = new Module5Assignment2();
        frame.getContentPane().add(contents);
        contents.init();
        // *************************************************************

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.show();
    }

    private JPanel pane = new JPanel();
    private TextArea bio = new TextArea(
        "This is the bio of Christian Sprague; he doesn't like typing things.");
    private JButton play = new JButton("Play");
    private Image myPicture;
    private ImageIcon icon;
    private JLabel label;
    // private Player player;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM