Obsługa zdarzeń klawiatury

Kody źródłowe z odcinka

package pl.am.swing.zdarzenia5;

import javax.swing.*;
import java.awt.*;

public class MyFrame extends JFrame {

    public MyFrame() {
        setTitle("Zdarzenia klawiatury");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 600);

        MyComponent myComponent = new MyComponent();
        add(myComponent);
        addKeyListener(new MyKeyListener(myComponent));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            MyFrame myFrame = new MyFrame();
            myFrame.setVisible(true);
        });

    }
}
package pl.am.swing.zdarzenia5;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MyComponent extends JComponent {

    public MyComponent() {
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                MyRectangle.X = e.getX();
                MyRectangle.Y = e.getY();

                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D graphics2D = (Graphics2D) g;

        Point point = new Point(MyRectangle.X -100, MyRectangle.Y -100);
        Dimension dimension = new Dimension(200, 200);

        Rectangle rectangle = new Rectangle(point, dimension);
        graphics2D.fill(rectangle);


    }
}
package pl.am.swing.zdarzenia5;

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

public class MyKeyListener extends KeyAdapter {

    private MyComponent myComponent;

    public MyKeyListener(MyComponent myComponent) {
        this.myComponent = myComponent;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        switch (keyCode) {
            case KeyEvent.VK_LEFT -> MyRectangle.X--;
            case KeyEvent.VK_RIGHT -> MyRectangle.X++;
            case KeyEvent.VK_UP -> MyRectangle.Y--;
            case KeyEvent.VK_DOWN -> MyRectangle.Y++;
        }

        myComponent.repaint();
    }

}
package pl.am.swing.zdarzenia5;

public class MyRectangle {
    public static int X = 500;
    public static int Y = 300;
}

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *