Help with java events

0

Very good.

I have created a fairly simple calculator in Java that works (at the moment) by pressing the buttons on the interface and I have the following questions:

  • For some reason, there are times when pressing the buttons these do not work the first time. What could cause this malfunction?
  • Is there a way to have the program pick up the numbers by keyboard?
  • I leave the code here below, thank you very much in advance.

        public class Main extends javax.swing.JFrame {
    
    private String textoPantalla, aux;
    private float primerOperando, segundoOperando, resultado;
    private boolean sumar, restar, multiplicar, dividir;
    
    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        pantallaResultado.setEditable(false);
        setTextoPantalla("");
        setResizable(false);
    }                      
    
    private void button1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button1.getText());
    }                                    
    
    private void button2MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button2.getText());
    }                                    
    
    private void button3MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button3.getText());
    }                                    
    
    private void button4MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button4.getText());
    }                                    
    
    private void button5MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button5.getText());
    }                                    
    
    private void button6MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button6.getText());
    }                                    
    
    private void button7MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button7.getText());
    }                                    
    
    private void button8MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button8.getText());
    }                                    
    
    private void button9MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button9.getText());
    }                                    
    
    private void button0MouseClicked(java.awt.event.MouseEvent evt) {                                     
        asignarNumeroABoton(button0.getText());
    }                                    
    
    
    private void buttonPlusMouseClicked(java.awt.event.MouseEvent evt) {                                        
        notEmpty();
        sumarTrue();
        try {
            setPrimerOperando(Float.parseFloat(textoPantalla));
        } catch (NumberFormatException e) {
            System.out.println("Cadena vacia"); 
        }
    
        setTextoPantalla("");
        setPantallaResultadoText("0");
    
    }                                       
    
    private void buttonEqualsMouseClicked(java.awt.event.MouseEvent evt) {                                          
        try{
        setSegundoOperando(Float.parseFloat(textoPantalla));
        } catch (NumberFormatException e)
        {
            System.out.println("Cadena Vacia"); 
        }
        seleccionarOperacion();
        setTextoPantalla(Float.toString(resultado));
        setPantallaResultadoText(textoPantalla);
        setPrimerOperando(resultado);
    }                                         
    
    private void buttonDivisionMouseClicked(java.awt.event.MouseEvent evt) {                                            
        notEmpty();
        dividirTrue();
        setPrimerOperando(Float.parseFloat(textoPantalla));
        setTextoPantalla("");
        setPantallaResultadoText("0");
    }                                           
    
    private void buttonMinusMouseClicked(java.awt.event.MouseEvent evt) {                                         
        notEmpty();
        restaTrue();
        setPrimerOperando(Float.parseFloat(textoPantalla));
        setTextoPantalla("");
        setPantallaResultadoText("0");
    }                                        
    
    private void buttonMultiplicationMouseClicked(java.awt.event.MouseEvent evt) {                                                  
        notEmpty();
        multiplicarTrue();
        setPrimerOperando(Float.parseFloat(textoPantalla));
        setTextoPantalla("");
        setPantallaResultadoText("0");
    }                                                 
    
    private void buttonCMouseClicked(java.awt.event.MouseEvent evt) {                                     
        setPrimerOperando(0);
        setSegundoOperando(0);
        setAllFalse();
        setTextoPantalla("");
        setPantallaResultadoText("0");
    }                                    
    
    private void seleccionarOperacion() {
        if (sumar) {
            setResultado(sumar(primerOperando, segundoOperando));
        }
    
        if (restar) {
            setResultado(restar(primerOperando, segundoOperando));
        }
    
        if (multiplicar) {
            setResultado(multiplicar(primerOperando, segundoOperando));
        }
    
        if (dividir) {
            setResultado(dividir(primerOperando, segundoOperando));
        }
    
        setTextoPantalla(Float.toString(resultado));
        setPantallaResultadoText(textoPantalla);
    }
    
    private float sumar(float operando1, float operando2) {
        float res = operando1 + operando2;
    
        return res;
    }
    
    private float restar(float operando1, float operando2) {
        float res = operando1 - operando2;
    
        return res;
    }
    
    private float multiplicar(float operando1, float operando2) {
        float res = operando1 * operando2;
    
        return res;
    }
    
    private float dividir(float operando1, float operando2) {
        float res = operando1 / operando2;
    
        return res;
    }
    
    private void restaTrue() {
        restar = true;
        sumar = false;
        multiplicar = false;
        dividir = false;
    }
    
    private void sumarTrue() {
        restar = false;
        sumar = true;
        multiplicar = false;
        dividir = false;
    }
    
    private void multiplicarTrue() {
        restar = false;
        sumar = false;
        multiplicar = true;
        dividir = false;
    }
    
    private void dividirTrue() {
        restar = false;
        sumar = false;
        multiplicar = false;
        dividir = true;
    }
    
    private void setAllFalse() {
        restar = false;
        sumar = false;
        multiplicar = false;
        dividir = false;
    }
    
    private void asignarNumeroABoton(String numero) {
        switch (numero) {
            case "0":
                numeroEnPantalla(numero);
                break;
            case "1":
                numeroEnPantalla(numero);
                break;
            case "2":
                numeroEnPantalla(numero);
                break;
            case "3":
                numeroEnPantalla(numero);
                break;
            case "4":
                numeroEnPantalla(numero);
                break;
            case "5":
                numeroEnPantalla(numero);
                break;
            case "6":
                numeroEnPantalla(numero);
                break;
            case "7":
                numeroEnPantalla(numero);
                break;
            case "8":
                numeroEnPantalla(numero);
                break;
            case "9":
                numeroEnPantalla(numero);
                break;
        }
    }
    
    public void notEmpty() {
        if (textoPantalla.equals("")) {
            setPrimerOperando(0);
        }
    }
    
    public void numeroEnPantalla(String numero) {
        aux = numero;
        textoPantalla = textoPantalla + aux;
        setPantallaResultadoText(textoPantalla);
    }
    

    Code generated by Netbeans:

    private void initComponents () {

        jPanel1 = new javax.swing.JPanel();
        button1 = new javax.swing.JButton();
        button2 = new javax.swing.JButton();
        button3 = new javax.swing.JButton();
        button4 = new javax.swing.JButton();
        button5 = new javax.swing.JButton();
        button6 = new javax.swing.JButton();
        button7 = new javax.swing.JButton();
        button8 = new javax.swing.JButton();
        button9 = new javax.swing.JButton();
        button0 = new javax.swing.JButton();
        buttonC = new javax.swing.JButton();
        buttonPlus = new javax.swing.JButton();
        buttonMinus = new javax.swing.JButton();
        buttonMultiplication = new javax.swing.JButton();
        buttonDivision = new javax.swing.JButton();
        buttonEquals = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        pantallaResultado = new javax.swing.JTextField();
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
        button1.setText("1");
        button1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button1MouseClicked(evt);
            }
        });
    
        button2.setText("2");
        button2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button2MouseClicked(evt);
            }
        });
    
        button3.setText("3");
        button3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button3MouseClicked(evt);
            }
        });
    
        button4.setText("4");
        button4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button4MouseClicked(evt);
            }
        });
    
        button5.setText("5");
        button5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button5MouseClicked(evt);
            }
        });
    
        button6.setText("6");
        button6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button6MouseClicked(evt);
            }
        });
    
        button7.setText("7");
        button7.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button7MouseClicked(evt);
            }
        });
    
        button8.setText("8");
        button8.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button8MouseClicked(evt);
            }
        });
    
        button9.setText("9");
        button9.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button9MouseClicked(evt);
            }
        });
    
        button0.setText("0");
        button0.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                button0MouseClicked(evt);
            }
        });
    
        buttonC.setText("C");
        buttonC.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buttonCMouseClicked(evt);
            }
        });
    
        buttonPlus.setText("+");
        buttonPlus.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buttonPlusMouseClicked(evt);
            }
        });
    
        buttonMinus.setText("-");
        buttonMinus.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buttonMinusMouseClicked(evt);
            }
        });
    
        buttonMultiplication.setText("x");
        buttonMultiplication.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buttonMultiplicationMouseClicked(evt);
            }
        });
    
        buttonDivision.setText("/");
        buttonDivision.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buttonDivisionMouseClicked(evt);
            }
        });
    
        buttonEquals.setText("=");
        buttonEquals.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buttonEqualsMouseClicked(evt);
            }
        });
    
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(button7, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button8, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button9, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(button4, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button5, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button6, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(buttonC, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button0, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(buttonEquals, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(buttonMultiplication, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(90, 90, 90))
                            .addComponent(buttonMinus, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(buttonDivision, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(button3, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(buttonPlus, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(90, 90, 90))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button1)
                    .addComponent(button2)
                    .addComponent(button3)
                    .addComponent(buttonPlus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button4)
                    .addComponent(button5)
                    .addComponent(button6)
                    .addComponent(buttonMultiplication))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button7)
                    .addComponent(button8)
                    .addComponent(button9)
                    .addComponent(buttonMinus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button0)
                    .addComponent(buttonC)
                    .addComponent(buttonDivision)
                    .addComponent(buttonEquals))
                .addGap(40, 40, 40))
        );
    
        pantallaResultado.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        pantallaResultado.setText("0");
        pantallaResultado.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
    
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pantallaResultado)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(pantallaResultado, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    
        pack();
    }// </editor-fold>  
    

    EDIT:

    Sorry for the delay, I've been pretty busy, I leave the missing code.

    public void setTextoPantalla(String textoPantalla) {
        this.textoPantalla = textoPantalla;
    }
    
    public void setPrimerOperando(float primerOperando) {
        this.primerOperando = primerOperando;
    }
    
    public void setSegundoOperando(float segundoOperando) {
        this.segundoOperando = segundoOperando;
    }
    
    public void setResultado(float resultado) {
        this.resultado = resultado;
    }
    
    public void setSumar(boolean sumar) {
        this.sumar = sumar;
    }
    
    public void setRestar(boolean restar) {
        this.restar = restar;
    }
    
    public void setMultiplicar(boolean multiplicar) {
        this.multiplicar = multiplicar;
    }
    
    public void setDividir(boolean dividir) {
        this.dividir = dividir;
    }
    
    public void setPantallaResultadoText(String pantallaResultado) {
        this.pantallaResultado.setText(pantallaResultado);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
    
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton button0;
    private javax.swing.JButton button1;
    private javax.swing.JButton button2;
    private javax.swing.JButton button3;
    private javax.swing.JButton button4;
    private javax.swing.JButton button5;
    private javax.swing.JButton button6;
    private javax.swing.JButton button7;
    private javax.swing.JButton button8;
    private javax.swing.JButton button9;
    private javax.swing.JButton buttonC;
    private javax.swing.JButton buttonDivision;
    private javax.swing.JButton buttonEquals;
    private javax.swing.JButton buttonMinus;
    private javax.swing.JButton buttonMultiplication;
    private javax.swing.JButton buttonPlus;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField pantallaResultado;
    // End of variables declaration                   
    

    }

        
    asked by ProK 18.02.2018 в 19:24
    source

    1 answer

    2

    Greetings, ProK.

      

    For some reason, there are times when pressing the buttons these do not   they work the first time What could cause this malfunction?

    Change the type of event you added to all your buttons, I noticed that your buttons have a MouseListener event, being a button, better add an event ActionListener , since they do not need that event MouseListener .

    Basically, it would be to change this:

    button1.setText("1");
    button1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            button1MouseClicked(evt);
        }
    });
    

    To something like this:

    button1.setText("1");
    button1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            button1ActionPerformed(evt);
        }
    });
    
    // Ese código lo escribí yo tratando de igualar el código generado por NetBeans
    // Y cómo podría quedar después de agregarlas el evento ActionListener
    

    And this way you should apply them to all your buttons, with that it would be enough so that when pressing the buttons they work to the first always.

      

    Is there any way to get the program to pick up the numbers   by keyboard?

    Yes, in fact there are two ways:

    • "Relatively" simple form:

    This form is quite simple to apply, but why "relatively"? Well, it can not always work because it requires eliminating the focus of buttons and text boxes in your program so that you can only focus on either the JPanel or the JFrame itself (your window).

    For this you need to add an event of type KeyListener (specifically a KeyPressed ) either in your panel ( jPanel1 ) or in your window ( JFrame ).

    The generated event should be something like this:

    // Ejemplo con el evento KeyPressed agregado al JFrame
    private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
        switch (evt.getKeyCode()) {
            case java.awt.event.KeyEvent.VK_0:
                // Ejecutar acción al presionar la tecla 0
                break;
            case java.awt.event.KeyEvent.VK_1:
                // Ejecutar acción al presionar la tecla 1
                break;
            case java.awt.event.KeyEvent.VK_2:
                // Ejecutar acción al presionar la tecla 2
                break;
            // Y así realizas con todos los botones que quieras
        }
    }
    
    • Shape a bit more complicated:

    Although it is usually the most complicated to adapt (besides that it generates more code), this is the definitive one to solve the problems of approaches that your program could present, since it would only imply having your application visible and focused (It is not necessary to eliminate approaches to the other components).

    This form is done directly in JPanel , by means of the Key Bindings (I invite you to investigate a little more on that topic):

    InputMap map = jPanel1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); // Te permite ejecutar las acciones con solo que la ventana esté visible y enfocada
    ActionMap action = jPanel1.getActionMap();
    
    map.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, 0), "KEY_0");
    action.put("KEY_0", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            button0ActionPerformed(e);
        }
    });
    map.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_1, 0), "KEY_1");
    action.put("KEY_1",  new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            button1ActionPerformed(e);
        }
    });
    // Y así con todas las teclas.
    

    NOTE:

    The above examples were based on a program generated by NetBeans to fit your question. However, if you plan to do it on your own (which would be much more orderly) could be more benefited by not having to use more code of the account, adding the knowledge you acquire.

        
    answered by 22.02.2018 / 07:30
    source