简体   繁体   English

Key Listener 一直在监听更多的键,我不知道如何阻止它这样做

[英]Key Listener keeps listening for more keys, and i can't figure out how to stop it from doing so

So i made a little sudoku game where I've used toggle buttons to take input.所以我做了一个小数独游戏,我使用切换按钮来输入。 Basically when a toggle button is toggled, a key listener is activated that listens for keys 1-9.基本上,当切换按钮被切换时,会激活一个键侦听器来侦听键 1-9。 Problem is, after the key is entered, i've used buttonGroup.clearSelection(), and it toggles the button again so it's deselected, but there's a small dotted rectangle over the text, and if i press any other digit, it changes the previous digit and writes the new one.问题是,在输入键后,我使用了 buttonGroup.clearSelection(),它再次切换按钮,使其被取消选择,但文本上有一个小的虚线矩形,如果我按下任何其他数字,它会改变前一位并写入新的一位。 I'm new to Java and GUIs so the problem could be something else entirely.我是 Java 和 GUI 的新手,所以问题可能完全是其他问题。 Code is attached below.代码附在下面。 Please help!请帮忙!

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


public class Test implements ActionListener, KeyListener {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JToggleButton[] cells = new JToggleButton[81];
    JToggleButton selectedButton = new JToggleButton();
    ButtonGroup group = new ButtonGroup();
    int index;

    int[][] board = {
        {7, 2, 6, 4, 9, 3, 8, 0, 5},
        {3, 1, 5, 0, 2, 8, 0, 4, 6},
        {4, 0, 9, 6, 5, 1, 2, 3, 7},
        {8, 5, 2, 1, 0, 7, 6, 0, 3},
        {6, 7, 3, 9, 0, 5, 0, 2, 4},
        {9, 4, 0, 3, 6, 2, 7, 5, 8},
        {1, 9, 4, 8, 3, 6, 5, 0, 2},
        {5, 0, 7, 2, 1, 0, 3, 8, 9},
        {2, 3, 8, 5, 7, 9, 4, 6, 0}
    };

    public Test() {
        for (int x=0; x<81; x++) {
            cells[x] = new JToggleButton();
            group.add(cells[x]);
            cells[x].putClientProperty("index", x);
            cells[x].addActionListener(this);
            panel.add(cells[x]);
        }

        panel.setLayout(new GridLayout(9, 9, 2, 2)); 
        panel.setBackground(Color.black);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        printBoard(board);

        frame.setJMenuBar(menuBar);
        frame.pack();
        frame.add(panel); 
        frame.pack();
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        selectedButton = (JToggleButton)e.getSource();
        index = (int) selectedButton.getClientProperty("index");
        selectedButton.addKeyListener(this);
    }

    public void keyPressed(KeyEvent e) {
        Integer digit;
        Integer r, c;
        r = index / 9;
        c = index % 9;
        digit = Integer.valueOf(e.getKeyCode() - 48);       

        if (digit > 0 && digit <10) {
            board[r][c] = digit;
        }

        String s = digit.toString();

        if (e.getKeyCode() >= 49 && e.getKeyCode() <= 57) {
            selectedButton.setText(s);
            group.clearSelection();
        } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE || e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            board[r][c] = 0;
            selectedButton.setText("");
            group.clearSelection();
        } 
    }

    public void keyReleased(KeyEvent e) {
        group.clearSelection();
    }

    public void keyTyped(KeyEvent e) {}

    public void printBoard(int[][] board) {
        for (int x=0; x<81; x++) { 
            cells[x].setEnabled(true);
        }
        Integer digit;
        String buttonText;

        int buttonIndex = 0;
        for (int r=0; r<9; r++) {
            for (int c=0; c<9; c++) {
                digit = Integer.valueOf(board[r][c]);
                if (digit == 0) {
                    cells[buttonIndex].setText("");
                    buttonIndex++;
                    continue;
                }
                else if (digit != 0) {
                    buttonText = digit.toString();
                    cells[buttonIndex].setText(s);
                    cells[buttonIndex].setEnabled(false);
                    buttonIndex++;
                }
            }
        }
    }

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

group here is a ButtonGroup of all the toggle buttons. group 是所有切换按钮的 ButtonGroup。 It does deselect the button but key listener still stays activated.它确实取消了按钮的选择,但键侦听器仍然保持激活状态。 Please help.请帮忙。

All you have to do is remove the key listener when the key is released.您所要做的就是在释放键时删除键侦听器。

I had to comment out the JMenu because it must be somewhere else,我不得不注释掉 JMenu,因为它必须在其他地方,

Here's the GUI.这是图形用户界面。

数独测试 GUI

