Skip to content

Instantly share code, notes, and snippets.

@paul-hammant
Created April 12, 2019 10:34
Show Gist options
  • Save paul-hammant/fb4f70b7b534386530d1fa48640ccf8e to your computer and use it in GitHub Desktop.
Save paul-hammant/fb4f70b7b534386530d1fa48640ccf8e to your computer and use it in GitHub Desktop.
MVC example for a single "text field" form
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class Foo {
public static void main(String[] args) {
// setup model
Document model = new PlainDocument();
// setup view
final JTextField view = new JTextField(model, "howdie", 30);
placeViewInFrameAndShowIt(view);
// controller logic
view.addActionListener(a -> {
try {
printModel("action event change (view initiated)", model);
} catch (BadLocationException e) {
throw new UnsupportedOperationException(e);
}
});
// change model value after 5 seconds (demo)
new Thread() {
@Override
public void run() {
try {
sleep(5000);
model.remove(0, model.getLength());
model.insertString(0, "goodbye", null);
printModel("model changed outside of view", model);
} catch (InterruptedException | BadLocationException e) {
throw new UnsupportedOperationException(e);
}
}
}.start();
}
private static void placeViewInFrameAndShowIt(JTextField view) {
JFrame frame = new JFrame("hello") {{
getContentPane().add(new JPanel() {{
add(view);
}});
setSize(500, 70);
}};
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private static void printModel(String preamble, Document model) throws BadLocationException {
System.out.println(preamble + ": " + model.getText(0, model.getLength()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment