KeyListener aus anderer Klasse hinzufügen

SkonroX

Aktives Mitglied
Hallo,

ich habe folgendes problem:
ich habe ein JFrame, welches als erstes normal als Menü benutzt wird (1 JLabel, 4 JButton), nach drücken der entsprechenden Buttons zum starten des spiels soll es direkt auf die BufferStrategy umspringen -> funktioniert wunderbar, doch wenn man eine taste drücken möchte passiert einfach nix, ebenso nicht wenn der fokus des fensters umspringt, was eine pausierung des spiels bewirken soll, d.h. der KeyListener und der WindowFocusListener wird nicht hinzugefügt, wobei der code durchlaufen wird (geprüft), wo kann das problem noch liegen??

lg
 
Hauptklasse:
Java:
private void InitializeFrame()
	{
		MainFrame							= new JFrame( "Snake Ultimate" );
		MainFrame.setSize					( new Dimension( 640, 480 ) );
		MainFrame.setDefaultCloseOperation	( 0 );
		MainFrame.setUndecorated			( true );
		MainFrame.setResizable				( false );
		MainFrame.setLocation				( new Point( GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().x - 320,
				GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().y - 240 ) );
		MainFrame.setVisible				( true );
	}
private void InitializeInterface()
	{
		Container Panel					= MainFrame.getContentPane();
		FirstButton 					= new JButton();
		SecondButton 					= new JButton();
		ThirdButton 					= new JButton();
		BackButton						= new JButton();
		Titel 							= new JLabel();
		FirstButton.setBounds			( new Rectangle(  70, 125, 500, 60 ) );
		SecondButton.setBounds			( new Rectangle(  70, 225, 500, 60 ) );
		ThirdButton.setBounds			( new Rectangle(  70, 325, 500, 60 ) );
		BackButton.setBounds			( new Rectangle( 450, 425, 150, 35 ) );
		Titel.setBounds					( new Rectangle(   0,  15, 640, 55 ) );
		FirstButton.setVisible			( false );
		SecondButton.setVisible			( false );
		ThirdButton.setVisible			( false );
		BackButton.setVisible			( false );
		FirstButton.setBackground		( Color.BLACK );
		Panel.setBackground				( Color.BLACK );
		SecondButton.setBackground		( Color.BLACK );
		ThirdButton.setBackground		( Color.BLACK );
		BackButton.setBackground		( Color.BLACK );
		FirstButton.setForeground		( Color.RED );
		SecondButton.setForeground		( Color.RED );
		ThirdButton.setForeground		( Color.RED );
		BackButton.setForeground		( Color.RED );
		Titel.setForeground				( Color.RED );
		FirstButton.setFont				( new Font( "Monospaced", Font.ITALIC, 32 ) );
		SecondButton.setFont			( new Font( "Monospaced", Font.ITALIC, 32 ) );
		ThirdButton.setFont				( new Font( "Monospaced", Font.ITALIC, 32 ) );
		BackButton.setFont				( new Font( "Monospaced", Font.ITALIC, 22 ) );
		Titel.setFont				   	( new Font( "Geneva", Font.BOLD, 48 ) );
		Titel.setHorizontalAlignment   	( SwingConstants.CENTER );
		Titel.setHorizontalTextPosition	( SwingConstants.CENTER );
		Panel.setLayout					( null );
		FirstButton.addActionListener	( new java.awt.event.ActionListener()
		{
			public void actionPerformed( java.awt.event.ActionEvent e )
			{ 
				new menu( FirstButton.getText() ); 
			}
		} );
		SecondButton.addActionListener( new java.awt.event.ActionListener()
		{
			public void actionPerformed( java.awt.event.ActionEvent e )
			{ 
				new menu( SecondButton.getText() ); 
			}
		} );
		ThirdButton.addActionListener( new java.awt.event.ActionListener()
		{
			public void actionPerformed( java.awt.event.ActionEvent e ) 
			{
				new menu( ThirdButton.getText() );
			}
		} );
		BackButton.addActionListener( new java.awt.event.ActionListener()
		{
			public void actionPerformed( java.awt.event.ActionEvent e )
			{
				if( Titel.getText().equals( "Snake Ultimate" ) )
					System.exit( 0 );
				else
					new menu( Titel.getText() + "2" );
			}
		} );
		Panel.add( Titel, null );
		Panel.add( FirstButton, null );
		Panel.add( SecondButton, null );
		Panel.add( ThirdButton, null );
		Panel.add( BackButton, null );
		new menu( "MainMenu" );
	}
