I have a text file with about a hundred code value pairs [$code
, Value
].
For example:
Sample file
$codeA
valueOfA
$codeB
valueofB
.
.
.
These values need to be initiated into textField
s, radioButton
s, checkBox
es, etc over "several panels" contained within a main Controller panel. I switch between panels through a simple card layout.
I read through the lines and use if
/else
statements to get values for the fields, which isn't efficient. I was wondering if there is a better approach, a more elegant approach maybe.
/*
* read File
*/
private void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals("$codeA")) {
panel1.txtFieldA.setText(br.readLine()));
} else if (line.equals("$codeB")) {
panel2.txtFieldB.setText(br.readLine()));
}
//.....
//.....
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2 Answers 2
Make a Map
like this
Map<String, JTextField> map = new HashMap<>();
map.put("$codeA", panel1.txtFieldA);
map.put("$codeB", panel2.txtFieldB);
and change your loop like this
String code = null;
while ((code = br.readLine()) != null) {
JTextField jtf = map.get(code);
if (jtf != null)
jtf.setText(br.readLine());
else
br.readLine();
}
-
\$\begingroup\$ Lets say, I have a group of radio buttons, check boxes. Can I just declare a hashmap of a generic object \$\endgroup\$San Mor– San Mor2015年04月22日 14:01:57 +00:00Commented Apr 22, 2015 at 14:01
I think I found a better solution. I welcome critique.
Map<String, Operate> map = map = new HashMap<String, Operate>();
map.put("$codeA", new TextFieldsOp(textField1));
map.put("$codeB", new TextFieldsOp(textField2));
map.put("$codeD", new RadBtnsOp(btnGroup));
Operate is an interface which is implemented by classes TextFieldsOp and RadBtnsOp.
public class TextFieldsOp implements Operate {
private JTextField txtF = null;
public TextFieldsOp(JTextField txtF) {
this.txtF = txtF;
}
@Override
public void execute(String str) {
txtF.setText(str);
}
}
...
public class RadBtnsOp implements Operate {
ButtonGroup btnGroup;
public RadBtnsOp(ButtonGroup btnGroup) {
this.btnGroup = btnGroup;
}
@Override
public void execute(String str) {
//set Radio Buttons here
}
}
...
/*
* read File
*/
private void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String code = null;
while ((code = br.readLine()) != null) {
Operate c = map.get(code);
if (c != null) {
c.execute(br.readLine());
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
txtFields.get(line).setText(br.readLine())
\$\endgroup\$//.....
sections. Otherwise, it may get closed as stub code. \$\endgroup\$