当前位置: 首页 > 知识库问答 >
问题:

如何在主类的Jframe中添加KeyListener对象的JLabel

柯波娃
2023-03-14
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.*;
import javax.swing.*;

class MKeyListener extends KeyAdapter
{
  static int n = 0;
    @Override
    public void keyPressed(KeyEvent event) 
    {
      if (event.getKeyCode() == KeyEvent.VK_ESCAPE) 
      {
        n += 1;
        if(n % 2 == 1)
        {
            
        }
        else
        {
            System.out.println("Not Quitting now");
        }
      }
      else if(event.getKeyCode() == KeyEvent.VK_ENTER && n % 2 == 1)
      {
          System.out.println("Quitting now...");
          try
          {
            Thread.sleep(200);
          }
          catch(Exception e)
          {
          }
          System.exit(0);
      }
    }
}

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

public class Main
{
    
    public static void main(String[] args) throws Exception 
    {
     JTextField textField = new JTextField();
     textField.addKeyListener(new MKeyListener());
     JFrame jframe = new JFrame();
     jframe.add(textField);
     jframe.setSize(1000, 1000);
     jframe.setTitle("First Development In JAVA Try : Day 3");
     jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     jframe.setVisible(true);
    }
}

共有1个答案

席俊驰
2023-03-14

你的问题的“基本”答案是,你需要使用某种“观察者模式”。

其目的是,你的“键处理器”将监视某种键盘输入,当某个触发发生时(按下特定的键),它将通知所有感兴趣的观察者所说的动作。

Swing称这些为“监听器”,因此,您已经看到了它们的实际操作。

    null
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.border.LineBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Map<KeyHandler.Direction, JPanel> mapPanels;
        private KeyHandler keyHandler;

        public TestPane() {
            mapPanels = new HashMap<>();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;

            add(createPanel(KeyHandler.Direction.LEFT_UP), gbc);
            gbc.gridx++;
            add(createPanel(KeyHandler.Direction.UP), gbc);
            gbc.gridx++;
            add(createPanel(KeyHandler.Direction.RIGHT_UP), gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            add(createPanel(KeyHandler.Direction.LEFT), gbc);
            gbc.gridx++;
            add(createPanel(), gbc);
            gbc.gridx++;
            add(createPanel(KeyHandler.Direction.RIGHT), gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            add(createPanel(KeyHandler.Direction.LEFT_DOWN), gbc);
            gbc.gridx++;
            add(createPanel(KeyHandler.Direction.DOWN), gbc);
            gbc.gridx++;
            add(createPanel(KeyHandler.Direction.RIGHT_DOWN), gbc);
            
            keyHandler = new KeyHandler(getInputMap(WHEN_IN_FOCUSED_WINDOW), getActionMap(), new KeyHandlerListener() {
                @Override
                public void keyHandlerDidPress(KeyHandler.Direction direction) {
                    activate(direction);
                }
            });
        }
        
        protected JPanel createPanel() {
            JPanel panel = new JPanel() {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(50, 50);
                }
            };
            panel.setBorder(new LineBorder(Color.DARK_GRAY));
            return panel;
        }

        protected JPanel createPanel(KeyHandler.Direction direction) {
            JPanel panel = createPanel();
            mapPanels.put(direction, panel);
            return panel;
        }
        
        protected void activate(KeyHandler.Direction direction) {
            JPanel panel = mapPanels.get(direction);
            panel.setBackground(Color.BLUE);
            Timer timer = new Timer(250, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    panel.setBackground(null);
                }
            });
            timer.setRepeats(false);
            timer.start();
        }

    }

    public interface KeyHandlerListener {

        public void keyHandlerDidPress(KeyHandler.Direction direction);
    }

    public class KeyHandler {

        public enum Direction {
            UP, DOWN, LEFT, RIGHT,
            LEFT_UP, RIGHT_UP,
            LEFT_DOWN, RIGHT_DOWN
        }

        public KeyHandler(InputMap inputMap, ActionMap actionMap, KeyHandlerListener listener) {
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0), "Press.leftUp");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "Press.up");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0), "Press.rightUp");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "Press.left");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "Press.right");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 0), "Press.leftDown");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, 0), "Press.down");
            inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, 0), "Press.rightDown");
            
            actionMap.put("Press.leftUp", new DirectionAction(Direction.LEFT_UP, listener));
            actionMap.put("Press.up", new DirectionAction(Direction.UP, listener));
            actionMap.put("Press.rightUp", new DirectionAction(Direction.RIGHT_UP, listener));
            actionMap.put("Press.left", new DirectionAction(Direction.LEFT, listener));
            actionMap.put("Press.right", new DirectionAction(Direction.RIGHT, listener));
            actionMap.put("Press.leftDown", new DirectionAction(Direction.LEFT_DOWN, listener));
            actionMap.put("Press.down", new DirectionAction(Direction.DOWN, listener));
            actionMap.put("Press.rightDown", new DirectionAction(Direction.RIGHT_DOWN, listener));
        }

        protected class DirectionAction extends AbstractAction {

            private Direction direction;
            private KeyHandlerListener listener;

            public DirectionAction(Direction direction, KeyHandlerListener listener) {
                this.direction = direction;
                this.listener = listener;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                listener.keyHandlerDidPress(direction);
            }

        }

    }
}
 类似资料:
  • 问题内容: 因此,我试图用()移动矩形,并且每当我尝试按下键时,矩形都不会移动。 绘制了矩形,但是每当我按和键时,都不会发生任何事情。我有两个类,一个是我的带有keyEvents和frame的主类,另一个是绘制矩形并保存用于移动矩形的函数。 这是我的代码: 现在是第二堂课: 请告诉我如何移动矩形。提前致谢! 问题答案: 矩形没有移动,因为使用不正确。您必须分配给而不是忽略实例化的对象。 @MadP

  • 我在一个java应用程序上工作。我想在箭头键上实现一个KeyListener。我有一个扩展JFrame并实现ActionListener的类

  • 我试图添加一个imagepanel,将JPanel扩展到另一个JPanel。这对我来说不太好。图像面板的绘制功能在Jpanel中不会被调用,但在JFrame中可以正常工作。任何想法或帮助都将不胜感激。

  • 我正在做一个游戏,我试图在JFrame中添加一个JPanel。我有一个单独的类来扩展JPanel,我创建了一个新的对象来扩展JPanel。 但是,我得到了这个错误:“类型容器中的方法add(Component)不适用于参数(mainMenu)”(mainMenu是扩展JPanel的类)。 (JPanel类)公共类mainMenu扩展JPanel{ 我希望这样可以向我的JFrame添加一个JPane

  • 我想在firebase中的post文档中引用类别文档。这是我的数据类,我还使用冻结和json_序列化程序: 当我运行build_runner时,出现以下错误: 所以尝试使用JsonConzer,但我不知道如何将json对象转换为Document参考...