Anuncio

Colapsar
No hay ningún anuncio todavía.

Java:

Colapsar
X
 
  • Filtro
  • Hora
  • Mostrar
Borrar todo
nuevos mensajes

  • Java:

    Hola, nos han propuesto hacer un programa en el que tú introduces el valor de una suma y si éste es correcto dice: "Correcto" y si es incorrecto "Incorrecto":

    Entonces, el código que uso es:
    Código:
    private void comprova1MouseClicked(java.awt.event.MouseEvent evt) {
          resultat1.setText(Integer.toString(input1.getValue()+input2.getValue()));
          if(resultatm == resultat1)System.out.println("Correcte");
          else (resultatm == else) System.out.println("Incorrecte");
    
    }
    Donde:

    comprova1: es el botón que se encarga de calcular la suma y decir si es correcto o incorrecto.
    resultat1: es la casilla donde debe realizarse la suma.
    resultatm: es la casilla donde se escribe el resultado a mano.

    El problema es que la línea de:

    Código:
    if(resultatm == resultat1)System.out.println("Correcte");
    me la acepta como correcta, pero no hace nada, es decir, una vez escribo mi resultado no dice "Correcte".

    en cambio, para ésta:
    Código:
    else (resultatm == else) System.out.println("Incorrecte");
    ya no me acepta el código.


    ¿Qué hago mal?

    Gracias!
    \sqrt\pi

  • #2
    Re: Java:

    Hola,
    Para comparar strings en java se usa el método equals().

    Por ejemplo, compraras a y b

    if(a.equals(B) {
    System.out...
    } else ...

    y en el else ya metes la otra opción, no puedes igualarlo a nada

    (Con lo que tu estabas haciendo, el poner == creo que lo que te evalúa es los nombres de los strings a ver si coinciden, nada más)

    Saludos

    Comentario


    • #3
      Re: Java:

      Escrito por BigMess Ver mensaje
      Hola,
      Para comparar strings en java se usa el método equals().

      Por ejemplo, compraras a y b

      if(a.equals(B) {
      System.out...
      } else ...

      y en el else ya metes la otra opción, no puedes igualarlo a nada

      (Con lo que tu estabas haciendo, el poner == creo que lo que te evalúa es los nombres de los strings a ver si coinciden, nada más)

      Saludos
      Hum, ahora me acepta el código pero no hace lo que yo quiero, ponga el valor que ponga (aunque sea el correcto) me dice que es incorrecto.

      El código que uso es:

      Código:
       private void ComprovarMouseClicked(java.awt.event.MouseEvent evt) {
              resultat1.setText(Integer.toString(input1.getValue()+input2.getValue())); 
              if(resultatm.equals(resultat1))System.out.println("Correcte");
              else{System.out.println("Incorrecte");}
      
      }

      Muchas Gracias!
      \sqrt\pi

      Comentario


      • #4
        Re: Java:

        no sé, ahora mismo no se me ocurre nada, como no sea algún espacio de más en la casilla donde pones el resultado (los strings tienen que ser idénticos). (Puedes usar .trim() para quitar los espacios de un string)

        Comentario


        • #5
          Re: Java:

          ¿Cómo obtenés resultatm?

          Comentario


          • #6
            Re: Java:

            Escrito por Fedenet Ver mensaje
            ¿Cómo obtenés resultatm?
            resultam es un text field, lo relleno a mano cuando se ejecuta el programa, y mi idea es que si el número q escribo es el correcto (es decir, el resultado de la suma de inputA+inputB) al apretar comprova me diga "correcte" y si no es el mismo, me diga "incorrecte".


            Gracias
            \sqrt\pi

            Comentario


            • #7
              Re: Java:

              ¿Pero hacés un resultatm.getvalue()?
              ¿O settext?
              No veo que le asignes el valor al objeto resultatm.
              Última edición por Fedenet; 19/10/2009, 23:48:44.

              Comentario


              • #8
                Re: Java:

                Escrito por Fedenet Ver mensaje
                ¿Pero hacés un resultatm.getvalue()?
                Mira, te paso el codigo entero de lo que llevo, ok (es que soy 100% novato, y no entiendo muy bien a qué te refieres) ? Se trata de un programa que suma, multiplica y divide. Eso lo hace bien. Además, pasa el resultado a binario.

                Luego, nos han pedido que hagamos una aplicación en la que si tu introduces en una casilla el valor correcto de la suma, te diga "Correcte" y si introduces un valor incorrecto, que te salga "Incorrecte".

                Código:
                /*
                 * CalculadoraView.java
                 */
                
                package calculadora;
                
                import org.jdesktop.application.Action;
                import org.jdesktop.application.ResourceMap;
                import org.jdesktop.application.SingleFrameApplication;
                import org.jdesktop.application.FrameView;
                import org.jdesktop.application.TaskMonitor;
                import java.awt.event.ActionEvent;
                import java.awt.event.ActionListener;
                import javax.swing.Timer;
                import javax.swing.Icon;
                import javax.swing.JDialog;
                import javax.swing.JFrame;
                
                /**
                 * The application's main frame.
                 */
                public class CalculadoraView extends FrameView {
                
                    public CalculadoraView(SingleFrameApplication app) {
                        super(app);
                
                        initComponents();
                
                        // status bar initialization - message timeout, idle icon and busy animation, etc
                        ResourceMap resourceMap = getResourceMap();
                        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
                        messageTimer = new Timer(messageTimeout, new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                statusMessageLabel.setText("");
                            }
                        });
                        messageTimer.setRepeats(false);
                        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
                        for (int i = 0; i < busyIcons.length; i++) {
                            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
                        }
                        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
                            }
                        });
                        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
                        statusAnimationLabel.setIcon(idleIcon);
                        progressBar.setVisible(false);
                
                        // connecting action tasks to status bar via TaskMonitor
                        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
                        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
                            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                                String propertyName = evt.getPropertyName();
                                if ("started".equals(propertyName)) {
                                    if (!busyIconTimer.isRunning()) {
                                        statusAnimationLabel.setIcon(busyIcons[0]);
                                        busyIconIndex = 0;
                                        busyIconTimer.start();
                                    }
                                    progressBar.setVisible(true);
                                    progressBar.setIndeterminate(true);
                                } else if ("done".equals(propertyName)) {
                                    busyIconTimer.stop();
                                    statusAnimationLabel.setIcon(idleIcon);
                                    progressBar.setVisible(false);
                                    progressBar.setValue(0);
                                } else if ("message".equals(propertyName)) {
                                    String text = (String)(evt.getNewValue());
                                    statusMessageLabel.setText((text == null) ? "" : text);
                                    messageTimer.restart();
                                } else if ("progress".equals(propertyName)) {
                                    int value = (Integer)(evt.getNewValue());
                                    progressBar.setVisible(true);
                                    progressBar.setIndeterminate(false);
                                    progressBar.setValue(value);
                                }
                            }
                        });
                    }
                
                    @Action
                    public void showAboutBox() {
                        if (aboutBox == null) {
                            JFrame mainFrame = CalculadoraApp.getApplication().getMainFrame();
                            aboutBox = new CalculadoraAboutBox(mainFrame);
                            aboutBox.setLocationRelativeTo(mainFrame);
                        }
                        CalculadoraApp.getApplication().show(aboutBox);
                    }
                
                    /** This method is called from within the constructor to
                     * initialize the form.
                     * WARNING: Do NOT modify this code. The content of this method is
                     * always regenerated by the Form Editor.
                     */
                    @SuppressWarnings("unchecked")
                    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
                    private void initComponents() {
                        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
                
                        mainPanel = new javax.swing.JPanel();
                        output1 = new javax.swing.JTextField();
                        input2 = new javax.swing.JSlider();
                        output2 = new javax.swing.JTextField();
                        Sumar = new javax.swing.JButton();
                        Multiplicar = new javax.swing.JButton();
                        Dividir = new javax.swing.JButton();
                        resultat1 = new javax.swing.JTextField();
                        resultat2 = new javax.swing.JTextField();
                        resultat3 = new javax.swing.JTextField();
                        resultat5 = new javax.swing.JTextField();
                        resultat6 = new javax.swing.JTextField();
                        resultat7 = new javax.swing.JTextField();
                        input1 = new javax.swing.JSlider();
                        jLabel1 = new javax.swing.JLabel();
                        Comprovar = new javax.swing.JButton();
                        resultatm = new javax.swing.JTextField();
                        menuBar = new javax.swing.JMenuBar();
                        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
                        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
                        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
                        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
                        statusPanel = new javax.swing.JPanel();
                        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
                        statusMessageLabel = new javax.swing.JLabel();
                        statusAnimationLabel = new javax.swing.JLabel();
                        progressBar = new javax.swing.JProgressBar();
                
                        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(calculadora.CalculadoraApp.class).getContext().getResourceMap(CalculadoraView.class);
                        mainPanel.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("mainPanel.border.matteColor"))); // NOI18N
                        mainPanel.setName("mainPanel"); // NOI18N
                
                        output1.setName("output1"); // NOI18N
                
                        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, input1, org.jdesktop.beansbinding.ELProperty.create("${value}"), output1, org.jdesktop.beansbinding.BeanProperty.create("text"));
                        bindingGroup.addBinding(binding);
                
                        input2.setMaximum(10000);
                        input2.setMinimum(-10000);
                        input2.setName("input2"); // NOI18N
                
                        output2.setName("output2"); // NOI18N
                
                        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, input2, org.jdesktop.beansbinding.ELProperty.create("${value}"), output2, org.jdesktop.beansbinding.BeanProperty.create("text"));
                        bindingGroup.addBinding(binding);
                
                        Sumar.setText(resourceMap.getString("Sumar.text")); // NOI18N
                        Sumar.setName("Sumar"); // NOI18N
                        Sumar.addMouseListener(new java.awt.event.MouseAdapter() {
                            public void mouseClicked(java.awt.event.MouseEvent evt) {
                                SumarMouseClicked(evt);
                            }
                        });
                
                        Multiplicar.setText(resourceMap.getString("Multiplicar.text")); // NOI18N
                        Multiplicar.setName("Multiplicar"); // NOI18N
                        Multiplicar.addMouseListener(new java.awt.event.MouseAdapter() {
                            public void mouseClicked(java.awt.event.MouseEvent evt) {
                                MultiplicarMouseClicked(evt);
                            }
                        });
                
                        Dividir.setText(resourceMap.getString("Dividir.text")); // NOI18N
                        Dividir.setName("Dividir"); // NOI18N
                        Dividir.addMouseListener(new java.awt.event.MouseAdapter() {
                            public void mouseClicked(java.awt.event.MouseEvent evt) {
                                DividirMouseClicked(evt);
                            }
                        });
                
                        resultat1.setText(resourceMap.getString("resultat1.text")); // NOI18N
                        resultat1.setName("resultat1"); // NOI18N
                
                        resultat2.setText(resourceMap.getString("resultat2.text")); // NOI18N
                        resultat2.setName("resultat2"); // NOI18N
                
                        resultat3.setText(resourceMap.getString("resultat3.text")); // NOI18N
                        resultat3.setName("resultat3"); // NOI18N
                
                        resultat5.setText(resourceMap.getString("resultat5.text")); // NOI18N
                        resultat5.setName("resultat5"); // NOI18N
                
                        resultat6.setText(resourceMap.getString("resultat6.text")); // NOI18N
                        resultat6.setName("resultat6"); // NOI18N
                
                        resultat7.setText(resourceMap.getString("resultat7.text")); // NOI18N
                        resultat7.setName("resultat7"); // NOI18N
                
                        input1.setMaximum(10000);
                        input1.setMinimum(-10000);
                        input1.setName("input1"); // NOI18N
                
                        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
                        jLabel1.setName("jLabel1"); // NOI18N
                
                        Comprovar.setText(resourceMap.getString("Comprovar.text")); // NOI18N
                        Comprovar.setName("Comprovar"); // NOI18N
                        Comprovar.addMouseListener(new java.awt.event.MouseAdapter() {
                            public void mouseClicked(java.awt.event.MouseEvent evt) {
                                ComprovarMouseClicked(evt);
                            }
                        });
                
                        resultatm.setText(resourceMap.getString("resultatm.text")); // NOI18N
                        resultatm.setName("resultatm"); // NOI18N
                
                        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
                        mainPanel.setLayout(mainPanelLayout);
                        mainPanelLayout.setHorizontalGroup(
                            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 138, Short.MAX_VALUE)
                                        .addComponent(resultatm, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(Comprovar))
                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                        .addGap(34, 34, 34)
                                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(mainPanelLayout.createSequentialGroup()
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(input2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                    .addComponent(input1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGap(49, 49, 49)
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                    .addComponent(output2)
                                                    .addComponent(output1, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)))
                                            .addGroup(mainPanelLayout.createSequentialGroup()
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(resultat1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(resultat5, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                                        .addGap(8, 8, 8)
                                                        .addComponent(Sumar)))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                    .addComponent(resultat6)
                                                    .addComponent(Multiplicar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                                        .addComponent(resultat2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                            .addGap(18, 18, 18)
                                                            .addComponent(resultat7, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                            .addComponent(resultat3, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                        .addComponent(Dividir)
                                                        .addGap(30, 30, 30)))))))
                                .addGap(44, 44, 44))
                        );
                        mainPanelLayout.setVerticalGroup(
                            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(Comprovar)
                                        .addComponent(resultatm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(36, 36, 36)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(output1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(input1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(input2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(output2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(26, 26, 26)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(Multiplicar)
                                    .addComponent(Sumar)
                                    .addComponent(Dividir))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(resultat1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(resultat2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(resultat3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(resultat5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(resultat6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(resultat7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(12, Short.MAX_VALUE))
                        );
                
                        menuBar.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("menuBar.border.lineColor"))); // NOI18N
                        menuBar.setName("menuBar"); // NOI18N
                
                        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
                        fileMenu.setName("fileMenu"); // NOI18N
                
                        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(calculadora.CalculadoraApp.class).getContext().getActionMap(CalculadoraView.class, this);
                        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
                        exitMenuItem.setName("exitMenuItem"); // NOI18N
                        fileMenu.add(exitMenuItem);
                
                        menuBar.add(fileMenu);
                
                        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
                        helpMenu.setName("helpMenu"); // NOI18N
                
                        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
                        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
                        helpMenu.add(aboutMenuItem);
                
                        menuBar.add(helpMenu);
                
                        statusPanel.setName("statusPanel"); // NOI18N
                
                        statusMessageLabel.setName("statusMessageLabel"); // NOI18N
                
                        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
                        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
                
                        progressBar.setName("progressBar"); // NOI18N
                
                        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
                        statusPanel.setLayout(statusPanelLayout);
                        statusPanelLayout.setHorizontalGroup(
                            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
                            .addGroup(statusPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(statusMessageLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 257, Short.MAX_VALUE)
                                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(statusAnimationLabel)
                                .addContainerGap())
                        );
                        statusPanelLayout.setVerticalGroup(
                            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(statusPanelLayout.createSequentialGroup()
                                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(statusMessageLabel)
                                    .addComponent(statusAnimationLabel)
                                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(3, 3, 3))
                        );
                
                        setComponent(mainPanel);
                        setMenuBar(menuBar);
                        setStatusBar(statusPanel);
                
                        bindingGroup.bind();
                    }// </editor-fold>                        
                
                    private void SumarMouseClicked(java.awt.event.MouseEvent evt) {                                   
                       resultat1.setText(Integer.toString(input1.getValue()+input2.getValue()));
                       resultat5.setText(Integer.toBinaryString(input1.getValue()+input2.getValue()));
                    }                                  
                
                    private void MultiplicarMouseClicked(java.awt.event.MouseEvent evt) {                                         
                      resultat2.setText(Integer.toString(input1.getValue()*input2.getValue()));
                      resultat6.setText(Integer.toBinaryString(input1.getValue()*input2.getValue()));
                    }                                        
                
                    private void DividirMouseClicked(java.awt.event.MouseEvent evt) {                                     
                      resultat3.setText(Double.toString((double)input1.getValue()/(double)input2.getValue()));
                      resultat7.setText(Integer.toBinaryString(input1.getValue()/input2.getValue()));
                    }                                    
                
                    private void ComprovarMouseClicked(java.awt.event.MouseEvent evt) {                                       
                        resultat1.setText(Integer.toString(input1.getValue()+input2.getValue())); 
                        if(resultatm.equals(resultat1))System.out.println("Correcte");
                        else{System.out.println("Incorrecte");}
                
                    }                                      
                
                    // Variables declaration - do not modify                     
                    private javax.swing.JButton Comprovar;
                    private javax.swing.JButton Dividir;
                    private javax.swing.JButton Multiplicar;
                    private javax.swing.JButton Sumar;
                    private javax.swing.JSlider input1;
                    private javax.swing.JSlider input2;
                    private javax.swing.JLabel jLabel1;
                    private javax.swing.JPanel mainPanel;
                    private javax.swing.JMenuBar menuBar;
                    private javax.swing.JTextField output1;
                    private javax.swing.JTextField output2;
                    private javax.swing.JProgressBar progressBar;
                    private javax.swing.JTextField resultat1;
                    private javax.swing.JTextField resultat2;
                    private javax.swing.JTextField resultat3;
                    private javax.swing.JTextField resultat5;
                    private javax.swing.JTextField resultat6;
                    private javax.swing.JTextField resultat7;
                    private javax.swing.JTextField resultatm;
                    private javax.swing.JLabel statusAnimationLabel;
                    private javax.swing.JLabel statusMessageLabel;
                    private javax.swing.JPanel statusPanel;
                    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
                    // End of variables declaration                   
                
                    private final Timer messageTimer;
                    private final Timer busyIconTimer;
                    private final Icon idleIcon;
                    private final Icon[] busyIcons = new Icon[15];
                    private int busyIconIndex = 0;
                
                    private JDialog aboutBox;

                Aunque bueno, lo "importante" es esta parte:

                Código:
                 private void SumarMouseClicked(java.awt.event.MouseEvent evt) {                                   
                       resultat1.setText(Integer.toString(input1.getValue()+input2.getValue()));
                       resultat5.setText(Integer.toBinaryString(input1.getValue()+input2.getValue()));
                    }                                  
                
                    private void MultiplicarMouseClicked(java.awt.event.MouseEvent evt) {                                         
                      resultat2.setText(Integer.toString(input1.getValue()*input2.getValue()));
                      resultat6.setText(Integer.toBinaryString(input1.getValue()*input2.getValue()));
                    }                                        
                
                    private void DividirMouseClicked(java.awt.event.MouseEvent evt) {                                     
                      resultat3.setText(Double.toString((double)input1.getValue()/(double)input2.getValue()));
                      resultat7.setText(Integer.toBinaryString(input1.getValue()/input2.getValue()));
                    }                                    
                
                    private void ComprovarMouseClicked(java.awt.event.MouseEvent evt) {                                       
                        resultat1.setText(Integer.toString(input1.getValue()+input2.getValue())); 
                        if(resultatm.equals(resultat1))System.out.println("Correcte");
                        else{System.out.println("Incorrecte");}


                A ver si ves algo mal o a mejorar!


                Muchísimas gracias!
                \sqrt\pi

                Comentario


                • #9
                  Re: Java:

                  Estos son los métodos de la clase textfield:
                  http://java.comsci.us/examples/awt/TextField.html

                  Para obtener el valor de los textfields, la única forma es a través de .getText

                  Esto lo utilizarías así:

                  String resultado = textField.getText();

                  Comentario


                  • #10
                    Re: Java:

                    Para comparar números, tendrías que convertir las cadenas a sus valores numéricos. Es mejor comparar números que cadenas...
                    La única alternativo a ser Físico era ser etéreo.
                    @lwdFisica

                    Comentario


                    • #11
                      Re: Java:

                      pues si, mejor comparar los valores diréctamente, si no resulta absurdo andar cambiando el valor en texto y después otra vez de texto a número para compararlo ... pero weno, así según lo cojo sobre la marcha sería esto lo que tendrías que cambiar.

                      private void ComprovarMouseClicked(java.awt.event.MouseEvent evt) {
                      resultat1.setText(Integer.toString(input1.getValue()+input2.getValue()));
                      if(Integer.parseInt(resultatm.getText()) == Integer.parseInt(resultat1.getText()) )
                      System.out.println("Correcte");
                      else{System.out.println("Incorrecte");}

                      }

                      ... pero es mejor que lo vuelvas a revisar y cambiar otra vez, para no tener tantas transformaciones de texto a número y viceversa, que no tiene ningún sentido.

                      sl2!!
                      Última edición por Xel; 30/11/2009, 02:51:24.

                      Comentario


                      • #12
                        Re: Java:

                        gracias por la explicación

                        Comentario

                        Contenido relacionado

                        Colapsar

                        Trabajando...
                        X