【问题标题】:Method returns null in simple JFrame方法在简单的 JFrame 中返回 null
【发布时间】:2017-08-28 19:23:14
【问题描述】:

我在Class Solv 中的.get() 方法似乎无法捕捉到String chosen1。如果我执行System.out.print(print),则返回null。为什么会这样? 我想要做的是能够从ComboBox中选择一个项目,然后当我点击JButton时,对应的值会出现在JTextField中。

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

【问题讨论】:

    标签: java swing class object hashmap


    【解决方案1】:
    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);
    

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

    【讨论】:

    • 回答你的第二个问题:我不知道。那是愚蠢的。我改变了它,现在它可以工作了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-07-18
    • 2021-07-11
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多