und dann ingame:
Java:
private void InitializeFrame() 
	{
		//JOptionPane.showMessageDialog( null, "Controls:\nUp - Move Up\nLeft - Move Left\nDown - Move Down" +
		//		"\nRight - Move Right\nR - Restart\nESC - Pause / Exit");
		Frame.setSize( SnakeApplication.Resolution );
		Frame.setCursor( Toolkit.getDefaultToolkit().createCustomCursor( new BufferedImage( 
				1, 1, BufferedImage.TYPE_4BYTE_ABGR ), new Point( 0,0 ), "NOCURSOR" ) );
		Frame.setLocation( new Point( GraphicsEnvironment.getLocalGraphicsEnvironment()
				.getCenterPoint().x - ( Frame.getSize().width / 2 ), GraphicsEnvironment
				.getLocalGraphicsEnvironment().getCenterPoint().y - ( Frame.getSize().height / 2 ) ) );
		Frame.addKeyListener		 ( new Listener() );
		Frame.addWindowFocusListener ( new Listener() );
	}
Wobei frame das MainFrame aus der anderen Klasse ist.
Dazu laufen eben noch die Graphics drüber ingame.

lg
 
Variablennamen schreibt man klein, und statt setLocation kannst du setLocationRelativeTo verwenden.
Das mit KeyListener und GUI-Elementen ist so eine Sache. Der KeyListener funktioniert nur an dem Komponenten, der derzeit den Focus hat. Deshalb versuche als Erste mal, einfach nur requestFocus aufzurufen, nach dem du fertig bist.
 
Schönheitsfehler sind erstmal nebensächlich, dazu hab ich das mit .requestFocus bereits probiert, ich habe sogar schon versucht getrennte JPanels und JFrames zu verwenden, beides ohne erfolg, nun bin ich dabei zwar ein JFrame für beides zu nutzen, dafür bereits in der ersten klasse direkt die listener zu implementieren, sodass es nicht nachträglich gemacht werden muss.
Jedoch ohne erfolg.
 
Das funktioniert ohne Probleme:

