-1

Can you have classes outside the Applet/JApplet class in a Java applet?

1 Answers1

0

You mean to have java classes in separate files in your applet project? The answer is yes.

E.g. Two classes MyApplet.java and Person.java

enter image description here

here is MyApplet.java

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

public class MyApplet extends JApplet implements ActionListener {
    public void init() {
          JButton button = new JButton("Click Me!");
        button.addActionListener(this);
        getContentPane().add(button);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Person person = new Person();
        person.setName("Jack");
        person.setAge(18);
        String title = "Greetings";  // Shown in title bar of dialog box.
        String message = "Hello " + person.getName() + " from the Swing User Interface Library.";
        JOptionPane.showMessageDialog(null, message, title,
                JOptionPane.INFORMATION_MESSAGE);
    }
}

And here is the Person.java class (in a separate file)

public class Person {
    String name;
    int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
pleft
  • 7,567
  • 2
  • 21
  • 45