9 Replies - 2413 Views - Last Post: 01 April 2011 - 04:05 PM Rate Topic: -----

#1 4D1  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 225
  • Joined: 22-October 09

Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 12:25 PM

Hi guys,

I have just started to get into Java, I have some experience with C++ so I am adapting quite well to Java, however I have a bit of a dilema... Not a problem with the syntax more the most professional/recommended way to lay things out?

The biggest dilema is how to link things together, if I were to create a number of classes and interfaces etc and I need them all to do something in order for the application to work, what is the best way to tie them all together and get them communicating? In a java console app is it to use main() to instanciate all objects and do what needs to be done passing values back and forth via main, and in a GUI app is it best to have a GUI class that obviously creates all the visual stuff and then has a nested class to handle events, or create a new events class that components use as a handler so there is a class for the GUI, a completely seperate class for events and main just initialises the GUI?

At the moment I have a nested class in the GUI class to handle events, so my nested class is having to declare objects of my other types and is getting quite cluttered it has to declare all the jcomponents, initialise them all, has a sub class for events which has to declare all my other classes and do things accordingly? Is this the ideal solution?

Is This A Good Question/Topic? 1
  • +

Replies To: Structuring a Java Application, how to organise classes?

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 12:34 PM

There are no ideal solution and without seeing all your classes difficult to say.

Sure that your JComponent will have to be declared somewhere. Usually we group all the JComponent of a single JPanel in that JPanel class (extend JPanel just for that if required)

The best idea is to limit each class to 200 or 300 lines.

All your class should have a main() method to unit test them. Then you can have a "Main" class with it's main() method that thight all of these together.
Was This Post Helpful? 1
  • +
  • -

#3 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,390
  • Joined: 27-December 08

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 12:42 PM

With GUIs, I have a rule of thumb: if there is enough code for a single JComponent to warrant using a method to initialize it, then it warrants subclassing it and initializing it there. You can use inner classes to handle your event listeners, or you can implement the interfaces with the outer class.

Also, make sure you separate your program state/data from your user interface. Mixing the two will only further clutter your code.
Was This Post Helpful? 0
  • +
  • -

#4 4D1  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 225
  • Joined: 22-October 09

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 12:43 PM

Here is some code from something I am doing at the moment, this is my first GUI in any language and I have programmed it by hand to understand what it is doing rather than just using a manager at the moment....


Main Class
package filecompare;

public class Main
{
    public static void main(String[] args)
    {
        GUI window = new GUI("File Compare!");
        window.setVisible(true);
    }
}



GUI Class
package filecompare;

import javax.swing.border.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class GUI extends JFrame
{
    private Excel excel;
    private File sourceFile, compareFile;
    private JPanel browsePanel;
    private JPanel buttonPanel;
    private JPanel progressPanel;
    private JProgressBar progress;
    private JFileChooser sourceFileChooser, compareFileChooser;
    private JTextField sourceTextField, compareTextField;
    private JTextArea textArea;
    private JScrollPane scrollArea;
    private JButton sourceButtonBrowse, compareButtonBrowse;
    private JButton buttonCompare;
    private JButton buttonCheckNew;
    private JButton buttonCheckOld;
    private JButton buttonSave;
    private GUIHandler handler;
    private String sourceFilePath;
    private String compareFilePath;

    public GUI(String s)
    {
        super(s);

        handler = new GUIHandler();
        
        setLayout(null);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 400);

        browsePanel = new JPanel();
        browsePanel.setBounds(25, 25, 440, 100);
        browsePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
        .createEtchedBorder(EtchedBorder.LOWERED), "Browse for File"));
        add(browsePanel);

        sourceTextField = new JTextField(30);
        sourceTextField.setText("Source File!!!");
        sourceTextField.setEditable(false);
        browsePanel.add(sourceTextField);

        sourceButtonBrowse = new JButton("Browse");
        browsePanel.add(sourceButtonBrowse);
        sourceButtonBrowse.addActionListener(handler);

        compareTextField = new JTextField(30);
        compareTextField.setText("Compare File!!!");
        compareTextField.setEditable(false);
        browsePanel.add(compareTextField);

        compareButtonBrowse = new JButton("Browse");
        browsePanel.add(compareButtonBrowse);
        compareButtonBrowse.addActionListener(handler);


        buttonPanel = new JPanel();
        buttonPanel.setBounds(25, 130, 440, 70);
        buttonPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
        .createEtchedBorder(EtchedBorder.LOWERED), "Choose an Option"));
        add(buttonPanel);

        buttonCompare = new JButton("Compare");
        buttonPanel.add(buttonCompare);
        buttonCompare.addActionListener(handler);

        buttonCheckNew = new JButton("Find New");
        buttonPanel.add(buttonCheckNew);
        buttonCheckNew.addActionListener(handler);

        buttonCheckOld = new JButton("Find Discon");
        buttonPanel.add(buttonCheckOld);
        buttonCheckOld.addActionListener(handler);

        buttonSave = new JButton("Save");
        buttonPanel.add(buttonSave);
        buttonSave.addActionListener(handler);


        progressPanel = new JPanel();
        progressPanel.setBounds(25, 205, 440, 150);
        progressPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
        .createEtchedBorder(EtchedBorder.LOWERED), "Progress"));
        add(progressPanel);

        textArea = new JTextArea(5, 35);
        textArea.setText("File Compare v1.0...\n\n");
        textArea.setEditable(false);
        scrollArea = new JScrollPane(textArea);
        progressPanel.add(scrollArea);

        progress = new JProgressBar(0, 100);
        progress.setValue(0);
        progress.setStringPainted(true);
        progressPanel.add(progress);

        sourceFileChooser = new JFileChooser();
        compareFileChooser = new JFileChooser();

        disableButtons();
    }

    public void disableButtons()
    {
        buttonCompare.setEnabled(false);
        buttonCheckNew.setEnabled(false);
        buttonCheckOld.setEnabled(false);
        buttonSave.setEnabled(false);
    }

    public void enableButtons()
    {
        if(sourceFilePath != null && compareFilePath != null)
        {
            sourceFile = new File(sourceFilePath);
            compareFile = new File(compareFilePath);
            
            if(sourceFile.exists() && compareFile.exists())
            {
                buttonCompare.setEnabled(true);
                buttonCheckNew.setEnabled(true);
                buttonCheckOld.setEnabled(true);
                buttonSave.setEnabled(true);

                excel = new Excel(sourceFile, compareFile);
            }
        }
    }

    public void setProgress(int i)
    {
        progress.setValue(getProgress()+i);
    }

    public int getProgress()
    {
        return(progress.getValue());
    }

    public void setSourceTextField(String s)
    {
        sourceTextField.setText(s);
    }

    public void setCompareTextField(String s)
    {
        compareTextField.setText(s);
    }

    public void setTextArea(String s)
    {
        textArea.append(s);
    }

    public void setSourceFilePath()
    {
        int temp = sourceFileChooser.showOpenDialog(GUI.this);

        if(temp == JFileChooser.APPROVE_OPTION)
        {
            sourceFilePath = sourceFileChooser.getSelectedFile().toString();
            setTextArea(String.format("Source File Path:\n%s\n\n",sourceFilePath));
            setSourceTextField(sourceFilePath);
        }
    }

    public void setCompareFilePath()
    {
        int temp = compareFileChooser.showOpenDialog(GUI.this);

        if(temp == JFileChooser.APPROVE_OPTION)
        {
            compareFilePath = compareFileChooser.getSelectedFile().toString();
            setTextArea(String.format("Compare File Path:\n%s\n\n",compareFilePath));
            setCompareTextField(compareFilePath);
        }
    }
    
    private class GUIHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            if(e.getSource() == sourceButtonBrowse)
            {
                setSourceFilePath();
                enableButtons();
            }
            else if(e.getSource() == compareButtonBrowse)
            {
                setCompareFilePath();
                enableButtons();
            }
            else if(e.getSource() == buttonCompare)
            {
                excel.compareFiles();
            }
        }
    }
}



