gamoridev
gamoridev

Reputation: 13

Change value one by one in JLabel by keyPressed

I'm trying to change jLabel value at one key pressed, but my doubt is: Can i change for value increment one by one? Like, i want to display 9 numbers, but, one by one after a key pressed. The way i did, it stops by "1" because of the "break;" command and back to beginning showing "1" again.

    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) {
    }

}

Upvotes: 1

Views: 1300

Answers (2)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9872

why do you use a loop? create a int i instance variable and increment it by one when press the key . like this

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

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

    }

full code

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) {
    }

}

note: call setVisible(true); after you add all the components to the frame.

Upvotes: 3

MadProgrammer
MadProgrammer

Reputation: 347204

I'm not sure what the point of the for-loop is for, you simply want to add (or subtract) one from i, check to make sure it's within the acceptable bounds of your range and update the label.

I would, however, strongly discourage you from using KeyListener, as it has no end of issues and instead, would recommended that you use the key bindings API instead, for example...

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));
        }

    }

}

See How to Use Key Bindings for more details

Upvotes: 3

Related Questions