答案 0 :(得分:1)
使用相关密钥从地图中检索它们。
String textOfFirst = fieldMap.get("Text1").getText();
fieldMap.get("Text2").setEnabled(false);
但是正如我的意见,看起来像这种群体创作你应该设置它,所以你不需要单独引用它们。
答案 1 :(得分:1)
以下是您可以运行的示例。我正在尝试使用Map
。可能有很多代码,但您感兴趣的是这个
Map<String, JTextField> fields;
....
JTextField field = new JTextField(15);
fields.put(fieldName, field);
....
public class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
String fieldName = button.getText();
JTextField field = fields.get(fieldName);
System.out.println(field.getText());
}
}
我只是将JTextField
放在Map
中。当我想访问它时,我只使用JTextField field = fields.get("textfield name");
在下面的示例中,只需在字段中键入内容,然后单击旁边的按钮。您将看到该按钮与地图中的文本字段键具有相同的名称,因此我只是使用它来在文本字段中打印该值
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test2 {
Map<String, JTextField> fields;
Map<String, JLabel> labels;
public Test2() {
fields = new HashMap<>();
labels = new HashMap<>();
JPanel mainPanel = new JPanel(new GridLayout(10, 1));
for (int i = 1; i <= 10; i++) {
JPanel panel = createPanel("Text Field " + i);
mainPanel.add(panel);
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Test2();
}
});
}
private JPanel createPanel(String fieldName) {
JPanel panel = new JPanel();
JTextField field = new JTextField(15);
field.addActionListener(new FieldListener());
fields.put(fieldName, field);
JLabel label = new JLabel(fieldName);
label.addMouseListener(new MouseHandler());
labels.put(fieldName, label);
JButton button = new JButton(fieldName);
button.addActionListener(new ButtonListener());
panel.add(label);
panel.add(field);
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
String fieldName = button.getText();
JTextField field = fields.get(fieldName);
System.out.println(field.getText());
}
}
public class FieldListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JTextField field = (JTextField)e.getSource();
System.out.println(field.getText());
}
}
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
System.out.println(label.getText());
}
}
}