JFileChooser und JPanel in Java Class einbauen.

Status
Nicht offen für weitere Antworten.

532lounge

Mitglied
Hallo!

Ich habe eine Klasse, die per JMF einen Effekt über einen Videostrom legt. Das ganze funktioniert einwandfrei, wird auch in einem externen Player geöffnet. Ich will das ganze jetzt aber in ein Swing-Interface einbauen, hab da aber noch wenig Erfahrung und die Tutorials haben mir zwar ein bisschen weitergeholfen, aber nicht so ganz zum Ziel geführt.

Hier mein Code:

Code:
/*

 * 
 * Hier wird der Player als eine Processorinstanz des JMF erzeugt 
 * und das eine vom User definierte Videodatei abgespielt. Beim
 * erzeugen des Processor wird als Codec der Schneefallfilter aus
 * der Datei SnowEffect.java hinzugefügt, der dann über das Video
 * gelegt wird.
 * 
 */
import javax.swing.*;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.*;
import javax.media.control.TrackControl;
import javax.media.Format;
import javax.media.format.*;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;



public class SnowPlayer extends Frame implements ControllerListener 
{
    Processor p;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;

    public SnowPlayer() 
    {
    	super("PugIn: SnowEffect");
    }

    /**
     * Given a media locator, create a processor and use that processor
     * as a player to playback the media. During the processor's 
     * Configured state, the Snow Effect is inserted into the video track.
     **/
    public boolean open(MediaLocator ml) 
    {
		try 
		{
		    p = Manager.createProcessor(ml);
		} 
		catch (Exception e) 
		{
		    System.err.println("Failed to create a processor from the given url: " + e);
		    return false;
		}

		p.addControllerListener(this);

		// Put the Processor into configured state
		p.configure();
		if (!waitForState(p.Configured)) 
		{
		    System.err.println("Failed to configure the processor.");
		    return false;
		}
	
		// So I can use it as a player
		p.setContentDescriptor(null);
	
		// Obtain the track controls
		TrackControl tc[] = p.getTrackControls();

		if (tc == null) 
		{
		    System.err.println("Failed to obtain track controls from the processor.");
		    return false;
		}

		// Search for the track control for the video track
		TrackControl videoTrack = null;
	
		for (int i = 0; i < tc.length; i++) 
		{
		    if (tc[i].getFormat() instanceof VideoFormat) 
		    {
		    	videoTrack = tc[i];
		    	break;
		    }
		}

		if (videoTrack == null) 
		{
		    System.err.println("The input media does not contain a video track.");
		    return false;
		}

		System.err.println("Video format: " + videoTrack.getFormat());
	
		// Instantiate and set the frame access codec to the data flow path
		try 
		{
		    Codec codec[] = { new SnowEffect() };
		    videoTrack.setCodecChain(codec);
		} 
		catch (UnsupportedPlugInException e) 
		{
		    System.err.println("The processor does not support effects.");
		}

		// Realize the processor
		p.prefetch();
		if (!waitForState(p.Prefetched)) 
		{
		    System.err.println("Failed to realize the processor.");
		    return false;
		}
	
		// Display the visual & control component if there's one
		setLayout(new BorderLayout());
		Component cc;
		Component vc;
		
		if ((vc = p.getVisualComponent()) != null) 
		{
		    add("Center", vc);
		}
	
		if ((cc = p.getControlPanelComponent()) != null) 
		{
		    add("South", cc);
		}
	
		// Start the processor.
		p.start();
	
		setVisible(true);
	
		addWindowListener(new WindowAdapter() 
		{
		    public void windowClosing(WindowEvent we) 
		    {
				p.close();
				System.exit(0);
		    }
		});
		return true;
    }

    public void addNotify() 
    {
		super.addNotify();
		pack();
    }

    /**
     * Block until the processor has transitioned to the given state.
     * Return false if the transition failed.
     */
    boolean waitForState(int state) 
    {
		synchronized (waitSync) 
		{
		    try 
		    {
				while (p.getState() != state && stateTransitionOK)
				    waitSync.wait();
		    } 
		    catch (Exception e) 
		    {}
		}
		return stateTransitionOK;
    }


