罗宾和尼克都是对的。
这是如何实施他们正在讨论的内容的示例...
public class TestForm02 {
public static void main(String[] args) {
new TestForm02();
}
public TestForm02() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyForm());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class MyForm extends JPanel {
private JTextField txtNo;
private JTextField txtName;
private String partToLoad;
private Timer loadTimer;
public MyForm() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.WEST;
txtName = new JTextField(12);
txtNo = new JTextField(12);
txtName.setEnabled(false);
add(new JLabel("Parts #:"), gbc);
gbc.gridx++;
add(txtNo, gbc);
gbc.gridy++;
gbc.gridx = 0;
add(new JLabel("Description:"), gbc);
gbc.gridx++;
add(txtName, gbc);
txtNo.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
loadParts();
}
});
txtNo.getDocument().addDocumentListener(new DocumentListener() {
protected void update() {
loadTimer.restart();
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
});
loadTimer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadParts();
}
});
loadTimer.setRepeats(false);
loadTimer.setCoalesce(true);
}
protected void loadParts() {
String text = txtNo.getText();
// Don't want to trigger this twice...
if (text == null ? partToLoad != null : !text.equals(partToLoad)) {
partToLoad = text;
txtNo.setEnabled(false);
txtName.setEnabled(false);
BackgroundWorker worker = new BackgroundWorker();
worker.execute();
}
}
protected class BackgroundWorker extends SwingWorker<String, String> {
@Override
protected String doInBackground() throws Exception {
// Do you're database load here. Rather then updating the text
// field, assign it to variable and return it from here
String desc = "Some description"; // load me :D
// Inserted delay for simulation...
Thread.sleep(2000);
return desc;
}
@Override
protected void done() {
try {
String value = get();
txtName.setText(value);
txtName.setEnabled(true);
txtNo.setEnabled(true);
} catch (InterruptedException exp) {
exp.printStackTrace(); // Log these some where useful
} catch (ExecutionException exp) {
exp.printStackTrace(); // Log these some where useful
}
}
}
}
}