Sobiaholic
Sobiaholic

Reputation: 2957

How to convert Java program to Applet?

I would like to convert my Simple Java program to an Applet Program. I've looked for different tutorials but all were in general most of it didn't talk about GUI to Applet.

This is my simple program if you could instruct me to do it or comment on the changed lines I would be so much appreciated.

Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test_Exam_091 {

    public static void main(String[] args) {
        new MyFrame();
    }
}

class MyFrame extends JFrame implements MouseListener {

    public MyFrame() {
        setTitle("Playing With The Mouse!");
        setSize(400, 400);
        setResizable(false);
        setVisible(true);
        addMouseListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        show();
    }

    public void mouseEntered(MouseEvent me) {
        System.out.println("Mouse entered at: ("
            + me.getX() + ", " + me.getY() + ")");
    }

    public void mouseExited(MouseEvent me) {
        System.out.println("Mouse exited at: ("
            + me.getX() + ", " + me.getY() + ")");
    }

    public void mouseClicked(MouseEvent me) {
        System.out.println("Mouse clicked at: ("
            + me.getX() + ", " + me.getY() + ")");
    }

    public void mousePressed(MouseEvent me) {
        System.out.println("Mouse pressed at: ("
            + me.getX() + ", " + me.getY() + ")");
    }

    public void mouseReleased(MouseEvent me) {
        System.out.println("Mouse released at: ("
            + me.getX() + ", " + me.getY() + ")");
    }
} // End of MyFrame class

Upvotes: 1

Views: 9505

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Some tips: Most of the lines of the constructor are irrelevant to applets.

setTitle("Playing With The Mouse!"); // An applet has no title 
    // (Though it might have an ID/name in HTML)
setSize(400, 400);  // Set in HTML
setResizable(false); // An applet is usually fixed size
setVisible(true); // Not relevant to an applet (visible by default)
addMouseListener(this); 
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Not allowed in an applet
show(); // Deprecated for components around 1.2, for TLCs around 1.5, ..
    // ..and redundant

In the listener methods..

System.out.println("Mouse pressed at: (" + me.getX() + ", " + me.getY() +")");

Will cause problems, since that output will end up in the Java Console which is generally invisible to the end user (and most developers). It was not particularly appropriate to the JFrame form either. It will be necessary to add a JLabel or similar to the GUI, in which to display the results.

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

JApplet is a descendant of java.awt.Panel that also acts as a Swing container so it can be used almost interchangeably with other containers like JFrame and JPanel.

Upvotes: 2

Related Questions