Java:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class Excercise2
{
	private static JFrame MainFrame;
	private static JButton FirstButton;
	private static JButton SecondButton;
	private static JButton ThirdButton;
	private static JButton BackButton;
	private static JLabel Titel;
		
	public static void main(String[] args)
    {
        MainFrame                           = new JFrame( "Snake Ultimate" );
        MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MainFrame.setSize                   ( new Dimension( 640, 480 ) );
        MainFrame.setResizable              ( false );
        MainFrame.setLocation( new Point( GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().x - 320,
                GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().y - 240 ) );
        InitializeInterface();
    }
	private static void InitializeInterface()
    {
        Container Panel                 = MainFrame.getContentPane();
        FirstButton                     = new JButton("Button");
        SecondButton                    = new JButton();
        ThirdButton                     = new JButton();
        BackButton                      = new JButton();
        Titel                           = new JLabel();
        FirstButton.setBounds           ( new Rectangle(  70, 125, 500, 60 ) );
        SecondButton.setBounds          ( new Rectangle(  70, 225, 500, 60 ) );
        ThirdButton.setBounds           ( new Rectangle(  70, 325, 500, 60 ) );
        BackButton.setBounds            ( new Rectangle( 450, 425, 150, 35 ) );
        Titel.setBounds                 ( new Rectangle(   0,  15, 640, 55 ) );
        SecondButton.setVisible         ( false );
        ThirdButton.setVisible          ( false );
        BackButton.setVisible           ( false );
        FirstButton.setBackground       ( Color.BLACK );
        Panel.setBackground             ( Color.BLACK );
        SecondButton.setBackground      ( Color.BLACK );
        ThirdButton.setBackground       ( Color.BLACK );
        BackButton.setBackground        ( Color.BLACK );
        FirstButton.setForeground       ( Color.RED );
        SecondButton.setForeground      ( Color.RED );
        ThirdButton.setForeground       ( Color.RED );
        BackButton.setForeground        ( Color.RED );
        Titel.setForeground             ( Color.RED );
        FirstButton.setFont             ( new Font( "Monospaced", Font.ITALIC, 32 ) );
        SecondButton.setFont            ( new Font( "Monospaced", Font.ITALIC, 32 ) );
        ThirdButton.setFont             ( new Font( "Monospaced", Font.ITALIC, 32 ) );
        BackButton.setFont              ( new Font( "Monospaced", Font.ITALIC, 22 ) );
        Titel.setFont                   ( new Font( "Geneva", Font.BOLD, 48 ) );
        Titel.setHorizontalAlignment    ( SwingConstants.CENTER );
        Titel.setHorizontalTextPosition ( SwingConstants.CENTER );
        Panel.setLayout                 ( null );
        FirstButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e )
            {
            	InitializeFrame2(MainFrame);
            }
        });
        Panel.add( Titel, null );
        Panel.add( FirstButton, null );
        Panel.add( SecondButton, null );
        Panel.add( ThirdButton, null );
        Panel.add( BackButton, null );
        
        MainFrame.setVisible(true);
    }
	private static void InitializeFrame2(JFrame Frame) 
    {
        Frame.addKeyListener(new Listener());
        Frame.requestFocus();
    }	
	public static class Listener implements KeyListener
	{

		@Override
		public void keyTyped(KeyEvent e)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public void keyPressed(KeyEvent e)
		{
			System.out.println("lol");
		}

		@Override
		public void keyReleased(KeyEvent e)
		{
			// TODO Auto-generated method stub

		}

	}
}
 
