I implement OOP in my Java assignment. But when I started creating user interface and accept the input I have faced a problem. I wanted to validate the user input of jTextField from user interface using my setter method. I want a pop up to appear when user input is invalid instead of just error message. I know it can be done easily if I implement the validation code directly in the user interface. I don't know which way is better but since I already have all my setter method so I wanted to validate using setter method.
Employee Class
public void setUsername(String username){
if(username.equals(null)){
//validation method
}
User Interface
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Admin ad = new Admin();
String username = jTextField6.getText();
ad.setUsername(username);
}
Validation must be done in several layers to ensure your application accuracy .But here according to your situation you are trying to validate an user input.So it's a validation which belongs to view layer like you are validating forms in web development.So since you are using Java Swing you need to place your view validation logic inside the controller.Because of that the best way to implement it is like below.
String username = jTextField6.getText();
if(userName.isEmpty()){
//Place your error message logic here
}else{
ad.setUsername(username);
}
Related
I have a conceptual question.( some questions ! )
Let explain it with a real project.
I have a Login swing form,it has the main method and application starts from here.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
}); // this method is inside main Method
The Login Form contains some TextFields and Buttons,And also some methods.
( For example when I press the Enter Button some authenticatation and action perform )
After press Enter Button, if authenticate success it goes to another form named MainTabbedForm.
Now the question is about Object Oriented Programming and class loading.
I want to access the Login Form form the MainTabbedForm. For example I want to dispose the Login Form after authentications successfully, And wanna do it in the MainTabbedForm constructor. I write a method inside the Login class to connect the Login to the MainTabbedForm. In this way :
public void disappearForm(MainTabbedForm form) {
this.form=form; // I already has defined a MainTabbedForm field in top of the Login class
this.dispose(); // Dispose the Login class
}
And use it in the constructor of the MainTabbedForm, Before using just declare a Login Form as a field in MainTabbedForm;
public MainTabbedForm(Login login) {
this.login=login;
login.disappearForm(this)
}
But it gives me NullPointException because the Login has not initialize.
And if i make a new class of Login, of course it is a new class and will not DO the thing i want, because is a new instance and not the first created Login in main method.
Now I have a question, How can i connect these two class to each other?
Of course I can make a static method to do my job ! But i do not want to do that in this way.
I think because of this class loading and art of programming the frameworks and design patterns like OSGi and MVC and others has created, to mange loading and accessing services and objects and other things more dynamically, am i right?
Now the reply to these answers are really appreciate !
In Login you could do:
MainTabbedForm mtf = MainTabbedForm(); //create
//set the required information using setters
//for example set userName which is defined in Login to MainTabbedForm
mtf.setUserName(this.userName);
//....
this.dispose(); //when no longer needed
So let's say I have 3 files.
Accounts.java (Account class)
loginGUI.java (JForm)
displayAccountGUI.java (JForm)
when I login I input CustomerID, Pin and Account Number. Then the program checks if the 3 values I have inputted are in accounts.txt.
I also have Account a = new Account(); in both of the Jframes.
In displayAccount.java I want to display Account Number from loginGUI.java that is being stored in Account.java using a.setId(ID); but because I have Account a = new Account(); in displayAccount.java the value set before is being removed due to creation new 'Account'.
Is there any way I can access this value in some other way?
Once you've validated the user credentials, create a "session" object, which encapsulates the information you need to share. It could be the "customer ID" and "account name" information or it could be an instance of the Account class.
Pass this to your displayAccount class (removing the Account a = new Account(); and using the passed reference)
How you achieve all this will depend on how you've structured your code. Me personally, I'd have some kind of controller which displayed a login dialog. When the dialog is dismissed, I'd validate the credentials, displaying an error message if they failed. If they succeeded, I'd create a new instance of the Account class (assuming it holds enough information about the client), I'd create the "account view", passing the instance of Account to it
This is a relatively basic programming concept, consider having a look at Passing Information to a Method or a Constructor
I belive you can create a new constructor for displayAccountGUI and pass Account as a parameter. It makes sense because in the future you may need more information from the account in displayAccountGUI, like a photo or something else.
Since I don't have the privilege to add comments yet, I'll just post it here. I only know two of many ways to accomplish what you want to do to get the desired result.
pass the value via a constructor
public displayAccount(Account a){this.a = a;}
use setter method
public void setAccount(Account a){this.a = a;}
I am working on a PDF Invoice generator in Vaadin 7. The code as it stands at the time of this writing can be found here. The repo includes a crude class diagram.
My question concerns the best practice of collecting the user input from the TextField and other Vaadin components to create an instance of Invoice.
Currently it works like this:
When the user clicks the button to generate the pdf, the class VaadinInvoiceGui (a Panel) calls the method createPdf(VaadinInvoiceGui gui) in the class VaadinInvoiceController.
VaadinInvoiceController calls method getInvoiceFromForm(VaadinInvoiceGui gui) in class InvoiceMapperImpl.
InvoiceMapperIml creates and returns an Invoice (POJO) by calling get methods in the VaadinInvoiceGui that gets passed to it. These getters return the values of the components in the view.
VaadinInvoiceController takes the Invoice returned by InvoiceMapperImpl and goes on to create pdf from it etc..
The getters in VaadinInvoiceGui look like this.
public String getCustomerName() {
return infoPanel.getCustomerNameTextField().getValue().toString();
}
public String getCustomerStreet() {
return infoPanel.getCustomerStreetTextField().getValue().toString();
}
public String getCustomerCity() {
return infoPanel.getCustomerCityTextField().getValue().toString();
}
...
I really don't feel like it's a good idea to pass the whole gui class to the controller and especially to the mapper, but I'm not sure what would be a better way of doing it. I could change the method createPdf(VaadinInvoiceGui gui) to something like createPdf(String customer name, String customerStreet, ...) but the number of parameters of the method would grow huge. I could do it using setters but then it would basically be doing the object mapping in the gui which doesn't seem like a very clean idea either.
What is the proper way of doing this?
Write a bean for the data to pass around as your model. Then use the FieldGroup to bind between model and form. Wrap the model as BeanItem<Model>. Binding is either done by name (convention) or by annotation #PropertyId.
master-detail-example: https://vaadin.com/wiki/-/wiki/Main/Creating+a+master-details+view+for+editing+persons
general infos: https://vaadin.com/book/vaadin7/-/page/datamodel.html
binding in forms: https://vaadin.com/book/vaadin7/-/page/datamodel.itembinding.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create a library management system. Now, I know that the boundary cannot interact with the entity directly. The control class acts as a mediator between the boundary and the entity classes. However, when are the objects of these classes created?
First, lets talk about the login. The boundary will be the login form's UI created using Java Swing. The Controller class will be PersonController which contains a function called "validateUser()". The Entity class called User contains the use's information and accesses the database.
Now, I need to create the UI, fetch username & password from the UI using action listeners and then, create a User entity with the username & password, and then, call validateUser() method of the PersonController to check if the login is correct and the user is valid.
How do I do this? Where do I create these objects?
Here's my code till now:
public class MainClass { // main class
public static void main(String[] args) {
PersonController loginSession = new PersonController(); //UNSURE
}
}
public class PersonController {
public PersonController(){
LoginUI loginForm = new LoginUI(); //UNSURE
loginForm.setVisible(true); //UNSURE
}
//implementation of the validateUser() function
}
public class User {
private String username;
private String password;
private String role;
private String name;
private String phone;
private String email;
// get & set methods and accessing the database
}
public class LoginUI{
//entire code for the UI in Java Swing created using Netbeans IDE
}
To my mind the process should work something like this...
You have three elements, the UI, the model and the controller.
The UI presents choices to the user...
The model will be required to create a User object (as your UI should not have the knowledge of how this is actually achieved).
The controller will be responsible for responding to events from the UI and making decisions on what it should do.
When the user types in there values and clicks the "accept" action (what ever it might be), the controller captures that event and requests from the UI a User object. The UI takes the information entered by the user and asks the model to create a User object with these values.
The controller can they validate the User object.
At any point any part of the process may choose to throw an exception. As the UI is the only part of the system that can actually talk back to the user, it's the UI's responsibility to show these errors.
The basic work flow might look something like this...
Create the model, form and controller.
Add the model to the form, add the form to the controller.
The interaction between these distinct elements MUST be done via interfaces where ever possible. No part should know more about the other part then it absolutely needs to - IMHO.
My first step would be - get it clear in your mind what it is you want to achieve. Work out who is responsible for what and design the bridges you need to connect them together
In play 2.0 you can get the request binding with validation done (via annotations) by :
ABCForm abcForm=(ABCForm)form(ABCForm.class).bindFromRequest().get();
The problem I have is , I want to get the validation done after trimming the form values.
So is there a way to either defer or call the validation stuff post binding in play 2.0 ?
Binding and validation are combined. So validation after the binding is not possible, as far as I know. However you can create a validate() method, in which you trim your values before validating them. For example:
public class User {
public String name;
public String validate() {
name.trim
if(name == "") {
return "Name is required";
}
return null;
}
}
The validate() method will be invoked when you bind a form. So you can make sure your data is valid, but errors won't be automatically added to the Form.Field objects. So it is certainly a nice solution.
There are also pretty much discussions about Form validation in Play's Google Group, so if you want to know more about the binding/validation problems I recommend reading them: https://groups.google.com/forum/#!searchin/play-framework/%5B2.0%5D$20validation.
If you need to modify your values before validation. You can create a setter for your field and do your trims there.