我目前正在为一所学校的团队项目工作,我在fieldMap中的textFields上遇到了困难的setText()。我可以使用fieldMap.get(fieldTitle.values()[i])从他们那里获取值,但由于我对HashMaps和gbcs缺乏了解,我无法弄清楚如何将文本设置到文本字段
class InstructorEditorPanel extends JPanel {
enum FieldTitle {
B_NUMBER("B Number"), FIRST_NAME("First Name"), LAST_NAME("Last Name");
private String title;
private FieldTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
};
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
public InstructorEditorPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Instructor Editor"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
GridBagConstraints gbc;
for (int i = 0; i < FieldTitle.values().length; i++) {
FieldTitle fieldTitle = FieldTitle.values()[i];
gbc = createGbc(0, i);
add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
gbc = createGbc(1, i);
JTextField textField = new JTextField(10);
add(textField, gbc);
fieldMap.put(fieldTitle, textField);
}
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
public String getFieldText(FieldTitle fieldTitle) {
return fieldMap.get(fieldTitle).getText();
}
答案 0 :(得分:2)
如果您必须在文本字段中设置文字,请在该textField上调用setText方法。
由于您已经通过调用
检索textFieldfieldMap.get(fieldTitle.values()[i])
您可以通过调用setText方法来设置文本,如:
fieldMap.get(fieldTitle.values()[i]).setText('Something');
答案 1 :(得分:1)
只是为了对称原因而猜测:
public void setFieldText (FieldTitle fieldTitle, String toSet) {
fieldMap.get (fieldTitle).setText (toSet);
}
您可以将该方法放入InstructorEditorPanel,其他方法是。要调用它,您必须访问该类的内部枚举:
public class TestFrame extends JFrame {
public TestFrame () {
super ("testframe");
setSize (400, 400);
setVisible (true);
}
public static void main (String [] args)
{
InstructorEditorPanel iep = new InstructorEditorPanel ();
TestFrame tf = new TestFrame ();
tf.add (iep);
iep.setFieldText (InstructorEditorPanel.FieldTitle.FIRST_NAME, "Donald");
}
}
经过测试,工作过。
答案 2 :(得分:0)
fieldMap.get(fieldTitle).setText("String to set");