如何在JFrame中使用KeyListener?

如何在JFrame中使用KeyListener?,第1张

如何在JFrame中使用KeyListener?

矩形没有移动,因为使用不

Jframe
正确。您必须分配
frame
new mainframe()
而不是忽略实例化的
mainframe
对象

@MadProgrammer指出了其他一些问题。

这是修复某些问题的代码

mainframe.java
import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.Jframe;public class mainframe extends Jframe implements KeyListener{    private mainDraw draw;    public void keyPressed(KeyEvent e) {        System.out.println("keyPressed");    }    public void keyReleased(KeyEvent e) {        if(e.getKeyCode()== KeyEvent.VK_RIGHT) draw.moveRight();        else if(e.getKeyCode()== KeyEvent.VK_LEFT) draw.moveLeft();        else if(e.getKeyCode()== KeyEvent.VK_DOWN) draw.moveDown();        else if(e.getKeyCode()== KeyEvent.VK_UP) draw.moveUp();    }    public void keyTyped(KeyEvent e) {        System.out.println("keyTyped");    }    public mainframe(){        this.draw=new mainDraw();        addKeyListener(this);        setFocusable(true);        setFocusTraversalKeysEnabled(false);    }    public static void main(String[] args) {        javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {     mainframe frame = new mainframe();     frame.setTitle("Square Move Practice");     frame.setResizable(false);     frame.setSize(600, 600);     frame.setMinimumSize(new Dimension(600, 600));     frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);     frame.getContentPane().add(frame.draw);     frame.pack();     frame.setVisible(true); }        });    }}
mainDraw.java
import java.awt.Color;import java.awt.Graphics;import javax.swing.JComponent;public class mainDraw extends JComponent {    public int x = 50;    public int y = 50;    public void paintComponent(Graphics g) {        super.paintComponent(g);        g.drawRect(x, y, 50, 50);        g.fillRect(x, y, 50, 50);        g.setColor(Color.BLACK);    }    public void moveRight() {        x = x + 5;        repaint();    }    public void moveLeft() {        x = x - 5;        repaint();    }    public void moveDown() {        y = y + 5;        repaint();    }    public void moveUp() {        y = y - 5;        repaint();    }}

顺便说一句,用于

SwingUtilities
放置gui更新代码,因为swing对象不是线程安全的。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5428184.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存