FAQ 4b
Updated: 1/10/00
>>>>>> How do I change screens like Dragon Court?
=================================================
As I've noted before (see FAQ_3d), Applets are Containers. Containers can hold Components.
And Containers can also hold other Containers (since Container extends Component).
Dragon Court is organized as a series of Panels (Panels are a type of Container).
To change screens, I simply change Panels.
Since Panels are a kind of Container, you can add Buttons, Images, and other tools to your Panel.
You can also add specialized code to each Panel. Organize your game so that all the code necessary
to operate one screen is associated with the appropriate panel.
Here is a simple example that flips between 3 screens:
// 'PanelApplet.java' code file
import java.applet.*;
import java.awt.*;
class PanelApplet extends Applet {
Panel currentScreen;
PanelApplet(){}
init(){
currentScreen = null;
changePanels(new FirstScreen("I am the First Screen"));
}
void changePanels(Panel newScreen){
if (newScreen==null) return;
if (currentScreen!=null) remove(currentScreen);
currentScreen = newScreen;
add(currentScreen);
}
}
class FirstScreen extends Panel {
Button link1,link2;
String title;
FirstScreen(String name){
super(); // calls the default panel constructor
title = name;
setBackground(Color.red);
add(link2 = new Button("Link 1"));
add(link3 = new Button("Link 2"));
}
public void paint(Graphics g){
g.drawString(title,10,10);
}
public boolean action(Event e,Object o){
PanelApplet app = (PanelApplet)getParent();
if (e.target==link1 && app!=null) {
app.changePanels(new SecondScreen("Here Via Link One",this));
}
if (e.target==link2 && app!=null) {
app.changePanels(new SecondScreen("Here Via Link Two",this));
}
return false;
}
}
class SecondScreen extends Panel {
Button back;
String title;
Panel lastScreen;
SecondScreen(String name,Panel who){
super();
title = name;
lastScreen = who;
setBackground(Color.yellow);
add(back = new Button("Back");
}
public void paint(Graphics g){
g.drawString(title,10,10);
}
public boolean action(Event e,Object o){
PanelApplet app = (PanelApplet)getParent();
if (e.target==back && app!=null) {
app.changePanels(lastScreen);
}
return false;
}
}
:::::: 'this' parameter
=======================
You will notice that when FirstScreen creates a SecondScreen, it includes the parameter 'this'.
The SecondScreen constructor is expecting a Panel there. The result is that SecondScreen
saves a pointer to the original FirstScreen in the variable 'lastScreen'.
SecondScreen later uses this pointer to restore FirstScreen. This skips the need to create
a new FirstScreen. It also means the the original FirstScreen still has its old title.
If you were to create a new FirstScreen, it could get a different string for its title.