NiceLayoutApplet.java

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

public class NiceLayoutApplet 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 BorderLayout());
    
    // Bereich mit FlowLayout für Label und Button
    JPanel upperPanel = new JPanel(new BorderLayout()); 
    upperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    p.add(upperPanel, BorderLayout.NORTH);
    
    title = new JLabel("Such was aus:", JLabel.CENTER);
    title.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    upperPanel.add(title, BorderLayout.WEST);  // ins upperPanel
    
    selection = new JComboBox(courses);
    selection.addActionListener(new MySelectionListener());
    p.add(selection, BorderLayout.CENTER);
    
    JButton button = new JButton("Drück mich!");
    button.addActionListener(new MyButtonListener());
    upperPanel.add(button, BorderLayout.EAST);  // ins upperPanel
  }
  
  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]);
      }
    }
  }
}