How to validate SWT form? - java

Label label1 = new Label(container, SWT.NULL);
label1.setText("Enter the Password ");
text1 = new Text(container, SWT.BORDER | SWT.PASSWORD);
text1.setText("");
text1.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (!text5.getText().isEmpty()) {
setPageComplete(false);
}
}
});
hi, i am creating form using SWT in eclipse can anyone tell me how to validate that form entry above is the sample code of that..actually i want to validate password field it should be minimum length of 6.How to do this please reply.

You can use a Message Manager, as described in Eclipse Form article.
As discussed above, support has been added to show messages in the form heading. To make the handling of multiple messages within a form easier, a message manager has been made available in 3.3 through the IManagedForm interface. The manager is provided as an interface (IMessageManager).
The message manager will track multiple messages for the user at a time and will show text-based on the most severe message present at any given time (ERROR > WARNING > INFO).
It also provides the ability, when adding a message, to associate a control with it. If this is done, the message manager will decorate the specified control with an image appropriate to the message type.
Regarding the specific issue, you can look at similar implementations of this problem, like the org.eclipse.team.internal.ccvs.ui.wizards.ConfigurationWizardMainPage class:
// Password
createLabel(g, CVSUIMessages.ConfigurationWizardMainPage_password);
passwordText = createPasswordField(g);
passwordText.addListener(SWT.Modify, listener);
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == passwordText) {
// check its length

Related

setDefaultButton not working as expected

public JoinChatClient(String serverAddress, String chatName)
{
chatWindow.getContentPane().add(sendButton, "South");
chatWindow.getContentPane().add(splitPane, "Center");
chatWindow.setSize(800,500);
sendButton.addActionListener(this);
chatWindow.setTitle("Chat Room");
chatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
splitPane.setDividerLocation(350);
sendButton.setBackground(Color.gray);
sendButton.setForeground(Color.red);
outChatTextArea.setEditable(false);
inChatTextArea.setFont (new Font("default",Font.ITALIC,20));
outChatTextArea.setFont(new Font("default",Font.BOLD,20));
inChatTextArea.setLineWrap(true);
outChatTextArea.setLineWrap(true);
inChatTextArea.setWrapStyleWord(true);
outChatTextArea.setWrapStyleWord(true);
inChatTextArea.setText("Enter text to be sent here.");
outChatTextArea.setText("You can move the separator bar!");
inChatTextArea.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if(inChatTextArea.getText().equals("Enter text to be sent here."))
{
inChatTextArea.setText("");
inChatTextArea.setFont(new Font("default",Font.BOLD,20));
}
}
public void focusLost(FocusEvent e) {
if(inChatTextArea.getText().isEmpty())
{
inChatTextArea.setFont (new Font("default",Font.ITALIC,20));
inChatTextArea.setText("Enter text to be sent here.");
}
}
});
chatWindow.getRootPane().setDefaultButton(sendButton);
chatWindow.setVisible(true);
}
I've looked over all the threads I could find concerning this, and I cannot figure out why hitting ENTER doesn't activate the actionPerformed method attached to sendButton. Is it because the text field has a FocusListener?
Things I've tried:
changing the statement to target the specific text field (inChatTextArea)
moved the setVisible statement to the end
targeted different parts of the GUI when hitting enter
Bear in mind I've only included the code that builds the GUI in an attempt to waste less of your time.
What I want: Ideally, I want to keep my FocusListener (or something like it) so that I can display the "text field hint." I would like to be able to hit ENTER to send the user's text while the inChatTextArea field is focused.
If a component on the JFrame has focus, and can accept an enter key press, such as one of the JTextAreas, then the enter presses will go to that component and not to the default button. For the default button to work, then the JFrame or the button or some other component that does not accept enter key presses, needs to have focus. I'm guessing that one of your JTextAreas has stolen the focus, and that this is messing you up.
This question is old, but I found it when having the same issue. So I hope others might find it useful.
I figured out that getRootPane() will return null if the component is trying to access the root pane too early, e.g. under construction of the component.
Hence, I propose to use SwingUtilities.invoke(Runnable) to postpone setting the default button on the root pane, and also to request the focus to the button.
So this method could be a helper method on a class to extend from:
protected void setDefaultButton(JButton button) {
// Uses invoke later, as getRootPane() might return null if the method is called under construction
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JRootPane rootPane = getRootPane();
if (rootPane != null) {
rootPane.setDefaultButton(button);
}
button.requestFocus(); // set the focus on the button
}
});
}

How to validate fields in vaadin made form