    /**
     * Controller Listener.
     */
    public void controllerUpdate(ControllerEvent evt) 
    {
		if (evt instanceof ConfigureCompleteEvent ||
		    evt instanceof RealizeCompleteEvent ||
		    evt instanceof PrefetchCompleteEvent) 
		{
		    synchronized (waitSync) 
		    {
				stateTransitionOK = true;
				waitSync.notifyAll();
		    }
		} 
		else if (evt instanceof ResourceUnavailableEvent) 
		{
		    synchronized (waitSync) 
		    {
				stateTransitionOK = false;
				waitSync.notifyAll();
		    }
		} 
		else if (evt instanceof EndOfMediaEvent) 
		{
		    p.close();
		    System.exit(0);
		}
    }
    	// Swing 
    private static void createAndShowGUI() {
    	JFrame.setDefaultLookAndFeelDecorated(true);
        //Erstellt das Fenster
        JFrame frame = new JFrame("Schneefall");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Beschriftung des Fensters
        JLabel label = new JLabel("Schneefall");
        frame.getContentPane().add(label);
        
        //Zeigt das Fenster an
        frame.pack();
        frame.setVisible(true);
        
        //Filechooser
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(aComponent);
        
        
        //Panels:
        JPanel bright = new JPanel(new BorderLayout());
        JPanel intens = new JPanel(new BorderLayout());
        
     

    }
    /**
     * Main program
     */
    public static void main(String [] args) 
    {
	    URL mediaURL = null;
	    MediaLocator ml;
	    
	    // Create a file chooser       
	    JFileChooser fileChooser = new JFileChooser("d:/studium/java/schnee_class");
	 
	    // Show open file dialog
	    int result = fileChooser.showOpenDialog( null );
	
	    // User chose a file
	    if ( result == JFileChooser.APPROVE_OPTION )
	    {
	    	try
	    	{
	    		// Get the file as URL
	    		mediaURL = fileChooser.getSelectedFile().toURL();
	    	} 
	    	catch ( MalformedURLException malformedURLException )
	    	{
	    		System.err.println( "Could not create URL for the file" );
	    	}
	 
	    	// Only display if there is a valid URL
	    	if ( mediaURL == null ) 
	    	{
	    		System.exit(0);
	    	}
	    	System.err.println("url = " + mediaURL);
	    }
	    
	    // Try to build a media locator
		if ((ml = new MediaLocator(mediaURL)) == null) 
		{
			System.err.println("Cannot build media locator from: " + mediaURL);
		    System.exit(0);
		}
		
		// Finally try to play the video
		SnowPlayer fa = new SnowPlayer();
		
		if (!fa.open(ml))
		{
		    System.exit(0);
		}
	
		//Swing
		  Runnable runnable = new Runnable() {
	            public void run() {
	                createAndShowGUI();
	            }
	        };
	        SwingUtilities.invokeLater(runnable);
    }
}

Jetzt weiß ich im Swing-Bereich nicht weiter, es wird weder ein Filechooser noch ein panel angezeigt. Außerdem öffnet sich das Swing-Fenster neben dem Player-Fenster... Kann mir da vielleicht jemand weiterhelfen?

Danke
 
Hab das ganze jetzt upgedatet, hab ein bisschen herumgespielt mit dem Code eines Tutorials, jetzt hüpft nicht mal mehr das Swing-Fenster auf. Muss ich denn in der Main noch etwas aufrufen, damit ich das Swing-File sehe?

Danke für jeden tipp!

