方法在简单的JFrame中返回null null

问题描述:

我的.get()方法在ClassSolv似乎无法赶上Stringchosen1。如果我做System.out.print(print)则返回null。这是为什么发生? 我想要做的是能够从ComboBox中选择一个项目,然后当我单击JButton时,相应的值出现在JTextField中。方法在简单的JFrame中返回null null

这里是我的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     
} 

这里是我的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; 
} 
} 

public class JFrame extends javax.swing.JFrame 

使用你的类一个合适的名字。类名称应该是描述性的,当然不应该是您正在扩展的类的“JFrame”。

chosen1 = (String)combo_solvents.getSelectedItem(); 
JFrame obj = new JFrame(); 
String print = obj.run_s(); 
textField.setText(print); 

为什么要在组合框中选择一个项目时创建一个新的“框架”对象?

+0

回答你的第二个问题:我不知道。那很愚蠢。我改变了,现在它的工作。谢谢 – loolipop