2017-08-28 1 views
1

Ma méthode .get() dans le ClassSolv ne semble pas être en mesure d'attraper le Stringchosen1. Si je fais System.out.print(print) alors null est retourné. Pourquoi cela arrive-t-il? Ce que je veux faire est de pouvoir sélectionner un élément à partir d'un ComboBox, puis lorsque je clique sur un JButton, une valeur correspondante apparaît dans un JTextField.La méthode renvoie null en JFrame simple

Voici mon JFrame Class:

public class JFrame extends javax.swing.JFrame { 

/* static field variables */ 
private String chosen1; 

public JFrame() { 
    initComponents(); 
} 

/* Auto-generated code for the JForm here*/ 

/*method for when button is clicked on JForm*/             
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {           
    chosen1 = (String)combo_solvents.getSelectedItem(); 
    JFrame obj = new JFrame(); 
    String print = obj.run_s(); 
    textField.setText(print); 
}  

public String run_s(){ 
    Solv s = new Solv(chosen1); 
    String shift = s.return_shift(); 
    return shift; 
    } 

/* main method */ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    // Auto-generated code here 
    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new JFrame().setVisible(true); 
     } 
    }); 
    } 

/* Variables declaration - do not modify */      
private javax.swing.JButton button1; 
private javax.swing.JComboBox<String> combo_impurity; 
private javax.swing.JComboBox<String> combo_solvents; 
private javax.swing.JTextField textField; 
private javax.swing.JTextField textField2; 
// End of variables declaration     
} 

Voici mon Solv class:

import java.util.HashMap; 

public class Solv { 

private final String shiftvalue; 

/* class constructor */ 

Solv(String str){ 

HashMap<String, String> hmap_s = new HashMap<>(); 

hmap_s.put("CDCl3", "7.26"); 
hmap_s.put("D2O", "4.79"); 
hmap_s.put("CD2Cl2", "5.32"); 
hmap_s.put("DMSO-d6", "2.50"); 
hmap_s.put("Acetone-d6", "2.05"); 
hmap_s.put("Benzene-d6", "7.16"); 
hmap_s.put("Acetonitrile-d3", "1.94"); 
hmap_s.put("Methanol-d4", "3.31"); 

/* get the value from the key */ 
shiftvalue = hmap_s.get(str); 
} 

/* return the value */ 
String return_shift() 
{ 
return shiftvalue; 
} 
} 

Répondre

2
public class JFrame extends javax.swing.JFrame 

Utilisez un nom propre pour votre classe. Les noms de classe devraient être descriptifs et ne devraient certainement pas être "JFrame", qui est la classe que vous étendez. Pourquoi voudriez-vous créer un nouvel objet "frame" lorsqu'un élément est sélectionné dans la combobox? Pourquoi?

+0

En réponse à votre deuxième question: Je ne sais pas. C'était stupide. J'ai changé cela et maintenant ça marche. Merci – loolipop