[Solved] How to run a java applet code


To draw the I love you text you can call: g.drawString(...) method and position it over the T-Shirt.

Next to draw a heart shape, you can call the same method using the ASCII’s heart shape:

But be sure to use a nice (big enough) font so it can be visualized correctly, for example:

g.setFont(new Font("Verdana", Font.PLAIN, 25));
g.setColor(Color.BLACK);
g.drawString("I love you", 570, 480);

g.setColor(Color.RED);
g.drawString("♥", 620, 510);

But as you’ve been said, Java Applets are no longer supported by browsers, there are 2 things you can do:

  1. Convert the code into a Swing Application (recommended)
  2. Use AppletViewer (Which I’ve never used)

We’re going to go through the 1st one:

First, we need to change:

// Draw a beautiful sky
setBackground(Color.cyan);

for:

g.setColor(Color.CYAN);
g.fillRect(0, 0, 1500, 1000); //I'm lazy to search the window size... change it accordingly

Next, we need to remove extends Applet from our class and change it to extends JPanel and change

public void paint(Graphics g) {

To:

@Override
public void paintComponent(Graphics g) {

And add another overriden method:

@Override
public Dimension getPreferredSize() {
    return new Dimension(1500, 1000); //Again, change it to the window's correct size.
}

To finish we need to create a main method as follows:

private JFrame frame;

public static void main(String[] args) {
    SwingUtilities.invokeLater(new FunnyClown()::createAndShowGui);
}

private void createAndShowGui() {
    frame = new JFrame(getClass().getSimpleName());

    this.setOpaque(true);
    frame.add(this);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Now, if you run the application you should see something like this:

enter image description here

For reference, you’re going to need:

solved How to run a java applet code