I am making a Java project with vaadin. Right now I have a user registration form looking like that:
public class RegistrationComponent extends CustomComponent implements View {
public static final String VIEW_NAME = "Registration";
public RegistrationComponent(){
Panel panel = new Panel("Registration Form");
panel.setSizeUndefined();
FormLayout content = new FormLayout();
CheckBox checkBox1, checkBox2, checkBox3;
checkBox1 = new CheckBox("Check Box 1");
checkBox2 = new CheckBox("Check Box 2");
checkBox3 = new CheckBox("Check Box 3");
checkBox1.setRequired(true);
checkBox2.setRequired(true);
TextField mailTextField = new TextField("Email Address");
TextField passwordTextField = new TextField("Password");
TextField confirmPasswordTextField = new TextField("Confirm Password");
final Button submitButton = new Button("Submit");
content.addComponent(mailTextField);
content.addComponent(passwordTextField);
content.addComponent(confirmPasswordTextField);
content.addComponent(checkBox1);
content.addComponent(checkBox2);
content.addComponent(checkBox3);
content.addComponent(submitButton);
content.setSizeUndefined(); // Shrink to fit
content.setMargin(true);
panel.setContent(content);
setCompositionRoot(panel);
//listeners:
submitButton.addClickListener(new Button.ClickListener() {
public void buttonClick(Button.ClickEvent event) {
//
}
});
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event){
//
}
}
Of course, the form doesn't do anything other than being displayed.
What I wanna do, is make Vaadin display error messages next to fields if some requirements are not met. The requirements themselves are not that important (lets say I want email field to contain at least 8 characters). What I wanna know, is: is there any simple built-in way to do that? I was here:
https://vaadin.com/api/com/vaadin/data/Validator.html
but I dont understand how to use a validator, or even if that is what I want to use. I've been looking all over google for usage examples, but so far with no success. Thanks for help!
Vaadin 7
The following applies to Vaadin 7. The validate() method has been removed in Vaadin 8.
All Field types in Vaadin implement the Validatable interface which has the addValidator method that accepts an implementation of Validator as parameter.
So to add a validator that checks the length of the value of a TextField, you would do this:
TextField textField = new TextField();
textField.addValidator(
new StringLengthValidator(
"Must be between 2 and 10 characters in length", 2, 10, false));
Vaadin fields have built-in functionality for displaying the validation errors to the user. By default, the field will be highlighted in red and an exclamation mark will appear next to the field, hovering over this will show a more detailed message to the user.
Automatic Validation
By default, the field will now validate on the next server request which contains a changed value for the field to the server. If the field is set to 'immediate', this will happen when the field looses focus. If the field is not immediate, validation will happen when some other UI action triggers a request back to the server.
Explicit Validation
Sometimes, you may want to exercise more control over when validation happens and when validation errors are displayed to the user. Automatic validation can be disabled by setting validationVisible to false.
textField.setValidationVisible(false);
When you are ready to validate the field (e.g. in a button click listener) you can explicitly call the validate (you can also use commit() if it is a buffered field) method on the TextField instance to trigger validation. validate will throw an InvalidValueException if the value is invalid. If you want to use the builtin display of validation errors included in the TextField component you will also have to set validationVisible back to true.
try {
textField.validate();
} catch (Validator.InvalidValueException ex) {
textField.setValidationVisible(true);
Notification.show("Invalid value!");
}
Note that once validationVisbible is set back to true, validation will happen implicitly so you must remember to set it back to false on the next request if you want to maintain explicit control over validation.
Validation Messages
Individual validation messages can be extracted from the instance of Validator.InvalidValueException which is thrown when validate() or commit() is called.
try {
textField.validate();
} catch (Validator.InvalidValueException ex) {
for (Validator.InvalidValueException cause: ex.getCauses()) {
System.err.println(cause.getMessage());
}
}
Validators
Validators implement the Validator interface and there are several useful validators shipped with Vaadin. Check out the API docs for more information on these: https://vaadin.com/api/7.4.5/com/vaadin/data/Validator.html
Custom validators are easy to implement, here is an example taken from the Book of Vaadin:
class MyValidator implements Validator {
#Override
public void validate(Object value)
throws InvalidValueException {
if (!(value instanceof String &&
((String)value).equals("hello")))
throw new InvalidValueException("You're impolite");
}
}
final TextField field = new TextField("Say hello");
field.addValidator(new MyValidator());
field.setImmediate(true);
layout.addComponent(field);
Problem solved,
Apparently I wasn't looking deep enough before. Here it comes:
field.addValidator(new StringLengthValidator("The name must be 1-10 letters (was {0})",1, 10, true));
all details here:
https://vaadin.com/book/-/page/components.fields.html
Vaadin 8
Using Vaadin 8 com.vaadin.data.Binder easily you can validate your fields. See Binding Data to Forms in the manual.
Create a TextField and a binder to validate the text field.
public class MyPage extends VerticalLayout{
TextField investorCode = new TextField();
Binder<MyBean> beanBinder = new Binder<MyBean>();
//Info : MyBean class contains getter and setter to store values of textField.
public MyPage (){
investorCode.addValueChangeListener(e->valueChange(e));
addComponent(investorCode);
bindToBean();
}
private void bindToBean() {
beanBinder.forField(investorCode)
.asRequired("Field cannot be empty")
.withValidator(investorCode -> investorCode.length() > 0,"Code shold be atleast 1 character long").bind(MyBean::getInvestorCode,MyBean::setInvestorCode);
}
//rest of the code .....
private void valueChange(ValueChangeEvent<String> e) {
beanBinder.validate();
}
}
Call validate() from binder will invoke the validation action.
beanBinder.validate();
to validate the filed. You can call this from anywhere in the page. I used to call this on value change or on a button click.

