Java用箭头键在gui中移动圆

Java用箭头键在gui中移动圆,第1张

Java用箭头键在gui中移动圆

实际上,这是您要添加

Window
到的内容
Jframe
,但重点是
Jframe
,因此,当您键入内容
Keyboard
时,该内容
Jframe
KeyListener
转到与
Window
类无关的内容。因此,为了克服它,你只需要调用
requestFocusInWindow()
Window
类的对象。试试这个代码,我已经对EDT和东西做了一些修改。

import java.awt.*;import java.awt.event.*;import java.awt.geom.Ellipse2D;import javax.swing.*;public class Window extends JPanel {    private static Ellipse2D.Double circle;    private Jframe frame;    public Window() {        super();        int width = 400;        int height = 400;        circle = new Ellipse2D.Double(0.5 * width, 0.9 * height,     0.1 * width, 0.05 * height); }    public Dimension getPreferredSize()    {        return (new Dimension(frame.getWidth(), frame.getHeight()));    }    @Override    protected void paintComponent(Graphics g) {        super.paintComponents(g);        Graphics2D brush = (Graphics2D) g;        int width = getWidth();        int height = getHeight();        g.clearRect(0, 0, width, height);        brush.setRenderingHint(RenderingHints.KEY_ANTIALIASING,     RenderingHints.VALUE_ANTIALIAS_ON);        brush.draw(circle);    }    public class MoveCircle implements KeyListener {        @Override        public void keyPressed(KeyEvent e) { System.out.println("Working on top!"); if (e.getKeyCode() == Event.ENTER) {     System.out.println("Working on bottom!");     double newX = circle.x - 1;     circle.x = newX;     repaint(); }        }        @Override        public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub        }        @Override        public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub        }    }    private void createAndDisplayGUI(Window window)    {        frame = new Jframe();        Container container = frame.getContentPane();    container.add(window);        window.addKeyListener(new MoveCircle());     frame.setSize(800, 700);        frame.setDefaultCloseOperation(Jframe.DISPOSE_ON_CLOSE);        frame.setVisible(true);        window.requestFocusInWindow();    }    public static void main(String[] args) {        SwingUtilities.invokeLater(new Runnable()        { public void run() {     Window window = new Window();     window.createAndDisplayGUI(window); }        });    }}


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存