Code:
// Swing 
    private static void createAndShowGUI() {
    	JFrame.setDefaultLookAndFeelDecorated(true);
        //Erstellt das Fenster
        JFrame frame = new JFrame("Schneefall");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Beschriftung des Fensters
        JLabel label = new JLabel("Schneefall");
        frame.getContentPane().add(label);
        
        //Zeigt das Fenster an
        frame.pack();
        frame.setVisible(true);
       
        //Filechooser
      /**  // Diese Aktion kreiert den Open-File Dialog
     public class OpenFileAction extends AbstractAction {
            JFrame frame;
            JFileChooser chooser;
        
            OpenFileAction(JFrame frame, JFileChooser chooser) {
                super("Open...");
                this.chooser = chooser;
                this.frame = frame;
            }
        
            public void actionPerformed(ActionEvent evt) {
                //Den Dialog anzeigen
                chooser.showOpenDialog(frame);
        
                // Die Datei auswählen
                File file = chooser.getSelectedFile();
            }
        };
        
        // This action creates and shows a modal save-file dialog.
        public class SaveFileAction extends AbstractAction {
            JFileChooser chooser;
            JFrame frame;
        
            SaveFileAction(JFrame frame, JFileChooser chooser) {
                super("Save As...");
                this.chooser = chooser;
                this.frame = frame;
            }
        
            public void actionPerformed(ActionEvent evt) {
                // Show dialog; this method does not return until dialog is closed
                chooser.showSaveDialog(frame);
        
                // Get the selected file
                File file = chooser.getSelectedFile();
            }
        };*/
        // Create a file chooser
        String filename = File.separator+"tmp";
        JFileChooser fc = new JFileChooser(new File(filename));
        
        // Create the actions
        Action openAction = new OpenFileAction(frame, fc);
        Action saveAction = new SaveFileAction(frame, fc);
        
        // Create buttons for the actions
        JButton openButton = new JButton(openAction);
        JButton saveButton = new JButton(saveAction);
        
        // Add the buttons to the frame and show the frame
        frame.getContentPane().add(openButton, BorderLayout.NORTH);
        frame.getContentPane().add(saveButton, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
        
        //Panels:

    }

Main:

Code:
	//Swing
		  Runnable runnable = new Runnable() {
	            public void run() {
	                createAndShowGUI();
	            }
	        };
	        SwingUtilities.invokeLater(runnable);
    }

Danke für jeden Tipp!
 
Also, hab das ding jetzt mal gedebugt. Hab aber noch zwei Fehler, die ich nicht wegbringe. Der Slider, sprich der intense Control Listener sollte auf die Variable maxNumPartikel aus der Klasse Snow Effect zugreifen.

Hier die Sources:

Code:
/*
 * SnowPlayer.java
 * 
 * 
 * 
 * Hier wird der Player als eine Processorinstanz des JMF erzeugt 
 * und das eine vom User definierte Videodatei abgespielt. Beim
 * erzeugen des Processor wird als Codec der Schneefallfilter aus
 * der Datei SnowEffect.java hinzugefügt, der dann über das Video
 * gelegt wird.
 * 
 */

import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.*;
import javax.media.control.TrackControl;
import javax.media.Format;
import javax.media.format.*;
import javax.swing.*;


public class SnowPlayer extends Frame implements ControllerListener 
{
    Processor p;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;

    public SnowPlayer() 
    {
    	super("PugIn: SnowEffect");
    }

    /**
     * Given a media locator, create a processor and use that processor
     * as a player to playback the media. During the processor's 
     * Configured state, the Snow Effect is inserted into the video track.
     **/
    public boolean open(MediaLocator ml) 
    {
		try 
		{
		    p = Manager.createProcessor(ml);
		} 
		catch (Exception e) 
		{
		    System.err.println("Failed to create a processor from the given url: " + e);
		    return false;
		}

		p.addControllerListener(this);

		// Put the Processor into configured state
		p.configure();
		if (!waitForState(p.Configured)) 
		{
		    System.err.println("Failed to configure the processor.");
		    return false;
		}
	
		// So I can use it as a player
		p.setContentDescriptor(null);
	
		// Obtain the track controls
		TrackControl tc[] = p.getTrackControls();

		if (tc == null) 
		{
		    System.err.println("Failed to obtain track controls from the processor.");
		    return false;
		}

		// Search for the track control for the video track
		TrackControl videoTrack = null;
	
		for (int i = 0; i < tc.length; i++) 
		{
		    if (tc[i].getFormat() instanceof VideoFormat) 
		    {
		    	videoTrack = tc[i];
		    	break;
		    }
		}

		if (videoTrack == null) 
		{
		    System.err.println("The input media does not contain a video track.");
		    return false;
		}

		System.err.println("Video format: " + videoTrack.getFormat());
	
		// Instantiate and set the frame access codec to the data flow path
		try 
		{
		    Codec codec[] = { new SnowEffect() };
		    videoTrack.setCodecChain(codec);
		} 
		catch (UnsupportedPlugInException e) 
		{
		    System.err.println("The processor does not support effects.");
		}

		// Realize the processor
		p.prefetch();
		if (!waitForState(p.Prefetched)) 
		{
		    System.err.println("Failed to realize the processor.");
		    return false;
		}
	
		// Display the visual & control component if there's one
		setLayout(new BorderLayout());
		Component cc;
		Component vc;
		
		if ((vc = p.getVisualComponent()) != null) 
		{
		    add("Center", vc);
		}
	
		if ((cc = p.getControlPanelComponent()) != null) 
		{
		    add("South", cc);
		}
	
		// Start the processor.
		p.start();
	
		setVisible(true);
	
		addWindowListener(new WindowAdapter() 
		{
		    public void windowClosing(WindowEvent we) 
		    {
				p.close();
				System.exit(0);
		    }
		});
		return true;
    }

