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
Related
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);
}
I am a total newbie with Codename One and have been studying up by watching the various tutorials etc. But there is a basic concept that I just can't seem to grasp.
When I design a form in the GUIBuilder, how do I reference the form from my code?
I.e. I designed my form in the UI Builder. Now in my main source code, I would like to add a toolbar to the form. Inside the GUIBuilder the form is called "Main", but statements such as Main.show(), Main.hide() etc do not work.
I managed to get the form "imported" for lack of a better word by using
private Form home;
...
...
home=Display.getInstance().getCurrent();
...
home.getToolbar().addCommandToOverflowMenu(edit);
Which works, but surely there must be a way of accessing the form directly without having to get the currently active instance? i.e. Something like
Main.getToolbar().addCommandToOverflowMenu(edit);
You can override the beforeShow() and postShow() of your form and just reference the parameter which represents the form.
To add commands, it's advisable that you do that in the beforeShow() method and long process like remote data fetching should be done in postShow().
For instance, let's say your form name is Main and was created in GUI Builder, you can do the following:
#Override
protected void beforeMain(final Form f) {
f.removeAllCommands();
Toolbar toolbar = new Toolbar();
f.setToolbar(toolbar);
toolbar.setTitleComponent(new Label("My Form Name", "Title"));
toolbar.addCommandToOverflowMenu(edit);
toolbar.addCommandToRightBar(backCommand);
f.setBackCommand(backCommand);
...
}
#Override
protected void postMain(final Form f) {
//fetch remote data here
...
}
I'm creating a Java Application that represents a school. My aim is to keep the application open for new features, so I'm trying to apply some Design Patterns to it.
What I have so far is a HSQLDB connected to my program.
In the database one can store
pupils
courses
years
exams
grades
The current structure is as follows:
there are classes for each of the objects that contain the attributes + setters and getters
for each object there is a DAO that manages the CRUD operations on the DB
each DAO implements a GenericDAO interface
If i want to create a new pupil i can call:
PupilDao pupil = new PupilDao();
pupil.connectToDB();
pupil.add(new Pupil(name, age,...));
pupil.disconnectDB();
Every DAOs connectToDB() and disconnectDB() methods point to a DBuser-Classes connect() and disconnect() methods. So if I want to change the connection, there's only one place to do so.
So far, those operations work.
My questions are the:
1.) Is the current design a proper use of DAOs? I'm asking because i would rather have one
Dao for all objects because right now there's a lot of repetitive code in the DAOs. (e.g. get, update, delete...)
Now that the DB-Access works, I want to create a GUI using Swing. I have some experience doing this although not with the MVC-Pattern.
2.) As far as I understand, the DAOs + my object classes would be the Model here. Is that correct?
3.) My understanding of MVC is that in my View-Class (i.e. the GUI) I set listeners for my actions which point to different Controller-Classes implementing the ActionListener interface and in my Controller-Classes I would for example have a actionPerformed() that creates a new Pupil (using the DAO / Model - Classes). Am I on the right track here?
4.) Is it favourable to have one big Controller managing all actions over having different Controllers?
I'm asking those questions because I read/watched a lot about patterns/OO-Design and want to make sure my understanding is correct.
Furthermore I highly appreciate your thoughts on my design! What could be done more flexible or better to maintain later?
Thanks in advance for every suggestion and sorry for the somewhat long explanation!
Felix
While I still can't answer my questions for sure, I think I found a suitable way
for me and want to share the design (suggestions/answers are still appreciated!).
1) The applications entry-point is the main-application class (MVC.class). This class creates the
view using a main-controller. Here's the code:
public static void main(String[] args) {
// view is declared as class-variable
view = new View();
MainController mcontroll = new MainController(view);
view.getFrame().setVisible(true);
}
The main-controller only takes the view as parameter as its only purpose is to display the view.
As stated in my post above my aim was to display different database tables from a HSQLDB and modify them.
2) In the menubar there are entries for managing years, courses, etc. If one entry is clicked, the controller for the clicked category (e.g. years) takes control. Here is, how the controller is changed:
public void addManageYearsListener(ActionListener listener) {
mntmYears.addActionListener(listener);
}
The above method is located in the view class (i.e. the GUI class) but the main-controller implements the actionPerformed()-method. To do that, the main-controller calls the method defined in the view in his constructor like that:
public MainController(View view) {
this.view = view;
this.view.addManageCoursesListener(new ManageCourses());
this.view.addManageYearsListener(new ManageYears());
}
The corresponding class "ManageYears" is then defined as inner class:
class ManageYears implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MVC mvc = new MVC("years");
}
}
What happens here is that when the menuitem is clicked, the main-controller "hears" the click (cause he is listening to it) and calls the main class again, although this time with a string as parameter. The constructor of the main class checks the string and sets the model and the controller that is needed. See here:
if (controller.equals("year")) {
YearDaoImpl yearDao = new YearDaoImpl();
YearController ycontroller = new YearController(view, yearDao);
}
"controller" is the string that is passed with the constructor and "yearDao" is the Data Access Object that handles the CRUD-operations which have to do with the object "year" (which is a class itself).
So now it's possible to switch controllers at runtime.
3) The year controller sets the ActionListeners for a add and remove button in his constructor (just like the main controller did for the menu item), get's the data from the database (via the yearDao) and sets the table model in the view (view has a setTableModel()-method for that) passing the returned ResultSet as parameter of the table Model class:
public void showYears() {
try {
con = yearDao.connectToDB();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM YEARS;");
view.setTableModel(new YearTableModel(rs));
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
As you can see, the yearDao has a connectToDB()-method that returns a connection (the connection is actually gotten from a c3p0 connection pool) which is then used to get a ResulSet of years from the database. The setTableModel()-method is then called setting the YearTableModel - a custom class extending AbstractTableModel and passing the ResulSet as parameter.
With the explained design it is now possible to:
1.) only have one table in the GUI that is populated with different database outputs.
2.) seperate the view from the data (which is what this whole fuss is about ;-)).
3.) add new controllers or models when needed without changing a lot of code.
As mentioned at the beginning I still appreciate every suggestion or improvement!
If you made it till the end of this post, I hope you found something to use in your own program!
regards,
Felix
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
I am using chrriis.dj.nativeswing.swtimpl.components.JWebBrowser in my swing application to open web page.
The page is going to show "Facebook Authentication" page and I want to prevent user from inputting some other URL other than I specify and also Forward and Back buttons should be visible but not has no affect.
So following functions are applicable for my goal
setButtonBarVisible(false);
setLocationBarVisible(false);
Once user completes the authentication I will handle the locationChanged event.
#Override
public void locationChanged(WebBrowserNavigationEvent arg0) {
System.out.println("locationChanged!");
....
}
}
I think what you want is a custom decorator. Check the demo application, under "JWebBrowser > Custom Decorator".
In your case, you could create a new decorator class, as an adapted copy of DefaultWebBrowserDecorator or a subclass with appropriate override.
You would also have to decide if this decorator is to be used only by one instance of the JWebBrowser or all instances (like child popups, etc.)