简体   繁体   English

如何在打开JFrame的Java Applet中创建一个按钮?

[英]How do I make a button in a Java Applet that opens a JFrame?

I've made a few JFrames and I want to call them from a JApplet. 我做了一些JFrames,我想从JApplet中调用它们。 What is the best way to do this? 做这个的最好方式是什么? Could I just instantiate my JFrames in my init method and then call them whenever a button is pushed? 我可以在init方法中实例化我的JFrame,然后只要按下按钮就调用它们吗?

How do I make a button in a Java Applet that opens a JFrame? 如何在打开JFrame的Java Applet中创建一个按钮?

You probably shouldn't do this, but rather if you want to open another window from the JApplet, create and show a JDialog. 你可能不应该这样做,而是如果你想从JApplet打开另一个窗口,创建并显示一个JDialog。 They are created and displayed similar to a JFrame, but uses different constructors. 它们的创建和显示类似于JFrame,但使用不同的构造函数。 You will need to get the applet's Window for the "owner" parameter of the JDialog, and this can be obtained via: 您需要获取JDialog的“owner”参数的applet窗口,这可以通过以下方式获得:

Window w = (Window) SwingUtilities.getAncestorOfClass(Window.class, comp); 

Where comp is a visible component in the JApplet. 其中comp是JApplet中的可见组件。

Ok, it sounds like you initialize a JFrame on initialization and you store it. 好吧,这听起来像是在初始化时初始化JFrame并存储它。 You don't need to re-instantiate the JFrame from initalization. 您无需从初始化中重新实例化JFrame。 Instead just store it in a field of your Applet and use it when ever the button is pressed. 而是将其存储在Applet的一个字段中,并在按下按钮时使用它。

OR you can use Singletons and lazy initialization: 或者您可以使用单身和懒惰初始化:

class JFrameToOpen extends JFrame {
    private static JFrame frame = null;
    private JFrameToOpen() {
        //init
    }
    public static GetJFrame() {
        if(frame==null) {
            frame=new JFrameToOpen();
        }
        return frame;
    }
}

But singletons are ugly and many people choose to avoid them. 但是单身人士很丑陋,很多人选择避开它们。

You can just create JFrame with its default constructor and then show it: 您可以使用其默认构造函数创建JFrame ,然后显示它:

JFrame frame = new JFrame();
JLabel label = new JLabel("Welcome");
frame.add(label);
frame.pack();
frame.setVisible(true);

This code forks from the applet similar way as from the standalone program. 此代码从applet以与独立程序类似的方式分叉。 No need for any special tricks. 不需要任何特殊技巧。 The applet itself then can only contain buttons like "press to launch the application". 然后applet本身只能包含“按下以启动应用程序”之类的按钮。

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

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