【Error record】Java AWT graphical interface programming setting keyboard event does not respond (setting keyboard event | keyboard event must be set to Frame / JFrame object)





1. Error message



To achieve a requirement, press the number button to make the image drawn in the Canvas canvas scale according to the pressed value;

In the AWT custom Canvas component, add a key event, and the keyPressed function in the KeyAdapter defined below does not call back;

        addKeyListener(new KeyAdapter() {
    
    
            @Override
            public void keyPressed(KeyEvent e) {
    
    
                if (e.getKeyCode() >= KeyEvent.VK_NUMPAD1 && e.getKeyCode() <= KeyEvent.VK_NUMPAD9) {
    
    
                    // 根据按键计算出缩放比例
                    scale = e.getKeyCode() - 96;

                    // 基于鼠标位置和比例, 计算最新的偏移
                    restore();
                    repaint();  // 重新绘制画布
                }
            }
        });

The blog code with the problem: [Java AWT Graphical Interface Programming] Use the small keyboard keys to zoom the background image drawn in the Canvas canvas (keyboard key monitoring + drawing a large image + mouse dragging + mouse wheel zooming + the current mouse pointer position as the zoom center example) ;





Two, the solution



Mouse events can be added to specific Component components,

However, any event involving the keyboard must be added to the top-level component, that is, the window component, such as: Frame / JFrame component, to take effect;

Otherwise, the above situation will occur, and the KeyAdapter / KeyListener set for the component will listen, and the corresponding callback function will not be called back at all;

Set the KeyAdapter / KeyListener listener to the JFrame window, and press the corresponding key in the application at this time, and the keyPressed function will be called back;

    public void initKeyListener(JFrame frame) {
    
    
        frame.addKeyListener(new KeyAdapter() {
    
    
            @Override
            public void keyPressed(KeyEvent e) {
    
    
                if (e.getKeyCode() >= KeyEvent.VK_NUMPAD1 && e.getKeyCode() <= KeyEvent.VK_NUMPAD9) {
    
    
                    // 根据按键计算出缩放比例
                    scale = e.getKeyCode() - 96;

                    // 基于鼠标位置和比例, 计算最新的偏移
                    restore();
                    repaint();  // 重新绘制画布
                }
            }
        });
    }

Call the keyboard key monitoring set by JFrame#addKeyListener(new KeyAdapter(){}) to achieve the desired function;

JFrame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) { }
});

Guess you like

Origin blog.csdn.net/han1202012/article/details/130563127