    public void addNotify() 
    {
		super.addNotify();
		pack();
    }

    /**
     * Block until the processor has transitioned to the given state.
     * Return false if the transition failed.
     */
    boolean waitForState(int state) 
    {
		synchronized (waitSync) 
		{
		    try 
		    {
				while (p.getState() != state && stateTransitionOK)
				    waitSync.wait();
		    } 
		    catch (Exception e) 
		    {}
		}
		return stateTransitionOK;
    }


    /**
     * Controller Listener.
     */
    public void controllerUpdate(ControllerEvent evt) 
    {
		if (evt instanceof ConfigureCompleteEvent ||
		    evt instanceof RealizeCompleteEvent ||
		    evt instanceof PrefetchCompleteEvent) 
		{
		    synchronized (waitSync) 
		    {
				stateTransitionOK = true;
				waitSync.notifyAll();
		    }
		} 
		else if (evt instanceof ResourceUnavailableEvent) 
		{
		    synchronized (waitSync) 
		    {
				stateTransitionOK = false;
				waitSync.notifyAll();
		    }
		} 
		else if (evt instanceof EndOfMediaEvent) 
		{
		    p.close();
		    System.exit(0);
		}
    }


// Swing 
    //Der Change-Listener (Variable von Andreas einbauen? in Main einbauen?)
    public void stateChanged(ChangeEvent bchange) {
  	    JSlider source = (JSlider)bchange.getSource();
  	    if (source.getValueIsAdjusting()) {
  	        int brightness = (int)source.getValue();
  	    }
  	}
    
    //Der Change-Listener für die Intensität (muss an die Variable die Andreas erstellt 
    //angepasst werden!
    public void stateChanged(ChangeEvent intensechange) {
  	    JSlider source = (JSlider)intensechange.getSource();
  	    if (source.getValueIsAdjusting()) {
  	        int intensity = (int)source.getValue();
  	    }
  	}
 

    /**
     * Main program
     */
    public static void main(String [] args) 
    {
   
        	JFrame.setDefaultLookAndFeelDecorated(true);
            //Erstellt das Fenster
            JFrame frame = new JFrame("Schneefall");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            //Beschriftung des Fensters
            JLabel label = new JLabel("Schneefall");
            frame.getContentPane().add(label);
            
            //Zeigt das Fenster an
            frame.pack();
            frame.setVisible(true);

            //Menu Bar
            
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("File");
            JMenuItem menuItem = new JMenuItem("Open");
            
            menuItem.addActionListener(this);
            menu.add(menuItem); //fügt den neuen MenüItem "Open" hinzu
            menuBar.add(menu);	//fügt die neue MenüBar hinzu
            
            frame.setJMenuBar(menuBar); // Menubar dem Hauptfenster zuweisen
            
            JPanel panel = new JPanel();
            // deckend setzen
            // ist eigentlich schon der Standardwert
            panel.setOpaque(true);
            panel.setBackground(Color.yellow);
            panel.setLayout(new BorderLayout());
            panel.add(new JLabel("Datei"));
            
           
           
            //Slider für Helligkeit und Intensität
            
            //Ein Panel für Brightness erstellen und darin den Slider anbringen
            JPanel brightnessPanel = new JPanel();
            
           /** //Layout für Panel festlegen
            brightnessPanel.setLayout(newBoxLayout(brightnessPanel,BoxLayout.X_AXIS));
            static final int brightness_min = 0;
            static final int brightness_init = 70;
            static final int brightness_max = 100;
            JSlider Brightness = new JSlider(JSlider.HORIZONTAL,
                    brightness_min, brightness_init, brightness_max);
            Brightness.addChangeListener(this);

//          Spacings für markante Punkte setzen
          Brightness.setMajorTickSpacing(10);
          Brightness.setMinorTickSpacing(1);
          Brightness.setPaintTicks(true);
          Brightness.setPaintLabels(true);*/
          
     
            
          //Ein Panel für Brightness erstellen und darin den Slider anbringen
          JPanel intensePanel = new JPanel();
          
          //Layout für Panel festlegen
          intensePanel.setLayout(newBoxLayout(intensePanel,BoxLayout.X_AXIS));
          final int intense_min = 1;
          final int intense_init = 50;
          final int intense_max = 100;
          JSlider Intensity = new JSlider(JSlider.HORIZONTAL,
                  intense_min, intense_init, intense_max);
          Intensity.addChangeListener(this);
/**
//        Spacings für markante Punkte setzen
        Brightness.setMajorTickSpacing(10);
        Brightness.setMinorTickSpacing(1);
        Brightness.setPaintTicks(true);
        Brightness.setPaintLabels(true);*/
        
      
    	
    	
	    URL mediaURL = null;
	    MediaLocator ml;
	    
	    // Create a file chooser       
	    JFileChooser fileChooser = new JFileChooser("c:/eclipse/workspace/SnowPlayer/");
	 
	    // Show open file dialog
	    int result = fileChooser.showOpenDialog( null );
	
	    // User chose a file
	    if ( result == JFileChooser.APPROVE_OPTION )
	    {
	    	try
	    	{
	    		// Get the file as URL
	    		mediaURL = fileChooser.getSelectedFile().toURL();
	    	} 
	    	catch ( MalformedURLException malformedURLException )
	    	{
	    		System.err.println( "Could not create URL for the file" );
	    	}
	 
	    	// Only display if there is a valid URL
	    	if ( mediaURL == null ) 
	    	{
	    		System.exit(0);
	    	}
	    	System.err.println("url = " + mediaURL);
	    }
	    
	    // Try to build a media locator
		if ((ml = new MediaLocator(mediaURL)) == null) 
		{
			System.err.println("Cannot build media locator from: " + mediaURL);
		    System.exit(0);
		}
		
		// Finally try to play the video
		SnowPlayer fa = new SnowPlayer();
		
		if (!fa.open(ml))
		{
		    System.exit(0);
		}

			
		
    }
}

