[英]Retrieving values from fields
我似乎无法从创建的每个字段中检索值。 我目前在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));
}
}
如果您想从文本字段中检索所有记录并将其存储在某个位置。 您需要有一个用于存储的变量。
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.