将文件中的数据读入java文本字段
你好,我有个问题 我想从文本文件中读取数据,每个数据都在不同的行中,看起来像这样 我有多达行的文本字段 jTextField1,jTextField2。。。 我想把这些数据。。。我真的不知道怎么处理它 jTextField1的值应为599 jTextField2的值应为1188将文件中的数据读入java文本字段,java,textfield,Java,Textfield,你好,我有个问题 我想从文本文件中读取数据,每个数据都在不同的行中,看起来像这样 我有多达行的文本字段 jTextField1,jTextField2。。。 我想把这些数据。。。我真的不知道怎么处理它 jTextField1的值应为599 jTextField2的值应为1188 不知道怎么做。你能帮我吗伙计们:你可以使用FileReader/BufferedReader或Scanner逐行读取文件: String filename = "path/to/the/file/with/numbers
不知道怎么做。你能帮我吗伙计们:你可以使用FileReader/BufferedReader或Scanner逐行读取文件:
String filename = "path/to/the/file/with/numbers.txt";
try(BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
int currentIndex = 1;
while((line = reader.readLine()) != null) {
// see further on how to implement the below method
setTextFieldValue(currentIndex, line.trim());
currentIndex++
}
}
要实现setTextFieldValue,您有两个选项:
编写一个开关大小写,将索引映射到相应的字段
按照@zlakad在注释中的建议,制作索引->字段的映射或数组
使用反射按字段名称获取字段
以上所有选项都有其利弊,这取决于上下文。下面我将展示如何使用反射实现它,因为其他两个选项非常简单:
void setTextFieldValue(int index, String value) {
// assuming the fields belong to the same class as this method
Class klass = this.getClass();
try {
Field field = klass.getField("jTextField" + index);
JTextField text = (JTextField)field.get(this);
text.setText(value);
} catch (NoSuchFieldException | IllegalAccessException e) {
// throw it further, or wrap it into appropriate exception type
// or just and swallow it, based on your use-case.
// You can throw a custom checked exception
// and catch in the caller method to stop the processing
// once you encounter index that has no corresponding field
}
}
你到底有什么问题?读取文件?设置文本字段的文本?你试过什么?我不知道如何阅读并将其输入文本字段:去查阅一些教程或在课堂上集中注意力。@Sedrick,我自己学习,找不到可以帮助我的东西,我给出了我将要给出的建议。也许有人会来给你想要的。好像你想对我做些什么。也许你能提供一些生活上的帮助?回答得好。但是,我认为实现setTextFieldValue还有第四种方法-初始化JTextField数组,如JTextField[]jTextFields=new JTextField[NO_of_DATA],并将其放入父容器中。@GGrela SO不是一个代码编写服务,如果我的回答不足以让你自己开始做某事,你应该去其他地方寻求帮助。
void setTextFieldValue(int index, String value) {
// assuming the fields belong to the same class as this method
Class klass = this.getClass();
try {
Field field = klass.getField("jTextField" + index);
JTextField text = (JTextField)field.get(this);
text.setText(value);
} catch (NoSuchFieldException | IllegalAccessException e) {
// throw it further, or wrap it into appropriate exception type
// or just and swallow it, based on your use-case.
// You can throw a custom checked exception
// and catch in the caller method to stop the processing
// once you encounter index that has no corresponding field
}
}