-
Notifications
You must be signed in to change notification settings - Fork 5
Sample 004
Michael Karneim edited this page May 9, 2018
·
1 revision
package wiki.snippets;
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.JFrame;
import org.beanfabrics.model.TextPM;
import org.beanfabrics.model.PMManager;
import org.beanfabrics.support.Validation;
import org.beanfabrics.swing.BnTextField;
/**
* Sample for extending a TextPM to add a custom validation
*/
public class Sample004 {
public static void main(String[] args) {
// We define a subclass of TextPM for holding a directory path
/**
* This is a pM for a directory path. It will be valid only
* when the directory exists.
*/
class DirectoryPathPM extends TextPM {
public DirectoryPathPM() {
PMManager.setup(this);
setMandatory(true);
}
/**
* Evaluates if the text content is a path to an existing directory.
* @return true, if the text is a path to an existing directory
*/
@Validation(message="This is not a valid directory")
public boolean isDirectory() {
return new File(this.getText()).isDirectory();
}
}
// create an instance
DirectoryPathPM model = new DirectoryPathPM();
// set the text to the path of the user's home directory
model.setText( System.getProperty("user.home"));
// create a textfield
BnTextField textfield = new BnTextField();
textfield.setColumns(30);
// bind the textfield to the model
textfield.setPresentationModel(model);
// show the textfield inside a window
JFrame frame = new JFrame("Enter path to directory");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new FlowLayout());
frame.add(textfield);
frame.setSize(400, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}