comment obtenir le texte d'un champ de texte à une variable?

je veux récupérer la valeur de la txt champ val1 et val2 et de les stocker dans des variables n1 et n2. alors n1 et n2 seront analysés pour obtenir la valeur de la calculatrice. voici le code:

    public class CalcUI extends javax.swing.JFrame {
String n1 = val1.getText();
String n2 = val2.getText();
double num1 = Double.parseDouble(n1);
double num2 = Double.parseDouble(n2); 
/**
* Creates new form CalcUI
*/
public CalcUI() {
initComponents();
}
/**
* 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() {
val1 = new javax.swing.JTextField();
val2 = new javax.swing.JTextField();
plus = new javax.swing.JButton();
multiply = new javax.swing.JButton();
clr = new javax.swing.JButton();
exit = new javax.swing.JButton();
minus = new javax.swing.JButton();
divide = new javax.swing.JButton();
ans = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
plus.setText("+");
plus.setMaximumSize(new java.awt.Dimension(41, 41));
plus.setMinimumSize(new java.awt.Dimension(41, 41));
plus.setPreferredSize(new java.awt.Dimension(41, 41));
plus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
plusActionPerformed(evt);
}
});
multiply.setText("*");
multiply.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
multiplyActionPerformed(evt);
}
});
clr.setText("Clear");
clr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clrActionPerformed(evt);
}
});
exit.setText("Exit");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
minus.setText("-");
minus.setMaximumSize(new java.awt.Dimension(41, 41));
minus.setMinimumSize(new java.awt.Dimension(41, 41));
minus.setPreferredSize(new java.awt.Dimension(41, 41));
minus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
minusActionPerformed(evt);
}
});
divide.setText("/");
divide.setMaximumSize(new java.awt.Dimension(41, 41));
divide.setMinimumSize(new java.awt.Dimension(41, 41));
divide.setPreferredSize(new java.awt.Dimension(41, 41));
divide.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divideActionPerformed(evt);
}
});
ans.setBorder(javax.swing.BorderFactory.createEtchedBorder());
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.LEADING)
.addComponent(val1)
.addComponent(val2)
.addGroup(layout.createSequentialGroup()
.addComponent(clr)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(exit)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(134, 134, 134)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(multiply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(plus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(minus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(divide, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(143, 143, 143))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(ans, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(val1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(val2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ans, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(clr)
.addComponent(exit))
.addContainerGap())
);
pack();
}//</editor-fold>
private void plusActionPerformed(java.awt.event.ActionEvent evt) {                                     
double add = num1 + num2;
ans.setText(Double.toString(add));
//TODO add your handling code here:
}                                    
private void minusActionPerformed(java.awt.event.ActionEvent evt) {                                      
double min = num1 - num2;
ans.setText(Double.toString(min));                                     
//TODO add your handling code here:
}                                     
private void divideActionPerformed(java.awt.event.ActionEvent evt) {                                       
double div = num1 / num2;
ans.setText(Double.toString(div));
//TODO add your handling code here:
}                                      
private void exitActionPerformed(java.awt.event.ActionEvent evt) {                                     
System.exit(0);
//TODO add your handling code here:
}                                    
private void clrActionPerformed(java.awt.event.ActionEvent evt) {                                    
val1.setText("");
val2.setText("");
ans.setText("");
//TODO add your handling code here:
}                                   
private void multiplyActionPerformed(java.awt.event.ActionEvent evt) {                                         
double mult = num1 * num2;
ans.setText(Double.toString(mult));   
//TODO add your handling code here:
}                                        
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
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(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CalcUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CalcUI.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 CalcUI().setVisible(true);
}
});
}
//Variables declaration - do not modify
private javax.swing.JLabel ans;
private javax.swing.JButton clr;
private javax.swing.JButton divide;
private javax.swing.JButton exit;
private javax.swing.JButton minus;
private javax.swing.JButton multiply;
private javax.swing.JButton plus;
private javax.swing.JTextField val1;
private javax.swing.JTextField val2;
//End of variables declaration

}

le problème est que, dans la déclaration

String n1 = val1.getText();
String n2 = val2.getText();

j'obtiens une erreur whioch dit illégal référence vers l'avant. comment puis-je résoudre ce problème?

cela a été fixée.

maintenant quand j'utilise le code suivant:

    public class CalcUI extends javax.swing.JFrame {

Double num1 ;
Double num2 ;

/**
* Creates new form CalcUI
*/
public CalcUI(){
val1 = new javax.swing.JTextField();
val2 = new javax.swing.JTextField();
num1 = Double.parseDouble(val1.getText());
num2 = Double.parseDouble(val2.getText()); 
initComponents();
}

j'obtiens une erreur qui dit:

    Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at CalcUI.<init>(CalcUI.java:24)
at CalcUI$7.run(CalcUI.java:227)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

comment puis-je résoudre ce problème? quel est le problème avec le code?

  • Astuce: Où est le "équivaut à" bouton?
InformationsquelleAutor LightMikeE | 2012-10-29