Search code examples
javaswinginputjframejapplet

Using JTextField in a JApplet


This is my first time messing with JApplet.. I'm trying to make this JTextField() work properly... But no matter what i do i cant get it to show up on the page!

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

public class Hangman extends JApplet{
    private static final long serialVersionUID = -3966472303224962681L;

    public void paint(Graphics g){
        super.paint(g);
        Container c = getContentPane();
        JTextField input = new JTextField(20);

        c.setBackground(Color.BLACK);

        g.setColor(Color.WHITE);
        g.setFont(new Font("Arial", Font.BOLD, 30));
        g.drawString("Welcome to the Hagman Applet for the Web!", 20, 30);

        g.setFont(new Font("Arial", Font.ITALIC, 18));
        g.drawString("also available on android.", 20, 50);

        c.add(input);
        input.getText();
    }
}

Solution

  • You should not add components to your applet in the "paint" method. Do it f.e. in the constructor:

     public Hangman() {
        Container c = getContentPane();
        c.setBackground(Color.BLACK);
        JTextField input = new JTextField(20);
        c.setLayout(new BorderLayout());
        c.add(input, BorderLayout.SOUTH);
    }