gpt4 book ai didi

java - 尝试为文本字段设置文本

转载 作者:行者123 更新时间:2023-12-02 00:24:32 25 4
gpt4 key购买 nike

我目前正在学校的一个团队项目中工作,但在 fieldMap 中的 textFields 上 setText() 时遇到困难。我可以使用 fieldMap.get(fieldTitle.values()[i]) 从它们获取值,但由于我对 HashMap 和 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();
}

最佳答案

如果您必须在文本字段中设置文本,请调用 setText该文本字段上的方法。

因为您已经通过调用来检索 textField

fieldMap.get(fieldTitle.values()[i])

您可以通过调用 setText 方法来设置文本,例如:

fieldMap.get(fieldTitle.values()[i]).setText('Something');

关于java - 尝试为文本字段设置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10284388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com