tags:

views:

24

answers:

1

I have never done Applet development. Trying something very simple. Basically I am drawing a string on the window. However, whenever I re-size the window the content disappears.

A similar suggested question on SO recommended overriding the update() method to call repaint(). I tried that but that still didn't do it. Also how can I center the string ("Hello World!") on the window (so that it stays centered even on resize)?

Here is the code:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JApplet;

public class TestApplet extends JApplet
{
 public void init(){
  setBackground (Color.gray);
 }
 public void paint (Graphics page){
  String name = "Hello World!";
  page.drawString(name,100,100);
 }

 public void update(Graphics page){
  this.repaint();
 }
}
+1  A: 

This is old code used for AWT applications. You should never override the paint() or update() methods of a JApplet.

When using Swing custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent). Then you add the panel to the content pane of the applet.

Read the section from the Swing tutorial on Custom Painting for examples and more details. The tutorial also has a section on "How to Make Applets" that you should look at.

Also how can I center the string ("Hello World!") on the window (so that it stays centered even on resize)

Get the size of the parent panel by using the getSize() method. Then divide by 2. Although you need to remember that the Y coordinated is the bottom of the text not the top. So you would also need to consider the FontMetrics of the Font to know the exact height of the text. You can get the FontMetrics from the Graphics object.

camickr