Ich hab es nochmal versucht, funktioniert nicht..
Java:
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
public class SnakeApplication
{
	public static JLabel				Titel				= null;
	public static JButton				FirstButton			= null,
										SecondButton		= null,
										ThirdButton 		= null,
										BackButton			= null;
	public static JFrame				MainFrame			= new JFrame( "Snake Ultimate" ),
										GameFrame			= new JFrame( "Snake Ultimate INGAME" );
	public static String				Difficulty			= "Medium";
	public static Graphics				Graphics 			= null;
	public static boolean 				Vsync				= true;
	public static Dimension				Resolution			= new Dimension( 1280, 900 );
	public static BufferStrategy		BufStrat			= null;
	public static void main( String[] args )
	{
		new SnakeApplication();
	}
	public SnakeApplication()
	{
		InitializeFrames();
		if( JOptionPane.showConfirmDialog(null, "Snake mit Menü Starten?", "Snake Ultimate", JOptionPane.YES_NO_OPTION) == 0 )
			InitializeInterface();
		else
			new SnakeGame();
	}
	private void InitializeFrames()
	{
		MainFrame.setSize						( new Dimension( 640, 480 ) );
		MainFrame.setDefaultCloseOperation		( 0 );
		GameFrame.setDefaultCloseOperation		( 0 );
		MainFrame.setUndecorated				( true );
		GameFrame.setUndecorated				( true );
		MainFrame.setResizable					( false );
		GameFrame.setResizable					( false );
		MainFrame.getContentPane().setLayout	( null );
		MainFrame.getContentPane().setBackground( Color.BLACK );
		MainFrame.setLocation					( new Point( GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().x - 320,
													GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().y - 240 ) );
		GameFrame.setCursor						( Toolkit.getDefaultToolkit().createCustomCursor( new BufferedImage( 
													1, 1, BufferedImage.TYPE_4BYTE_ABGR ), new Point( 0,0 ), "NOCURSOR" ) );
		MainFrame.setVisible					( true );
	}
	public static void InitializeFrame2()
	{
		GameFrame.setSize					( Resolution );
		GameFrame.setLocation				( new Point( GraphicsEnvironment.getLocalGraphicsEnvironment()
												.getCenterPoint().x - ( GameFrame.getSize().width / 2 ), GraphicsEnvironment
												.getLocalGraphicsEnvironment().getCenterPoint().y - ( GameFrame.getSize().height / 2 ) ) );
		GameFrame.addKeyListener			( new Listener() );
		GameFrame.addWindowFocusListener	( new Listener() );
		GameFrame.requestFocus();
		GameFrame.setVisible				( true );
		GameFrame.createBufferStrategy		( 2 );
		BufStrat 							= GameFrame.getBufferStrategy();
	}
	private void InitializeInterface()
	{
		Container Panel					= MainFrame.getContentPane();
		FirstButton 					= new JButton();
		SecondButton 					= new JButton();
		ThirdButton 					= new JButton();
		BackButton						= new JButton();
		Titel 							= new JLabel();
		FirstButton.setBounds			( new Rectangle(  70, 125, 500, 60 ) );
		SecondButton.setBounds			( new Rectangle(  70, 225, 500, 60 ) );
		ThirdButton.setBounds			( new Rectangle(  70, 325, 500, 60 ) );
		BackButton.setBounds			( new Rectangle( 450, 425, 150, 35 ) );
		Titel.setBounds					( new Rectangle(   0,  15, 640, 55 ) );
		FirstButton.setVisible			( false );
		SecondButton.setVisible			( false );
		ThirdButton.setVisible			( false );
		BackButton.setVisible			( false );
		FirstButton.setBackground		( Color.BLACK );
		SecondButton.setBackground		( Color.BLACK );
		ThirdButton.setBackground		( Color.BLACK );
		BackButton.setBackground		( Color.BLACK );
		FirstButton.setForeground		( Color.RED );
		SecondButton.setForeground		( Color.RED );
		ThirdButton.setForeground		( Color.RED );
		BackButton.setForeground		( Color.RED );
		Titel.setForeground				( Color.RED );
		FirstButton.setFont				( new Font( "Monospaced", Font.ITALIC, 32 ) );
		SecondButton.setFont			( new Font( "Monospaced", Font.ITALIC, 32 ) );
		ThirdButton.setFont				( new Font( "Monospaced", Font.ITALIC, 32 ) );
		BackButton.setFont				( new Font( "Monospaced", Font.ITALIC, 22 ) );
		Titel.setFont				   	( new Font( "Geneva", Font.BOLD, 48 ) );
		Titel.setHorizontalAlignment   	( SwingConstants.CENTER );
		Titel.setHorizontalTextPosition	( SwingConstants.CENTER );
		FirstButton.addActionListener	( new Listener() );
		SecondButton.addActionListener	( new Listener() );
		ThirdButton.addActionListener	( new Listener() );
		BackButton.addActionListener	( new Listener() );
		Panel.add						( Titel, null );
		Panel.add						( FirstButton, null );
		Panel.add						( SecondButton, null );
		Panel.add						( ThirdButton, null );
		Panel.add						( BackButton, null );
		new menu						( "MainMenu" );
	}
}
 
Ich hatte mit Listener noch nie echte Probleme. Und ich bin echt nicht das, was man unter einen guten Coder verstehen könnte. 🙄

Der Code funktioniert bei mir wieder problemlos. Der Reihe nach, was ich gemacht habe: Das Else im Konstruktor auskommentiert, das GameFrame.setUndecorated in InitializeFrames auskommentiert, in ...2 das setSize auf nur 100x100 gesetzt, addWindowFocusListener auskommentiert und GameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); hinzugefügt, im InitializeInterface() FirstButton.setVisible auskommentiert und den Button mit new JButton("Start"); intialisiert, einen anonymen Listener hinzugefügt der InitializeFrame2(); aufruft und die restlichen addActionListener aller Buttons auskommentiert. Am Ende noch new menu entfernt. Dann noch eine Klasse namens Listener die den KeyListener implementiert geschrieben und irgendeine Standartausgabe gemacht. Funktioniert tadellos.