How to add a hook to close event for a particular editor in Netbeans?

I need to do something when an editor for a particular document is closed. I have a following code:
FileObject fobj = FileUtil.toFileObject(file);
final DataObject dobj = DataObject.find(fobj);
if (dobj != null) {
EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
StyledDocument doc = ec.openDocument();
// Here I would like to add a listener for close event, for the editor window that was opened
}
Is there a way of doing this? Or can I at least hook a listener for global editor closing, so that I get notified of each editor window being closed? I guess in that case I would be somehow able to decide whether the given editor window is the one I am interested in.
OK, I found a working solution, however, it still feels like an ugly workaround. I do not understand why all solutions to my problems with NetBeans IDE look so ugly. I can see that the platform aims to prepare a nice space for creating new editors and other pluggable components, however, when one wants just to listen to existing components (Editors, etc.), it becomes a nightmare.
In my current solution I add a property change listener to TopComponent Registry and listen for a "tcClosed" property to change, and then I test whether it has an EditorCookie (so whether it is an editor) and whether the cookie is the same one that I want to listen to:
TopComponent.getRegistry().addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("tcClosed") && evt.getOldValue() == null) {
EditorCookie cookie = ((TopComponent) evt.getNewValue()).getLookup().lookup(EditorCookie.class);
// I have to remember editor cookie to compare it to the one that is closed
// so that I can find out whether it is the editor I want to listen to
if (cookie != null && cookie.equals(ParentClass.this.getRememberedEditorCookie())) {
// Do my stuff
}
}
}
});
However, if anyone knows a better solution, I will be happy to hear about it.
By accident I stumbled about something which may help you:
EditorCookie.Observable cookie = dataObject.getLookup().lookup(EditorCookie.Observable.class);
cookie.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
// Do your stuff
}
});

How to Subscribe to GUI Events in Other JFrames

What is the best practice for subscribing to events from another JFrame? For example, I have a "settings" form, and when the user presses okay on the settings form, I want the main form to know about this so it can retrieve the settings.
Thanks.
Here is my ideal interface:
public void showSettingsButton_Click() {
frmSettings sForm = new sForm(this._currentSettings);
//sForm.btnOkay.Click = okayButtonClicked; // What to do here?
sForm.setVisible(true);
}
public void okayButtonClicked(frmSettings sForm) {
this._currentSettings = sForm.getSettings();
}
Someone publishes an Event, that something has changed, here the settings. A subscriber that registered for this specifig event, gets notified about it and can do his work, here get the settings. This is called publisher/subscriber.
For this you can use Eventbus or implementing something smaller on your own.
One approach is to have only a single JFrame. All the other 'free floating top level containers' could be modal dialogs. Access the the main GUI will be blocked until the current dialog is dismissed, and the code in the main frame can check the settings of the dialog after it is dismissed.
For anyone interested, here is what I ended up going with. I'm not sure if it's the best way, but it is working for my purposes.
// Method called when the "Show Settings" button is pressed from the main JFrame
private void showSettingsButton_Click() {
// Create new settings form and populate with my settings
frmSettings sForm = new frmSettings(this.mySettings);
// Get the "Save" button and register for its click event...
JButton btnSave = sForm.getSaveButton();
btnSave.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
SaveSettings(sForm);
}
});
// Show the settings form
sForm.setVisible(true);
}
// Method called whenever the save button is clicked on the settings form
private void SaveSettings(frmSettings sForm) {
// Get the new settings and assign them to the local member
Settings newSettings = sForm.getSettings();
this.mySettings = newSettings;
}
And if, like me, you are coming from a .NET perspective, here is the C# version:
private void showSettingsButton_Click(object sender, EventArgs e)
{
frmSettings sForm = new frmSettings(this.mySettings);
sForm.btnSave += new EventHandler(SaveSettings);
sForm.Show();
}
private void SaveSettings(object sender, EventArgs e)
{
frmSettings sForm = (frmSettings)sender; // This isn't the exact cast you need..
Settings newSettings = sForm.Settings;
this.mySettings = newSettings;
}

Java - change focus on key press

I am writing a Java Application for Data Entry using Eclipse and SWT. Naturally it has a great many Text objects.
What I would like to happen is that when user enters something into one field focus automatically changes to the next field.
Thanks in advance
final Text textBox = new Text(shell, SWT.NONE);
textBox.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (x.getText().length() == 1); {
x.traverse(SWT.TRAVERSE_TAB_NEXT);
}
}
});
final Text textBox = new Text(shell, SWT.NONE);
textBox.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
if (textBox.getText().equals("") == false) {
textBox.traverse(SWT.TRAVERSE_TAB_NEXT);
}
}});
You may also want to have a look at the VerifyListener interface. See this interesting blog post for a caveat though: http://eclipsenuggets.blogspot.com/2008/10/eclipse-bug-patterns-selfish-validation.html
I assume you want to change the focus after the field has been filled. I suggest using a DocumentListener (or whatever SWT calls it) to be notified of changes to the field's content: if it has the right number of characters, jump to the next field.

Categories

Resources