How to separate GUI from logic in practice

Hello

I have programmed in other languages in the past, now I need to make a serious application in Java, and feel the need to make it easy to maintain in the future.

So I must separate the GUI from the logic, so if I change the GUI, my program continues working. And too to see better the way it works, so it doesn't become too complex to maintain.

How do I do this in Netbeans?

For example: I did a frame with a button. Then made a class called CloseButton with a public static method that exits. From the Frame class I import the package that contains CloseButton class.

In the code of the button I place a call to the method that exits.

Is this well done? How do you do to separate gui and logic? Can this be done better?

I suppose the starting point to an application with GUI is the class that makes the GUI. Isn't it? So the class constructs the GUI, and then I place other classes to be called from there and make it function.

In this example I isolated the logic of a button.

Please tell me how is this done in Java, if I am doing well or not, before I continue coding.

I am not sure at all, as I am not used to this.

Thanks.

Jordi

PD: Here is an example code of what I mean

/*

* HiperBrowserFrame.java

*

* Created on 25 de marzo de 2007, 18:54

*/

package frame3dbrowser;

import logic.*;

/**

*

* @author Administrador

*/

publicclass HiperBrowserFrameextends javax.swing.JFrame{

/** Creates new form HiperBrowserFrame */

public HiperBrowserFrame(){

initComponents();

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

privatevoid initComponents(){

jButton1 =new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setText("jButton1");

jButton1.addActionListener(new java.awt.event.ActionListener(){

publicvoid actionPerformed(java.awt.event.ActionEvent evt){

jButton1ActionPerformed(evt);

}

});

org.jdesktop.layout.GroupLayout layout =new org.jdesktop.layout.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(layout.createSequentialGroup()

.add(68, 68, 68)

.add(jButton1)

.addContainerGap(587, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

.add(layout.createSequentialGroup()

.add(45, 45, 45)

.add(jButton1)

.addContainerGap(309, Short.MAX_VALUE))

);

pack();

}// </editor-fold>

privatevoid jButton1ActionPerformed(java.awt.event.ActionEvent evt){

CloseButton.closeThis();

}

/**

* @param args the command line arguments

*/

publicstaticvoid main(String args[]){

java.awt.EventQueue.invokeLater(new Runnable(){

publicvoid run(){

new HiperBrowserFrame().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

// End of variables declaration

}

/*

* CloseButton.java

*

* Created on 25 de marzo de 2007, 19:08

*

* To change this template, choose Tools | Template Manager

* and open the template in the editor.

*/

package logic;

publicclass CloseButton{

publicstaticvoid closeThis(){

System.exit(0);

}

}

[5813 byte] By [Jordi_rca] at [2007-11-26 22:51:13]
# 1

I don't know about NetBeans -- the bestt hing an IDE can do is stay out of the way --

but you should investiage the Spring Framework:

http://www.springframework.org/

It's based around Dependency Injection:

http://en.wikipedia.org/wiki/Dependency_injection

which helps you keep layers of an application loosely coupled.

DrLaszloJamfa at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 2

Thanks DrLaszlo

Thanks, but I am quite happy with Netbeans.

Anyway, I just only ask for a general advice on how to do this.

The way I described to work is the way I did when programming in Visual Basic.

Maybe there is a better way, more separate. Maybe not.

Please tell me anyone who makes programs in Java would tell me.

Just tell me how you do it. When you write an application that has a UI for the users (not a console one), how do you separate the UI from the logic of the program?

I suppose placing all the code in the same class is a nonsense, we would need to make it more modular.

Greetings,

Jordi

Jordi_rca at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 3

> Thanks DrLaszlo

>

> Thanks, but I am quite happy with Netbeans.

> Anyway, I just only ask for a general advice on how

> to do this.

>

> The way I described to work is the way I did when

> programming in Visual Basic.

> Maybe there is a better way, more separate. Maybe

> not.

>

> Please tell me anyone who makes programs in Java

> would tell me.

> Just tell me how you do it. When you write an

> application that has a UI for the users (not a

> console one), how do you separate the UI from the

> logic of the program?

>

> I suppose placing all the code in the same class is a

> nonsense, we would need to make it more modular.

>

> Greetings,

>

> Jordi

it's kind-of hard to explain how to do it, other than to say keep presentation logic and business logic separate. you're on the right track with keeping code modular, and not having everything in the same class. in fact, a good OO principle that applies everywhere, not just for keeping UI and domain logic separate, is to have small classes that do one thing and no more. bear this in mind, and your UI and domain logic will naturally be decoupled. don't have UI classes that also perform computations, access databases, files etc. a good way to make sure you're keeping UI logic separate is to write more than one UI, say maybe a Swing UI and a command-line UI. if you need to change any of your business logic to add the new UI, you've probably let business logic leak into your UI

georgemca at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 4

I'm not saying you should drop NetBeans -- if you are coming from VB

you are probably used to that sort of setting. I'm just saying your IDE

should have nothing to do with how you program. If you dumped NetBeans

and worked just with NotePad and the command line, you should still

design your code the same way, right?

Anyway, one standard pattern to separate your GUI presentation from

your business logic is call the Model-View-Controller Pattern

http://en.wikipedia.org/wiki/Model-view-controller

DrLaszloJamfa at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 5

Hello

I mean, in Visual Basic, you have a GUI that you have created visually like in Netbeans.

You can add then a section of code that calls other methods that make the logic work.

So you have 3 parts:

1) The GUI for the users

2) The part of the code that detects events

3) The part of the code that makes calculations

How is this done in Java?

Is the button example that I gave right?

Thanks.

Jordi

Jordi_rca at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 6

A good way to keep things separate is work in a different order:

- you:

1 Draw GUI

2 Add event handlers

3 Add business code

- other way:

1. Write and test business code (model)

2. Draw GUI (view)

3. Write code that glues this together (controller) -> I might get executed for expressing it this way!

I admit that the separation between these steps isn't absolute. You can do parts interleaved, but if you have a good design of the back ground processes, your program should be more stable and better maintainable than when you first draw a nice GUI and then hack together the business layer to make your GUI work. (This is at least my personal favour)

Peetzorea at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 7

Hi Peetzore,

>I admit that the separation between these steps isn't absolute

So I suppose the example button I gave in my first post IS the way to that, isn't it?

I mean, I add a button in the GUI, then place in the same class a handler that calls the logic. Have a look to the example I gave, please, and just tell me if it is the way.

Jordi

Jordi_rca at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 8

Here's the way I try to apply MVC when I'm designing gui apps:

Say you have an app that maintains a price, and lets the user update it and view it. Your model will hold the price, with a setter and a getter to update and view it. The controller has an instance of the model that it maintains. It only sets and gets the price by calling those methods. The view has a method that the controller can call to update the price on the ui. The controller has a method that the view can call to pass the updated price along to the model. If you want to create a different view, all it has to do is pass the data along to the controller the same way. Nothing else should have to change.

You could even use interfaces for each part to standardize the way they interact.

interface View {

public void updatePrice();

}

interface Model {

public int getPrice();

public void setPrice(int price);

}

interface Controller {

public void updatePrice(int price);

}

So the controller is just a middle man between the view and model, and neither needs to know anything about the other besides what their interfaces require them to implement. If you need to add functionality, like keeping a quantity along with the price, you'd add it to the interfaces, then each view would implement the methods however they want (gui, commandline, etc.). The same for the controller and model.

There are probably pros and cons to this method, but it seems like a good way to keep things separated to me. :)

hunter9000a at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 9

Your problem does not isolate itself to Java alone. It's an overall design problem one faces in any sort of programming in any sort of language. For OOP language like Java, you might want to research into Design Patterns. They help you design to loose coupling of inter-system dependency, among others.

Clem1986a at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...
# 10

> I mean, I add a button in the GUI, then place in the same class a handler that calls the logic. Have a look to the example I gave, please, and just tell me if it is the way.

It is A way! You can however accomplish a better separation by not putting the action listeners inside the GUI class. Extract them into a new class and you can even have the benefit of reusing them in case you run into a similar situation.

What I meant with

>I admit that the separation between these steps isn't absolute was the order of doing things, not the location of the code.

Peetzorea at 2007-7-10 12:13:05 > top of Java-index,Java Essentials,New To Java...