Du musst wohl etwas mehr Code zeigen, das wir es ohne jegliche Veränderung testen können. Womöglich habe ich die Fehlerquelle unbemerkt entfernt, aber ohne die Änderungen ging es natürlich nicht. ^^
 
Ich würde mich da echt von der Lösung mittels KeyListener verabschieden, da dieser Dir - auch wenn es mal funktioniert - u.U. später noch Probleme bereiten kann (bzw. bei Dir gibt's ja schon Probleme)
Denke nicht, dass der KeyListener für solche Zwecke gedacht ist.

Hier mal ein Beispiel mit Key Bindings (reagiert auf Cursortasten Up & Down):
Java:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class KeyBindingDemo2 extends JFrame {
	public KeyBindingDemo2() {
		this.setContentPane(new GamePanel());
	}
	
	class GamePanel extends JPanel {
		private int x, y;
		public GamePanel() {
			Action downAction = new AbstractAction() {
			    public void actionPerformed(ActionEvent e) {
			    	y+=10;
			    }
			};
			Action upAction = new AbstractAction() {
			    public void actionPerformed(ActionEvent e) {
			    	y-=10;
			    }
			};
			InputMap inputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
			inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "downAction");
			inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "upAction");
			this.getActionMap().put("downAction", downAction);
			this.getActionMap().put("upAction", upAction);
			new Thread(new Runnable() {
				public void run() {
					while(true) {
						try {
							Thread.sleep(20);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						calculateNextPos();
					}
				}
			}).start();
		}
		
		private void calculateNextPos(){
			x+=5;
			if (x>this.getWidth())
				x=0;
			repaint();
		}
		
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.setColor(Color.BLUE);
			g.fillRect(x, y, 10, 10);
		}
	}
	
	public static void main(String[] args) {
		JFrame frame = new KeyBindingDemo2();
		frame.setBounds(0, 0, 500, 300);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}
 
Hast du die "Listener" class von Volva. benutzt?

[Java]

