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
 

532lounge

Mitglied
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!
 

532lounge

Mitglied
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.
Ähnliche Java Themen
  Titel Forum Antworten Datum
G Swing JFileChooser in einem JPanel? AWT, Swing, JavaFX & SWT 3
Tommy135 JFileChooser ist sehr langsam AWT, Swing, JavaFX & SWT 13
T JFileChooser ist Englisch und bleibt Englisch und bleibt Englisch... AWT, Swing, JavaFX & SWT 15
M Swing jFileChooser Header viewTypeDetails setFont AWT, Swing, JavaFX & SWT 0
I JFileChooser mit System L&F bei anderem L&F der eigtl. Anwendung AWT, Swing, JavaFX & SWT 0
Meeresgott AWT JFileChooser bestimmte Ordner anzeigen AWT, Swing, JavaFX & SWT 16
S Swing JFileChooser best. Ordner wie Dateien behandeln AWT, Swing, JavaFX & SWT 4
H Swing JFileChooser für nicht existierendes Unterverzeichnis AWT, Swing, JavaFX & SWT 3
javampir Swing Anzeige der FileFilter im JFileChooser AWT, Swing, JavaFX & SWT 0
L JFileChooser Datentyp Unterscheidung AWT, Swing, JavaFX & SWT 6
K JFileChooser NullPointerException AWT, Swing, JavaFX & SWT 7
H JFileChooser Dateinamen vorgeben (Save Dialog) AWT, Swing, JavaFX & SWT 9
Neumi5694 Swing JFilechooser - Detailansicht AWT, Swing, JavaFX & SWT 0
M JFileChooser Look and Feel AWT, Swing, JavaFX & SWT 2
T JFileChooser Rahmenfarbe ändern AWT, Swing, JavaFX & SWT 1
K Pfad mit JFileChooser ausgeben lassen AWT, Swing, JavaFX & SWT 7
C JFileChooser hängt bei Ausführung mit Terminal AWT, Swing, JavaFX & SWT 2
T Swing JFileChooser und FileView AWT, Swing, JavaFX & SWT 4
M Einzelne Ordner im JFileChooser ausgrauen? AWT, Swing, JavaFX & SWT 4
H Swing JFileChooser inline editing AWT, Swing, JavaFX & SWT 4
D JFileChooser anpassen AWT, Swing, JavaFX & SWT 5
AssELAss Verzeichnis JFileChooser aktualisieren AWT, Swing, JavaFX & SWT 0
A JFileChooser Datei speichern AWT, Swing, JavaFX & SWT 4
A Datei weiterverwenden mit JFileChooser AWT, Swing, JavaFX & SWT 6
T Importer-Auswahl im JFileChooser AWT, Swing, JavaFX & SWT 3
N JFileChooser bzw. FileDialog Problem AWT, Swing, JavaFX & SWT 10
A Swing JFileChooser - Größenänderung nach Aufruf von showOpenDialog() AWT, Swing, JavaFX & SWT 15
D Serverdirectory auf Client browsen mit JFileChooser AWT, Swing, JavaFX & SWT 7
F icon aus exe auslesen mithilfe des JFilechooser ? AWT, Swing, JavaFX & SWT 4
C JFileChooser und Netzwerk Laufwerke AWT, Swing, JavaFX & SWT 4
Iron Monkey JFileChooser - Drag and Drop AWT, Swing, JavaFX & SWT 5
J JFileChooser - Datei speichern AWT, Swing, JavaFX & SWT 7
M Element aus JList eines JFileChooser entfernen AWT, Swing, JavaFX & SWT 3
P JFileChooser mit verschidene Endungen AWT, Swing, JavaFX & SWT 12
S Swing Ordner im JFileChooser auswählen AWT, Swing, JavaFX & SWT 2
C JFileChooser bringt parent durcheinander AWT, Swing, JavaFX & SWT 2
N JFileChooser mit Dateinamenvorgabe AWT, Swing, JavaFX & SWT 9
S JFileChooser GTK (Ubuntu) "hässlich" AWT, Swing, JavaFX & SWT 2
A Swing JFileChooser mit modifiziertem Kontextmenü AWT, Swing, JavaFX & SWT 4
S JFileChooser öffnet den falschen Ordner AWT, Swing, JavaFX & SWT 4
A Swing JFilechooser zeigt verzeichnisse nicht an AWT, Swing, JavaFX & SWT 2
A Swing JFileChooser - Anzeige in Echtzeit filtern AWT, Swing, JavaFX & SWT 10
M JFileChooser umbenennen verbieten AWT, Swing, JavaFX & SWT 4
Helgon JFileChooser öffnet sich 2x AWT, Swing, JavaFX & SWT 12
K JFileChooser mit Zusatzfunktionen AWT, Swing, JavaFX & SWT 8
GUI-Programmer JFilechooser, mehrere Datein selektieren und Reihenfolge (2) AWT, Swing, JavaFX & SWT 8
V JFileChooser auf Mac und Netzwerkordner AWT, Swing, JavaFX & SWT 2
B JFileChooser breite der Spalten? AWT, Swing, JavaFX & SWT 5
M JFileChooser setCurrentDirectory() - Verzeichnis relativ zum Code/binary AWT, Swing, JavaFX & SWT 14
P Swing Dateinamen im JFileChooser vorschlagen AWT, Swing, JavaFX & SWT 11
M JFileChooser Abfangen des DateiTypen möglich?? AWT, Swing, JavaFX & SWT 5
T Swing JFileChooser --> Desktop und Laufwerke im "Suchen in" - Drop Down AWT, Swing, JavaFX & SWT 3
N JFileChooser - Keine Funtkion AWT, Swing, JavaFX & SWT 13
T JFileChooser - "Öffnen-Button" aktivieren/deaktivieren möglich??? AWT, Swing, JavaFX & SWT 2
jueki Aktuell eingestellten Filter aus einem JFileChooser abfragen. AWT, Swing, JavaFX & SWT 5
F Swing JFileChooser - Dateinamen nicht editierbar machen AWT, Swing, JavaFX & SWT 8
I Fehler bei JFileChooser AWT, Swing, JavaFX & SWT 2
K JFileChooser mehrere Dateien markieren ohne STRG AWT, Swing, JavaFX & SWT 4
Ivan Dolvich [Linux] JFileChooser sieht komisch aus... AWT, Swing, JavaFX & SWT 12
M Zurück-Button in JFileChooser AWT, Swing, JavaFX & SWT 9
N JFileChooser AWT, Swing, JavaFX & SWT 4
D Problem mit JFileChooser -> Daten werden mit anführungsstriche in JTable geschrieben AWT, Swing, JavaFX & SWT 8
S JFileChooser Dateiname Autovervollständigung AWT, Swing, JavaFX & SWT 2
B JDialog über JFileChooser anzeigen AWT, Swing, JavaFX & SWT 6
I Swing JFileChooser '\' im Pfad... AWT, Swing, JavaFX & SWT 2
K Swing JFileChooser zum Speichern - FileFilter AWT, Swing, JavaFX & SWT 2
M Swing Execption beim JFileChooser AWT, Swing, JavaFX & SWT 4
kodela Swing JFileChooser und die Datei-Extension AWT, Swing, JavaFX & SWT 3
jueki eigenen Button in JFileChooser einfügen AWT, Swing, JavaFX & SWT 7
alderwaran jFileChooser showSaveDialog, dateinamen werden mit pfadnamen überschrieben beim navigieren AWT, Swing, JavaFX & SWT 1
B Swing Suche JFileChooser zum Speichern AWT, Swing, JavaFX & SWT 2
Iron Monkey JFileChooser DIRECTORIES_ONLY AWT, Swing, JavaFX & SWT 4
Semox Swing JFileChooser: Problem Approve oder Cancel abzufangen AWT, Swing, JavaFX & SWT 7
H JTree - nach Auswahl aus JFileChooser wird nur der erste Knoten angezeigt AWT, Swing, JavaFX & SWT 3
kodela Sicherheitsabfrage mit JFileChooser AWT, Swing, JavaFX & SWT 2
DARK_ZERATO2 jFileChooser AWT, Swing, JavaFX & SWT 4
G JFileChooser Problem AWT, Swing, JavaFX & SWT 4
G Swing JFileChooser Event für neue Directory? AWT, Swing, JavaFX & SWT 5
P JFileChooser AWT, Swing, JavaFX & SWT 2
M Swing JFileChooser und JFrame AWT, Swing, JavaFX & SWT 5
J JFileChooser Dateiauswahl beim Tippen einschränken AWT, Swing, JavaFX & SWT 3
M Swing JFileChooser mit Windows 7 AWT, Swing, JavaFX & SWT 8
R JFileChooser - Initiales Verzeichnis auswählen AWT, Swing, JavaFX & SWT 8
brainray JFileChooser - es sollen nur Ordner wählbar sein AWT, Swing, JavaFX & SWT 2
T JFileChooser Problem AWT, Swing, JavaFX & SWT 3
N Mit JFileChooser ein Verzeichnis auswählen AWT, Swing, JavaFX & SWT 7
M Swing JFileChooser und versteckte Ordner AWT, Swing, JavaFX & SWT 2
F jFileChooser verwenden AWT, Swing, JavaFX & SWT 4
M Swing ImageIcon über JFileChooser einbinden AWT, Swing, JavaFX & SWT 4
F JFileChooser mal wieder AWT, Swing, JavaFX & SWT 2
ARadauer Swing JFileChooser mit Bildvorschau AWT, Swing, JavaFX & SWT 5
H Swing Dateiauswahldialog mit JFileChooser funktioniert unzuverlässig AWT, Swing, JavaFX & SWT 11
G Swing JFileChooser nur in Verzeichnis+Unterverzeichnisse AWT, Swing, JavaFX & SWT 5
K Swing JFileChooser AWT, Swing, JavaFX & SWT 6
M JFileChooser einschränken AWT, Swing, JavaFX & SWT 3
L JFileChooser braucht lang zum öffnen AWT, Swing, JavaFX & SWT 2
S NullPointerException bei JFileChooser AWT, Swing, JavaFX & SWT 8
M JFilechooser defaultdirectory AWT, Swing, JavaFX & SWT 5
C JFilechooser this.setAlwaysOnTop AWT, Swing, JavaFX & SWT 2
G JFileChooser - erkennen v. existierenden Dateien ohne Endung AWT, Swing, JavaFX & SWT 1

Ähnliche Java Themen


Oben