通过keyPressed在JLabel中逐个更改值

时间:2015-09-16 04:01:08

标签: java swing keylistener keyevent

我试图在按下一个键时更改jLabel值,但我的疑问是:我可以逐个更改值增量吗? 比如,我想要显示9个数字,但是在按下一个键后逐个显示。我做的方式,由于“休息”,它停在“1”命令并重新开始显示“1”。

while ((dirp = readdir (directory)) != NULL) { 
  if ( strstr(dirp->d_name , ".txt" )) { 
    printf( "found a .txtfile: %s\n", dirp->d_name ); 
  } 
}

2 个答案:

答案 0 :(得分:3)

为什么要使用循环?创建一个int i实例变量,并在按下该键时将其递增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);

答案 1 :(得分:3)

我不确定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