EventApplet.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventApplet extends JApplet {
protected JLabel title;
protected JComboBox selection;
protected String[] courses = {"Physik", "Informatik", "Thermodynamik"};
protected String[] sweets = {"Eis", "Pudding", "Schokolade"};
protected String[] answer = {"Prima!", "Bravo!", "Sehr schön!"};
protected boolean isSweet = false; // zeigt, welche Liste angezeigt wird
public void init() {
// Fenster mit ein paar Bedienungselementen
Container p = getContentPane();
p.setLayout(new FlowLayout());
title = new JLabel("Such was aus:");
p.add(title);
selection = new JComboBox(courses);
selection.addActionListener(new MySelectionListener());
p.add(selection);
JButton button = new JButton("Drück mich!");
button.addActionListener(new MyButtonListener());
p.add(button);
}
protected void switchList() {
// tauscht Liste der ComboBox aus
// Bestimmung der neuen Liste
String[] newList;
if (isSweet) {
newList = courses;
isSweet = false;
} else {
newList = sweets;
isSweet = true;
}
selection.removeAllItems(); // löscht alle alten Einträge
for (int i = 0; i < newList.length; i++) {
selection.addItem(newList[i]);
}
}
class MyButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// tauscht Liste der ComboBox aus
switchList();
}
}
class MySelectionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// ändert das Label je nach Auswahl
int nr = selection.getSelectedIndex();
if (nr != -1) { // geschieht beim Wechsel der Liste!
title.setText(answer[nr]);
}
}
}
}