gpt4 book ai didi

java - 通过按钮调用时不显示用户输入。使用 Java 数组列表

转载 作者:行者123 更新时间:2023-12-01 17:04:05 24 4
gpt4 key购买 nike

目前正在开发一个 Java Swing 应用程序来存储大学生评估的名称、类型和权重。他们可以使用 GUI 按钮添加多个评估(以存储在 ArrayList 中),并使用 GUI 上的“显示”按钮显示输入。我已经寻找了我的问题的答案,我是 Java 初学者,正在使用带有 GUI 的可实例化类,并且不理解使用扫描仪的相关问题,如果我错了,请道歉。

我的代码中没有错误,但是当我按下显示按钮时,名称、类型和权重字段为空。

这是我的 GUI 的图片:

这是我的评估类,我在其中声明变量/getter 和 setter:

package arraylistexample;

public class Assessment {
private String name;
private String type;
private double weighting;
private int count;

public Assessment(){
name = new String();
type = new String();
count = 0;
weighting = 0.0;

}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public double getWeighting() {
return weighting;
}

public void setWeighting(double weighting) {
this.weighting = weighting;
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}

}

这是我的 GUI 的相关源代码,其中包含 ArrayList 和添加/显示按钮。我还没有编写其他按钮的代码:

package arraylistexample;

import java.util.ArrayList;
import javax.swing.JOptionPane;


public class AssessmentGUI extends javax.swing.JFrame {

private ArrayList<Assessment> aList;
private String name, type;
private double weighting;
private int count;

/**
* Creates new form AssessmentGUI
*/
public AssessmentGUI() {
initComponents();
aList = new ArrayList<>();
name = new String();
type = new String();
weighting = 0.0;
count = 0;

}


private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//get Textfield text

name = nameTf.getText();
type = typeTf.getText();
weighting = Double.parseDouble(weightingTf.getText());

Assessment a = new Assessment();
a.getName();
a.getType();
a.getWeighting();

//add to arraylist
aList.add(a);

//increment counter
count++;
}



private void displayBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
for(int i = 0; i < aList.size();i++) {
JOptionPane.showMessageDialog(null, "Name: "+aList.get(i).getName()+"\n Type: "+aList.get(i).getType()+"\n Weighting: "+aList.get(i).getWeighting());
}


}

最佳答案

您必须使用设置方法

删除:

a.getName();
a.getType();
a.getWeighting();

添加:

a.setName(nameTf.getText());
a.setType(TypeTf.getText());
a.setWeighting(Double.parseDouble(weightingTf.getText()));

循环中的 JOptionPane 也不是显示结果的好解决方案

关于java - 通过按钮调用时不显示用户输入。使用 Java 数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com