Code:
  public ArrayList<SnowParticle> particle =  new ArrayList<SnowParticle>();
    
    double[] sinTable; 					// For the swinging movement
    private int numAngle = 20;				// Swinging steps
    private int maxNumParticle;			// Number of particles maximum
    public double relNumParticle = 1;	// Control panel input: between 0.00 and 1.00
    private double countParticleDistance = 0;	// For the creation of particles
    private int countRandom = 0;		// For the costum random function
    private int gravity = 1;			// Gravity for the movement
    

    
    public SnowEffect() 
    {
        this(5);
    }

    public SnowEffect(int num) 
    {
    	// Checking borders
        if ( num <= 0 )
            this.maxNumParticle = 1;
        else
            this.maxNumParticle = num;
        
        if ( num > 50 )
        	this.maxNumParticle = 50;
        	
        // Create a look-up-table for the movement
        buildTable();
        
        inputFormats = new Format[] {
            new RGBFormat(null,
                          Format.NOT_SPECIFIED,
                          Format.byteArray,
                          Format.NOT_SPECIFIED,
                          24,
                          3, 2, 1,
                          3, Format.NOT_SPECIFIED,
                          Format.TRUE,
                          Format.NOT_SPECIFIED)
        };

        outputFormats = new Format[] {
            new RGBFormat(null,
                          Format.NOT_SPECIFIED,
                          Format.byteArray,
                          Format.NOT_SPECIFIED,
                          24,
                          3, 2, 1,
                          3, Format.NOT_SPECIFIED,
                          Format.TRUE,
                          Format.NOT_SPECIFIED)
        };
    }

    // Methods for interface Codec
    public Format[] getSupportedInputFormats()
    {
    	return inputFormats;
    }

    public Format [] getSupportedOutputFormats(Format input) 
    {
        if (input == null) 
        {
            return outputFormats;
        }
        
        if (matches(input, inputFormats) != null) 
        {
            return new Format[] { outputFormats[0].intersects(input) };
        } 
        else 
        {
            return new Format[0];
        }
    }

    public Format setInputFormat(Format input) 
    {
		inputFormat = input;
		return input;
    }

    public Format setOutputFormat(Format output) 
    {
        if (output == null || matches(output, outputFormats) == null)
            return null;
        RGBFormat incoming = (RGBFormat) output;
        
        Dimension size = incoming.getSize();
        int maxDataLength = incoming.getMaxDataLength();
        int lineStride = incoming.getLineStride();
        float frameRate = incoming.getFrameRate();
        int flipped = incoming.getFlipped();
        
        if (size == null)
            return null;
        if (maxDataLength < size.width * size.height * 3)
            maxDataLength = size.width * size.height * 3;
        if (lineStride < size.width * 3)
            lineStride = size.width * 3;
        if (flipped != Format.FALSE)
            flipped = Format.FALSE;
        
        outputFormat = outputFormats[0].intersects(new RGBFormat(size,
                                                        maxDataLength,
                                                        null,
                                                        frameRate,
                                                        Format.NOT_SPECIFIED,
                                                        Format.NOT_SPECIFIED,
                                                        Format.NOT_SPECIFIED,
                                                        Format.NOT_SPECIFIED,
                                                        Format.NOT_SPECIFIED,
                                                        lineStride,
                                                        Format.NOT_SPECIFIED,
                                                        Format.NOT_SPECIFIED));

        return outputFormat;
    }

    // For every frame
    public int process(Buffer inBuffer, Buffer outBuffer) 
    {
        int outputDataLength = ((VideoFormat)outputFormat).getMaxDataLength();

        validateByteArraySize(outBuffer, outputDataLength);

        outBuffer.setLength(outputDataLength);
        outBuffer.setFormat(outputFormat);
        outBuffer.setFlags(inBuffer.getFlags());

        byte [] inData = (byte[]) inBuffer.getData();
        byte [] outData = (byte[]) outBuffer.getData(); 

        RGBFormat vfIn = (RGBFormat) inBuffer.getFormat();
        Dimension sizeIn = vfIn.getSize();

        int iw = sizeIn.width;
        int ih = sizeIn.height;
        int ip = 0;
        int op = 0;

        updateSnow(ih, iw, true);
        	
        if ( outData.length < ih*iw*3 ) 
        {
            System.out.println("the buffer is not full");
            return BUFFER_PROCESSED_FAILED;
        }
           
        // Copy the hole input data to the output
        for ( int y = 0; y < ih; y++ )
            for ( int x = 0; x < iw; x++ )
            {
        		outData[op++] = inData[ip++];
                outData[op++] = inData[ip++];
                outData[op++] = inData[ip++];
            }

        // Replace output data by snow particles
        for (int i = 0; i < particle.size(); i++ )
        {
        	op = (int)(particle.get(i).y * iw * 3  + (particle.get(i).x +(int)particle.get(i).sinusValue) * 3);	
    		
        	outData[op++] = particle.get(i).r;		// blue
            outData[op++] = particle.get(i).g;		// green
            outData[op++] = particle.get(i).b;		// red
        	
        }

        // Count for the custom random function
        countRandom ++;
        if ( countRandom >= ih )
            countRandom = 0;
         
        // Count for the decision how many particles can be created
        countParticleDistance++;
        if (countParticleDistance/10 + relNumParticle*maxNumParticle > 1)
        	countParticleDistance = 0;
        
        return BUFFER_PROCESSED_OK;   
    }
    
    // Same content as the process methode above, but only for testing attempts.
    public int processTestModus(Buffer inBuffer, Buffer outBuffer, int ih, int iw) 
    {
    	int op = 0;	
    	int [] inData = (int[]) inBuffer.getData();  //byte  //int
        int [] outData = (int[]) outBuffer.getData(); 

        updateSnow(ih, iw, false);    

        // Copy the hole input data to the output
        for ( int i = 0; i < ih* iw; i++ )
        {       	
    		outData[i] = inData[i];
    	}
        
        // Replace output data by snow particles
        for (int i = 0; i < particle.size(); i++ )
        {
        	op = (int)(particle.get(i).y * iw + (particle.get(i).x +(int)particle.get(i).sinusValue));	

        	outData[op++] = particle.get(i).r;		// blue
            outData[op++] = particle.get(i).g;		// green
            outData[op++] = particle.get(i).b;		// red
        	
        }
        
        outBuffer.setData(outData);

        // Count for the custom random function
        countRandom ++;
        if ( countRandom >= ih )
            countRandom = 0;
                
        // Count for the decision how many particles can be created
        countParticleDistance++;
        if (countParticleDistance/10 + relNumParticle*maxNumParticle > 1)
        	countParticleDistance = 0;
        
        return BUFFER_PROCESSED_OK;
	}
    
    // Methods for interface PlugIn
    public String getName() 
    {
        return "Snow Effect";
    }

    public void open() 
    {
    }

    public void close() 
    {
    }

    public void reset() 
    {
    }

    // Methods for interface javax.media.Controls
    public Object getControl(String controlType) 
    {
    	return null;
    }

    public Object[] getControls() 
    {
    	return null;
    }


    // Utility methods
    Format matches(Format in, Format outs[]) 
    {
		for (int i = 0; i < outs.length; i++) 
		{
		    if (in.matches(outs[i]))
			return outs[i];
		}
	
		return null;
    }
    
    
    byte[] validateByteArraySize(Buffer buffer,int newSize) 
    {
        Object objectArray=buffer.getData();
        byte[] typedArray;

        // is correct type AND not null
        if (objectArray instanceof byte[]) 
        {
            typedArray=(byte[])objectArray;
            
            // is sufficient capacity
            if (typedArray.length >= newSize ) 
            {
                return typedArray;
            }

            byte[] tempArray=new byte[newSize];  // re-alloc array
            System.arraycopy(typedArray,0,tempArray,0,typedArray.length);
            typedArray = tempArray;
        } 
        else 
        {
            typedArray = new byte[newSize];
        }

        buffer.setData(typedArray);

        return typedArray;
    }

    // Creating a look up table for the oscillation of the particles
    private void buildTable() 
    {
        double tmp ;
        sinTable = new double[numAngle];
        
        for ( int i = 0; i < numAngle; i++) 
        {
        	tmp = 2 * Math.PI * ((float)i / (float)numAngle);
            sinTable[i] = Math.sin(tmp) * 3; 
        }  
    }
    
    // Moving all visible snow particles on the screen
    public void updateSnow(int height, int width, boolean random)
    {
    	int i;
    	double condition;
    	SnowParticle p;
    	
    	// Move or erase them
    	for ( i = 0; i < particle.size(); i++ )
    	{
    		p = particle.get(i);
    		
    		p.y -= p.weight * gravity;
    		p.sinusIndex += gravity;
    		
    		if (p.sinusIndex >= numAngle)
    		{
    			p.sinusIndex = 0;
    		}
    		
    		p.sinusValue = sinTable[p.sinusIndex];
    		
    		particle.set(i, p);
    		
    		if (particle.get(i).y < 0)
    		{
    			particle.remove(i);
    			i--;	
    		}
    	}
    	
    	// Decide the number of particles to be created
    	if (maxNumParticle*relNumParticle < 1)
    	{
    		condition = relNumParticle*maxNumParticle + countParticleDistance/10 + 0.05;
    	}
    	else
    	{
    		condition = maxNumParticle*relNumParticle;
    	}
    	
    	// Create them
    	for ( i = 0; i < (int)condition; i++ )
    	{
    		p = new SnowParticle();
    		p.y = height-1;
    		p.sinusIndex = 0;
    		p.sinusValue = 0;
    		p.r = -1;
    		p.g = -1;
    		p.b = -1;
    		
    		if (random)
    		{
	    		p.sinusAmplitude = (int)(2 + customRandom(height) * 4);
	    		p.weight = (int)(1 + customRandom(height) * 3);
	    		p.x = (int)(5 + customRandom(height) * (width - 10));
    		}
    		else
    		{
	    		p.sinusAmplitude = (int)(2 + i/condition * 4);
	    		p.weight = (int)(1 + i/condition * 3);
	    		p.x = (int)(5 + i/condition * (width - 10));
    		}
    		
        	particle.add(p);
    	}
    }
    
    // A better random function than the default
    private double customRandom(int value)
    {
    	double r;

    	r = countRandom % ((int)(value/20));
    	r = Math.cos((r / 21) * Math.random())* Math.random();
    	return r;
    }
}

Kann mir jemand helfen, meinen Fehler zu finden? Die Fehlermeldung lautet:

Cannot use this in a static context
The method newBoxLayout(JPanel, int) is undefined for the type SnowPlayer
Cannot use this in a static context

at SnowPlayer.main(SnowPlayer.java:248)

Wie kann ich auf die Variable zugreifen? Bin absoluter Neebie in Swing, ich weiß ich verlange viel, aber bitte kann mir jemand helfen?

Danke vielmals...
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Zurück
Oben