如何从gui(jframe)调用此代码

时间:2014-06-03 11:46:20

标签: java swing djnativeswing

我想通过actionlistener从一个窗口调用youtubeviewer

public class YouTubeViewer {

public YouTubeViewer(){
    NativeInterface.open();
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame("YouTube Viewer");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().add(getBrowserPanel(), BorderLayout.CENTER);
            frame.setSize(800, 600);
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    });
    NativeInterface.runEventPump();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            NativeInterface.close();
        }
    }));
}

public JPanel getBrowserPanel() {
    JPanel webBrowserPanel = new JPanel(new BorderLayout());
    JWebBrowser webBrowser = new JWebBrowser();
    webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
    webBrowser.setBarsVisible(false);
    webBrowser.navigate("www.youtube.com/embed/sKeCX98U29M");
    return webBrowserPanel;
}
}

jframe示例(用于测试)

public class trailerPlayer extends JPanel implements ActionListener
{
private JButton press;
public trailerPlayer ()
{
    setLayout(new BorderLayout());
            press = new JButton("press");
            press.addActionListener(this);
            add(press);
}
public void actionPerformed(ActionEvent actionEvent)
{
           YouTubeViewer a = new YouTubeViewer();
    }
    public static void main(String args[ ])
{  
    trailerPlayer p = new trailerPlayer(); 
    JFrame test = new JFrame();

    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.add(p);
    test.setSize(500,500);
    test.setVisible(true);
}
}

YouTubeViewer包括DJ Native Swing api库。

如果我直接通过main函数调用,它会工作。但是如果我从actionlistener调用它会在我按下时停止响应〜我猜这是运行问题的问题〜如何解决?任何的想法?谢谢 任何的想法??

1 个答案:

答案 0 :(得分:1)

您的代码会阻止EDT(NativeInterface.runEventPump();)。所以你应该在另一个线程中做到这一点。

public void actionPerformed(ActionEvent actionEvent)
{
       Thread t = new Thread(new Runnable() {
         public void run() {
           YouTubeViewer a = new YouTubeViewer();
         }
       });
       t.start();
}