通过 keyPressed 在 JLabel 中一个一个地更改值

Change value one by one in JLabel by keyPressed

我正在尝试一键更改 jLabel 值,但我的疑问是:我可以逐个更改值增量吗? 就像,我想显示 9 个数字,但是,在按下一个键后一个一个地显示。我这样做的方式是,由于 "break;" 命令,它停在“1”处,然后又回到开始显示“1”的位置。

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

    public class Automato extends JFrame implements KeyListener {

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

    JLabel lbNumero = new JLabel("0");

    Automato() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 300);
        setTitle("Automato");
        setLocationRelativeTo(null);
        setLayout(new FlowLayout());
        setVisible(true);
        lbNumero.setFont(new Font("Arial", Font.PLAIN, 200));
        lbNumero.setForeground(Color.red);
        addKeyListener(this);
        add(lbNumero);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int teclaPressionada = e.getKeyCode();

        for (int i = 0; i < 9;){
            if (teclaPressionada == KeyEvent.VK_NUMPAD1){
                i++;
                lbNumero.setText(""+i);
                System.out.println(i);
            }
            break; //Infinity output without break
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

}

为什么要使用循环?创建一个 int i 实例变量并在按下 key 时将其递增 1。像这样

public void keyPressed(KeyEvent e) {
    int teclaPressionada = e.getKeyCode();

        if (teclaPressionada == KeyEvent.VK_NUMPAD1&& i<9) {
            i++;
            lbNumero.setText("" + i);
            System.out.println(i);
        }

    }

完整代码

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

public class Automato extends JFrame implements KeyListener {

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

    JLabel lbNumero = new JLabel("0");
    private int i;


    Automato() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 300);
        setTitle("Automato");
        setLocationRelativeTo(null);
        setLayout(new FlowLayout());
        lbNumero.setFont(new Font("Arial", Font.PLAIN, 200));
        lbNumero.setForeground(Color.red);
        addKeyListener(this);
        add(lbNumero);
        setVisible(true);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int teclaPressionada = e.getKeyCode();

            if (teclaPressionada == KeyEvent.VK_NUMPAD1&& i<9) {
                i++;
                lbNumero.setText("" + i);
                System.out.println(i);
            }

        }


    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

}

注意:将所有组件添加到框架后调用 setVisible(true);

我不确定 for-loop 的意义是什么,您只是想从 i 中添加(或减去)一个,检查以确保它在可接受的范围内您的范围并更新标签。

但是,我强烈建议您不要使用 KeyListener,因为它没有尽头,相反,我建议您使用键绑定 API,例如.. .

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;
        private int value = 0;

        public TestPane() {
            label = new JLabel();
            label.setFont(label.getFont().deriveFont(Font.BOLD, 48f));

            setLayout(new GridBagLayout());
            add(label);

            updateLabel();

            InputMap im = label.getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = label.getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD8, 0), "increment");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, 0), "decrement");

            am.put("increment", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    value = Math.min(9, ++value);
                    updateLabel();
                }
            });
            am.put("decrement", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    value = Math.max(0, --value);
                    updateLabel();
                }
            });
        }

        protected void updateLabel() {
            label.setText(String.format("%02d", value));
        }

    }

}

有关详细信息,请参阅 How to Use Key Bindings