public static class Listener implements KeyListener
{
...


//------------------------ aus deinem Code ---

FirstButton.addActionListener ( new Listener() );
SecondButton.addActionListener ( new Listener() );
ThirdButton.addActionListener ( new Listener() );
BackButton.addActionListener ( new Listener() );


[/Java]

Das kann nicht Funktionieren.
Da Listener KeyListener implementiert und nicht ActionListener. Sollte sich nicht compilieren lassen...

ActionListener = Hört auf ACTIONS (z.B selbst geschriebene Actions)
MouseListener = Hört auf MouseEvents (z.B MouseClicked)
KeyListener = Hört auf KeyEvent (z.B A KeyPresed)

Wenn du deinen ganzen Code postet kann ich dir bestimmt helfen, mit "geht nicht" leider nicht...

Was soll den an die Buttons ????:L
 
Zuletzt bearbeitet:
okay okay,
also ich habe es folgend umschrieben:

Java:
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
public class SnakeApplication
{
	public static JLabel				Titel				= null;
	public static JButton				FirstButton			= null,
										SecondButton		= null,
										ThirdButton 		= null,
										BackButton			= null;
	public static JFrame				Frame				= new JFrame( "Snake Ultimate" );
	public static String				Difficulty			= "Medium";
	public static Graphics				Graphics 			= null;
	public static boolean 				Vsync				= true;
	public static Dimension				Resolution			= new Dimension( 1280, 900 );
	public static BufferStrategy		BufStrat			= null;
	public static JPanel				MenuPanel			= new JPanel(),
										GamePanel			= new JPanel();
	public static void main( String[] args )
	{
		new SnakeApplication();
	}
	public SnakeApplication()
	{
		InitializeFrame( MenuPanel );
		if( JOptionPane.showConfirmDialog( null, "Snake mit Menü Starten?", "Snake Ultimate", JOptionPane.YES_NO_OPTION ) == 0 )
			InitializeInterface();
		else
			new SnakeGame();
	}
	public static void InitializeFrame( JPanel Panel )
	{
		Frame.setSize						( new Dimension( 640, 480 ) );
		Frame.setDefaultCloseOperation		( 0 );
		Frame.setUndecorated				( true );
		Frame.setResizable					( false );
		Frame.setFocusable					( true );
		Frame.setContentPane				( Panel );
		Frame.getContentPane().setLayout	( null );
		Frame.getContentPane().setBackground( Color.BLACK );
		Frame.setLocation					( new Point( GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().x - 320,
												GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint().y - 240 ) );
		Frame.setVisible					( true );
		Frame.createBufferStrategy			( 2 );
		BufStrat 							= Frame.getBufferStrategy();
	}
	private void InitializeInterface()
	{
		FirstButton 					= new JButton();
		SecondButton 					= new JButton();
		ThirdButton 					= new JButton();
		BackButton						= new JButton();
		Titel 							= new JLabel();
		FirstButton.setBounds			( new Rectangle(  70, 125, 500, 60 ) );
		SecondButton.setBounds			( new Rectangle(  70, 225, 500, 60 ) );
		ThirdButton.setBounds			( new Rectangle(  70, 325, 500, 60 ) );
		BackButton.setBounds			( new Rectangle( 450, 425, 150, 35 ) );
		Titel.setBounds					( new Rectangle(   0,  15, 640, 55 ) );
		FirstButton.setVisible			( false );
		SecondButton.setVisible			( false );
		ThirdButton.setVisible			( false );
		BackButton.setVisible			( false );
		FirstButton.setBackground		( Color.BLACK );
		SecondButton.setBackground		( Color.BLACK );
		ThirdButton.setBackground		( Color.BLACK );
		BackButton.setBackground		( Color.BLACK );
		FirstButton.setForeground		( Color.RED );
		SecondButton.setForeground		( Color.RED );
		ThirdButton.setForeground		( Color.RED );
		BackButton.setForeground		( Color.RED );
		Titel.setForeground				( Color.RED );
		FirstButton.setFont				( new Font( "Monospaced", Font.ITALIC, 32 ) );
		SecondButton.setFont			( new Font( "Monospaced", Font.ITALIC, 32 ) );
		ThirdButton.setFont				( new Font( "Monospaced", Font.ITALIC, 32 ) );
		BackButton.setFont				( new Font( "Monospaced", Font.ITALIC, 22 ) );
		Titel.setFont				   	( new Font( "Geneva", Font.BOLD, 48 ) );
		Titel.setHorizontalAlignment   	( SwingConstants.CENTER );
		Titel.setHorizontalTextPosition	( SwingConstants.CENTER );
		FirstButton.addActionListener	( new Listener() );
		SecondButton.addActionListener	( new Listener() );
		ThirdButton.addActionListener	( new Listener() );
		BackButton.addActionListener	( new Listener() );
		MenuPanel.add					( Titel, null );
		MenuPanel.add					( FirstButton, null );
		MenuPanel.add					( SecondButton, null );
		MenuPanel.add					( ThirdButton, null );
		MenuPanel.add					( BackButton, null );
		new menu						( "MainMenu" );
	}
}

Java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Listener implements WindowFocusListener, ActionListener
{
	private static Action 		MoveUp 		= null,
				  				MoveDown 	= null,
				  				MoveLeft 	= null,
				  				MoveRight 	= null;
	public Listener()
	{
		InitializeInputMap();
		InitializeActions();
	}
	private static void InitializeInputMap()
	{
		ActionMap 		Actions 	= SnakeApplication.GamePanel.getActionMap();
		InputMap 		input 		= SnakeApplication.GamePanel.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW );
		input.put( KeyStroke.getKeyStroke( KeyEvent.VK_UP,    0 ),	"MoveUp" 	);
		input.put( KeyStroke.getKeyStroke( KeyEvent.VK_DOWN,  0	),	"MoveDown" 	);
		input.put( KeyStroke.getKeyStroke( KeyEvent.VK_LEFT,  0 ),	"MoveUp" 	);
		input.put( KeyStroke.getKeyStroke( KeyEvent.VK_RIGHT, 0 ),	"MoveDown" 	);
		Actions.put( "MoveUp", 		MoveUp 		);
		Actions.put( "MoveDown", 	MoveDown 	);
		Actions.put( "MoveLeft", 	MoveLeft 	);
		Actions.put( "MoveRight", 	MoveRight 	);
	}
	@SuppressWarnings( "serial" )
	private static void InitializeActions()
	{
		MoveUp = new AbstractAction()
		{
			public void actionPerformed( ActionEvent e )
			{
				if( SnakeGame.CurrentTurn != 3 )
		    		SnakeGame.CurrentTurn = 0;
			}
		};
		MoveDown = new AbstractAction()
		{
			public void actionPerformed( ActionEvent e )
			{
				if( SnakeGame.CurrentTurn != 0 )
		    		SnakeGame.CurrentTurn = 3;
			}
		};
		MoveLeft = new AbstractAction()
		{
			public void actionPerformed( ActionEvent e )
			{
				if( SnakeGame.CurrentTurn != 2 )
		    		SnakeGame.CurrentTurn = 1;
			}
		};
		MoveRight = new AbstractAction()
		{
			public void actionPerformed( ActionEvent e )
			{
				if( SnakeGame.CurrentTurn != 1 )
		    		SnakeGame.CurrentTurn = 2;
			}
		};
	}
	/*public void keyPressed( KeyEvent arg0 )
	{
		
    	
    	
    	
    	if( arg0.getKeyCode() == KeyEvent.VK_R )
    		SnakeGame.Restart();
    	if( arg0.getKeyCode() == KeyEvent.VK_ESCAPE )
    	{
    		if( SnakeGame.GameActive )
    			SnakeGame.GameActive = false;
    		else
    			System.exit( 0 );
    	}
    	if( arg0.getKeyCode() != KeyEvent.VK_ESCAPE && !SnakeGame.GameActive )
    	{
    		if( SnakeGame.ShowText.equals( "highscorebuf" ) )
    			SnakeGame.ShowText = "highscore";
    		if( SnakeGame.ShowText.equals( "gameoverbuf" ) )
    			SnakeGame.ShowText = "gameover";
    		SnakeGame.GameActive = true;
    	}
	}
	public void keyReleased( KeyEvent arg0 ){}
	public void keyTyped( KeyEvent arg0 ){}*/
	public void windowGainedFocus( WindowEvent e ){}
	public void windowLostFocus( WindowEvent e )
	{
		SnakeGame.GameActive = false;
	}
	public void actionPerformed( ActionEvent e )
	{ 
		if( e.getActionCommand().equals( "Exit" ) || e.getActionCommand().equals( "Back" ) )
			new menu( SnakeApplication.Titel.getText() + "2" );
		else
			new menu( e.getActionCommand() );
	}
}
 
In dem Code taucht viel zu viel static auf. In Deinem Fall sollte ein static und zwar das in der public static void main(...) völlig ausreichen.
In der OOP arbeitet man möglichst mit Objekten und referenzen auf diese.
In dem Code fehlt das wesentliche. Ausserdem gibt es Code Konventionen ;-)
 
Naja egal ich habe mich nun dazu entschieden einfach auch das Menü zu rendern mit dem BufferStrategy.. spart solch ein kopfzerbrechen und sieht noch besser aus 🙂
trotzdem vielen dank an alle die sich gedanken gemacht haben!

lg
 
registerKeyboardAction

Java:
 {
// Bsp.-Aufruf
registerKeyAction(rootPane, yourMoveUpAction, KeyEvent.VK_UP);
}

    public static final void registerKeyAction(final JRootPane rootPane, final Action action, final int virtualKey) {
        final KeyStroke stroke = KeyStroke.getKeyStroke(virtualKey, 0);
        rootPane.registerKeyboardAction(action, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
 
ne ne ne... das war alles in ordnung, das problem lag darin, das die endlosschleife für das spiel wenn es mittendrin ist, in einer anderen klasse als in der main-class war, sodass die listener anscheinend keine chance hatten zu reagieren
 

Zurück
Oben