KeyListener

0

Witam, mam zrobić, że po wciśnięciu przycisku - powiedzmy 'a' - coś się dzieje, chciałem zrobić analogicznie jak z obsługą myszy, bo tam mi wszystko działa, natomiast w klawiaturze nie. Kody poniżej:

deklarowane na początku

	MovingAdapter ma = new MovingAdapter();
        KeyboardAdapter ka = new KeyboardAdapter();

        addMouseMotionListener(ma);
        addMouseListener(ma);
        addKeyListener(ka);

to nie działa

class KeyboardAdapter extends KeyAdapter{
    	
    	public void keyPressed(KeyEvent e)
    	{
    		if(e.getKeyCode() == KeyEvent.VK_A)
    		{
    			instrukcja..
    		}
    	}
    	
    }

a to działa

    class MovingAdapter extends MouseAdapter {


        
        public void mousePressed(MouseEvent e){
        	
        if(e.getButton() == MouseEvent.BUTTON1)
        {
        	instrukcja....
	}
}
0

Ale Twoja klasa KeyboardAdapter jest spoko. Dodaję do frame:
frame.addKeyListener(new KeyboardAdapter()); i działa jak trzeba.

Jakie masz błędy?

package swingTest;

import java.awt.EventQueue;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

public class MainWindow {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {

			public void run() {
				try {
					MainWindow window = new MainWindow();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainWindow() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.addKeyListener(new KeyboardAdapter());
	}

	class KeyboardAdapter extends KeyAdapter {

		public void keyPressed(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_A) {
				System.out.println("Wciśnięto 'A'");
			}
		}

	}
}

0

Coś pozmieniałem i zobaczyłem, że jeśli umieszczę addKeyListener w metodzie initUI na dole kodu + przerzucę do klasy MovingScalingEx tą metodę odpowiadającą za klikanie liter na klawiaturze to działa. Natomiast tak jak ja mam, czyli w klasie Surface mi nie działa. Pozaznaczałem miejsca o których mówię.

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


class Surface extends JPanel {

	ZRectangle zrect;
	
	String colorAnswer;
	ArrayList<ZRectangle> shapes = new ArrayList<ZRectangle>();
	int rgb[] = new int[3];
	
	public Surface() {

        initUI();
    }
    
    private void initUI() {
        
       
        addMouseMotionListener(new MovingAdapter());
        addMouseListener(new MovingAdapter());
        addKeyListener(new KeyboardAdapter());//<--------------------------------------------------------------
       
       
   
        zrect = new ZRectangle(50,50,50,50);
        shapes.add(zrect);
        zrect = new ZRectangle(65,65,50,50);
        shapes.add(zrect);
        zrect = new ZRectangle(85,85,50,50);
        shapes.add(zrect);
    }
 
    private void doDrawing(Graphics g) {
        
        Graphics2D g2d = (Graphics2D) g;
        
        Font font = new Font("Serif", Font.BOLD, 40);
        g2d.setFont(font);
        
        for(ZRectangle x: shapes)
        {
	        if(x.isActive == 0)
	        {
	        	g2d.setPaint(new Color(0, 0, 200));
	        	g2d.draw(x); 
	        }
	        else if(x.isActive == 1)
	        {
	        	g2d.setPaint(new Color(rgb[0], rgb[1], rgb[2]));
	        	g2d.fill(x); 
	        }
        }
    }

    public void paintComponent(Graphics g) {
       
        
    	super.paintComponent(g);
        doDrawing(g);        
    }

    class ZRectangle extends Rectangle2D.Float {

    	..
    }

    class KeyboardAdapter extends KeyAdapter{//<-------------------------------------------------------------------------
    	
    	public void keyPressed(KeyEvent e)
    	{
    		if(e.getKeyCode() == KeyEvent.VK_A)
    		{
    			zrect = new ZRectangle(150,150,50,50);
    	        shapes.add(zrect);
    	        repaint();
    		}
    	}
    	
    }
    
    class MovingAdapter extends MouseAdapter {

        private int x;
        private int y;
       
        
        public void mousePressed(MouseEvent e){
        	
       ..
   }

        @Override
        public void mouseDragged(MouseEvent e) {

           ..
        }   
        
        private void doMove(MouseEvent e) {
            ..
        }
        
        private void checkingRGB(String colorAnswer, int rgb[]){
        	
        	...
        	
        }
        
          }

   
    
    
}

public class MovingScalingEx extends JFrame {
    
	public MovingScalingEx() {
        
        initUI();
    }
    
    private void initUI() {
        
        add(new Surface());

        setTitle("Moving and scaling");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); 
	//tu wrzuciłem addKeyListener <------------------------------------------------------------------
    }

	tu wrzuciłem metodę od klikania na klawiaturze <-----------------------------------------------

    public static void main(String[] args) {        
        
                MovingScalingEx ex = new MovingScalingEx();
                ex.setVisible(true);
            }

}
0

Zobacz, że działa dla JFrame, a dla JPanel nie.

Spróbuj ustawić w ten sposób:

JPanel panel = new JPanel();
panel.setFocusable(true); // ustaw ten parametr w Twojej klasie Surface
panel.addKeyListener(new KeyboardAdapter());
0

Wszystko działa jak powinno, dziękuję bardzo!

1 użytkowników online, w tym zalogowanych: 0, gości: 1