Auf Thema antworten

Das Ganze noch mal mit einem Teil von deinem Code, etwas objektorientierter und mit CardLayout umgebaut. Das könnte so aussehen:


Das Applet:

[code=Java]import javax.swing.*;

import javax.imageio.*;

import java.awt.*;

import java.net.*;

import java.io.*;

import java.awt.event.*;



public class PictureApplet extends JApplet implements ActionListener {

   private Image image;

   private TestPanel tp;

   private MyContentPane cp;

   private JPanel cards;


   public void init() {

      setLayout(new BorderLayout());

      try {

         image = ImageIO.read(new URL(getCodeBase(), "Bild.jpg"));

      }

      catch(IllegalArgumentException iae) {

         JOptionPane.showMessageDialog(this, "Grafikdatei nicht gefunden!");

      }

      catch(IOException ioe) {

         JOptionPane.showMessageDialog(this, "Fehler beim Einlesen der Grafikdatei!");

      }

     

      cards = new JPanel(new CardLayout());


      cp = new MyContentPane(this, image);

      cards.add(cp, "MyContentPane");

     

      tp = new TestPanel(this);

      cards.add(tp, "TestPanel");

     

      add(cards, BorderLayout.CENTER);

   }

  

   public void actionPerformed(ActionEvent e) {

      JButton source = (JButton)e.getSource();

      if(source.getText().equals("GEIL")) {

         showMyContentPane();

      }

      else if(source.getText().equals("Klicken!")) {

         showTestPanel();

      }

   }

  

   public void showTestPanel() {

      CardLayout cl = (CardLayout)(cards.getLayout());

      cl.show(cards, "TestPanel");

   }

  

   public void showMyContentPane() {

      CardLayout cl = (CardLayout)(cards.getLayout());

      cl.show(cards, "MyContentPane");

   }


}[/code]


Das MyContentPane:

[code=Java]import java.awt.*;

import java.awt.event.*;

import javax.swing.*;


public class MyContentPane extends JPanel {

    private Image image;

   

    public MyContentPane(PictureApplet pa, Image image) {

        this.image = image;

        setLayout(new GridBagLayout());

        JButton b = new JButton("Klicken!");

        b.addActionListener(pa);


        add(b);

    }


    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        if (image != null) {

            g.drawImage(image, 0, 0, this);

        }

    }



}[/code]


und das TestPanel:

[code=Java]import java.awt.*;

import java.awt.event.*;

import javax.swing.*;


public class TestPanel extends JPanel {


    public TestPanel(PictureApplet pa) {

        setLayout(new BorderLayout());

        JButton bt = new JButton("GEIL");

        bt.addActionListener(pa);


        add(bt, BorderLayout.SOUTH);

    }


}[/code]


Wenn ich jetzt keine Fehler eingebaut habe, sollte das so funktionieren.



Oben