javaswingappletawtswingbuilder

Java components are invisible when swing app is run as APPLET


Respected all, I am making a Swing-application window in ECLIPSE. When I run the program as 'JAVA-Application' the program functions well. However when I try to run the program as "Java_applet" the components like 'command button', 'textbox' are invisible.

I am entirely new to Java. I had previously worked on C#. Kindly please help me.

import java.awt.EventQueue;
import java.applet.*;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import java.awt.BorderLayout;

public class sa extends Applet{

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    sa window = new sa();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public sa() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
        frame.getContentPane().add(rdbtnNewRadioButton, BorderLayout.CENTER);
    }
}

Solution

  • You can't just have your class extend Applet and expect that that is all that is necessary for it to behave like a proper Applet. You need to give the class a proper init method and build the GUI from within this method. But most importantly you will need to read an Applet tutorial, any decent tutorial should do. Myself, I'd have my GUI extend JPanel, build the GUI in its constructor, and then I could use this JPanel in a JApplet or JFrame as needed.

    As Andrew aptly notes in comment,

    I think the OP should also dump the entire 'applet' part of it and develop the JFrame with an idea to launching it from a link using Java Web Start. At least then it would have a better chance for working for users of Chrome and FireFox (which are both planning to remove all support for applets).