I intend this app to work with Excel comparing files, finding missing values etc etc, I am just looking at the different libraries available so havent gotten to that yet, my issues with this is the last few lines of GUI where I call excle.compareFiles(); Excel class is not really relevant to the GUI and neither will any other classes be so is it best to be included these objects in GUI and calling them from there?

This is probably a bad example as Excel class is not functioning yet so there will be alot more calls to it when its finished

This post has been edited by 4D1: 01 April 2011 - 12:50 PM

Was This Post Helpful? 0
  • +
  • -

#5 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,390
  • Joined: 27-December 08

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 12:57 PM

If Excel deals with program data or state, then it should be separate from your GUI. For example, if you were dealing with a School program, you may have your Teacher, Student, Course classes, etc. Then you may have a School class which encapsulates all of this data. You should then have a DataManager class to manage access to your school. Your GUI should be set up to interact with the DataManager only. Generally, a DataManager is a singleton.

In this way, you are separating your program data/state and user interface. So if you go to a console application or use another GUI library, you won't have as much work to do re-incorporating all the data. It also makes using the data easier.
Was This Post Helpful? 2
  • +
  • -

#6 4D1  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 225
  • Joined: 22-October 09

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 01:15 PM

So please correct me if my understanding is flawed...

Best practice:-

1: Create an abstract class which all related data manipulation classes will extend, and either create an abstract method or interface for all children so that I can manipulate all child classes, via a superclass object...

2: Create a GUI class, that only interacts with the superclass data manipulation object? Have the event handler nested in GUI and using superclass object, or polymorphism on superclass object.... Or have the event handler seperate and doing whatever.... this bit is not important

seperate event handler ? doesnt matter : doesnt matter
Was This Post Helpful? 0
  • +
  • -

#7 4D1  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 225
  • Joined: 22-October 09

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 01:53 PM

macosxnerd101?
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 02:02 PM

Kind of

- something that hold the data (data can change from flat file to SQL to something held in memory) the other components do not have to know. It provides accessors for the business rules modules
- business rules. It plays with the data. Perform calculations, what should be displayed or not. It provides accessors to the computed info. This module does not know anything about if the user interface is console, GUI, another application
- user interface, it could be GUI or console or calls from another application

These rules apply for Java or C++ or any other languages
Was This Post Helpful? 2
  • +
  • -

#9 4D1  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 225
  • Joined: 22-October 09

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 02:46 PM

Thanks pbl, just so I am absolutely clear and as I am relatively new to programming and Java...

To see this from a bottom up perspective

1: Classes to get and store data, from wherever
2: Classes to get the gotten data from the get classe(s) and manipulate
3: Abstract, or interface Class to interact with classes in step 2 in a controlled way....
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Structuring a Java Application, how to organise classes?

Posted 01 April 2011 - 04:05 PM

View Post4D1, on 01 April 2011 - 04:46 PM, said:

Thanks pbl, just so I am absolutely clear and as I am relatively new to programming and Java...

To see this from a bottom up perspective

1: Classes to get and store data, from wherever
2: Classes to get the gotten data from the get classe(s) and manipulate
3: Abstract, or interface Class to interact with classes in step 2 in a controlled way....

:^:
Glad your learn that using Java, if it is the case good move you did to learn it
less obvious (and easier to cheat) in C++ but the concepts are the same

Happy coding
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1