Created
April 12, 2019 10:34
-
-
Save paul-hammant/fb4f70b7b534386530d1fa48640ccf8e to your computer and use it in GitHub Desktop.
MVC example for a single "text field" form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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