And here's the code I used.这是我使用的代码。

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

public class SudokuTest implements ActionListener, KeyListener {
    JFrame frame = new JFrame("Sudoku Test");

    JPanel panel = new JPanel();
    JToggleButton[] cells = new JToggleButton[81];
    JToggleButton selectedButton = new JToggleButton();
    ButtonGroup group = new ButtonGroup();
    int index;

    int[][] board = { { 7, 2, 6, 4, 9, 3, 8, 0, 5 }, { 3, 1, 5, 0, 2, 8, 0, 4, 6 }, { 4, 0, 9, 6, 5, 1, 2, 3, 7 },
            { 8, 5, 2, 1, 0, 7, 6, 0, 3 }, { 6, 7, 3, 9, 0, 5, 0, 2, 4 }, { 9, 4, 0, 3, 6, 2, 7, 5, 8 },
            { 1, 9, 4, 8, 3, 6, 5, 0, 2 }, { 5, 0, 7, 2, 1, 0, 3, 8, 9 }, { 2, 3, 8, 5, 7, 9, 4, 6, 0 } };

    public SudokuTest() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Font font = panel.getFont().deriveFont(32F).deriveFont(Font.BOLD);
        for (int x = 0; x < 81; x++) {
            cells[x] = new JToggleButton();
            group.add(cells[x]);
            cells[x].putClientProperty("index", x);
            cells[x].addActionListener(this);
            cells[x].setFont(font);
            panel.add(cells[x]);
        }

        panel.setLayout(new GridLayout(9, 9, 2, 2));
        panel.setBackground(Color.black);

        printBoard(board);

//        frame.setJMenuBar(menuBar);
        frame.add(panel);
        frame.pack();
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        selectedButton = (JToggleButton) e.getSource();
        index = (int) selectedButton.getClientProperty("index");
        selectedButton.addKeyListener(this);
    }

    public void keyPressed(KeyEvent e) {
        Integer digit;
        Integer r, c;
        r = index / 9;
        c = index % 9;
        digit = Integer.valueOf(e.getKeyCode() - 48);

        if (digit > 0 && digit < 10) {
            board[r][c] = digit;
        }

        String s = digit.toString();

        if (e.getKeyCode() >= 49 && e.getKeyCode() <= 57) {
            selectedButton.setText(s);
            group.clearSelection();
        } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE
                || e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            board[r][c] = 0;
            selectedButton.setText("");
            group.clearSelection();
        }
    }

    public void keyReleased(KeyEvent e) {
        group.clearSelection();
        selectedButton.removeKeyListener(this);
    }

    public void keyTyped(KeyEvent e) {
    }

    public void printBoard(int[][] board) {
        for (int x = 0; x < 81; x++) {
            cells[x].setEnabled(true);
        }
        Integer digit;
        String buttonText;

        int buttonIndex = 0;
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                digit = Integer.valueOf(board[r][c]);
                if (digit == 0) {
                    cells[buttonIndex].setText("");
                    buttonIndex++;
                } else {
                    buttonText = digit.toString();
                    cells[buttonIndex].setText(buttonText);
                    cells[buttonIndex].setEnabled(false);
                    buttonIndex++;
                }
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SudokuTest();
            }
        });
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我不知道 spring 的哪个组件正在这样做 - i can't figure out which component of the spring is doing this 如何确定密钥是否存在于番石榴缓存中,这样我才不会覆盖它? - How to figure out whether a key exists in guava cache so that I don't overwrite it? 某些内容正在杀死我的脚本,无法确定代码中正在执行的操作并输出STOP_ACTIVITY_HIDE - Something is killing my script, can't figure out what is doing it in code and outputs STOP_ACTIVITY_HIDE 如何在满足条件后停止值事件侦听器的侦听 - how to stop value event listener from listening after a condition is met 空指针异常,我无法弄清楚我在做什么错 - Null Pointer Exception, I can't figure out what I am doing wrong 无法弄清楚如何重置一个int,因此我可以正确使用循环来制作Pig游戏 - Can't figure out how to reset an int so I can use my loop properly making the game of Pig 我似乎无法弄清楚接下来要做什么。 它一直说“不是声明” - I can't seem to figure out what to do next. It keeps saying “Not a statement” Java做while循环不断重复,我不知道为什么 - java do while loop keeps repeating and I can't figure out why 我似乎无法弄清楚如何处理此实例,以便我的代码可以打印出要求 - I can't seem to figure out what to do with this instance so that my code could print out the requirement Java Udemy 课程闰年计算器 - 无法弄清楚我做错了什么 - Java Udemy course leap year calculator - can't figure out what am I doing wrong
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM