我似乎无法从创建的每个字段中检索值。我目前在我的actionPerformed()
方法中将f
设置为1,但我想从所有创建的字段中检索值。可能是因为并非所有字段都被使用。
请参阅以下代码
package classes;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Classes extends JFrame implements ActionListener {
private JTextField ivol, fvol;
private JLabel ilabel, flabel;
private JButton button;
private final JTextField vol1HH[] = new JTextField[10];
private final JLabel vollabel[] = new JLabel[10];
private int f;
public static void main(String[] args) {
Classes RV = new Classes();
RV.setSize(1000, 1200);
RV.createGUI();
RV.setVisible(true);
double sum = add((double) 10, (double) 20.1, (double) 30.1, (double) 40.1);
System.out.println(sum);
}
public static int add(Double... numbers) {
int result = 0;
for (Double number : numbers) {
result += number;
}
return result;
}
public void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(null);
ivol = new JTextField(20);
ivol.setBounds(150, 50, 100, 20);
fvol = new JTextField(20);
fvol.setBounds(150, 1000, 100, 20);
ilabel = new JLabel("Initial Order Volume");
ilabel.setBounds(10, 50, 150, 20);
flabel = new JLabel("Final Order Volume");
flabel.setBounds(10, 1000, 150, 20);
button = new JButton("Remaning Volume");
button.setBounds(10, 1050, 150, 20);
button.addActionListener(this);
window.add(ivol);
window.add(fvol);
window.add(ilabel);
window.add(flabel);
window.add(button);
for (int y = 100; y < 1000; y += 50) {
for (int f = 0; f < 10; f++) {
vol1HH[f] = new JTextField(10);
vol1HH[f].setName("volHH" + f);
vollabel[f] = new JLabel("HH34");
vol1HH[f].setBounds(150, y, 100, 20);
vollabel[f].setBounds(80, y, 100, 20);
window.add(vol1HH[f]);
window.add(vollabel[f]);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
//double vol;
f = 1;
double vol = Double.parseDouble(vol1HH[f].getText());
//if(e.getSource() == button) {
fvol.setText(Double.toString(vol));
}
}
答案 0 :(得分:1)
如果要从文本字段中检索所有记录并将其存储在某处。你需要有一个变量来存储。
public class Classes extends JFrame implements ActionListener {
//Your other variable declarations
String [] fieldRecords = new String[10]; //Declare array for storing textfields' data
}
现在,只需创建一个方法即可将所有输入转移到fieldRecords[]
填充为空。
public void retrieve(){
for(int x=0; x<vol1HH.length; x++)
fieldRecords[x] = vol1HH[x].getText();
}
如果您需要检索记录,只需致电retrieve()
即可。例如,当您按下按钮时 - 您可以将其放在actionPerformed()
。
public void actionPerformed(ActionEvent e) {
//Your other actions..
retrieve(); //Send all textfield data into fieldRecord[]
}
将数据保存到数组中。您可以随时打印或将其重新设置到文本字段中。
示例:强>
public void display(){
for(int x=0; x<fieldRecords.length; x++)
System.out.println(fieldRecords[x]);
}
public void load(){
for(int x=0; x<vol1HH.length; x++)
vol1HH.setText(fieldRecords[x]);
}