简体   繁体   中英

How to properly separate GUI from the Logic in this Java Swing code

I am trying to learn a bit about GUI interfaces with swing and how to construct a GUI program correctly, at least in the most efficient way depending on the project of course.

Here in this example, I try to create a simple program which does the following.

  • I have a Menu consisting of 2 buttons, each button when is pressed the appropriate ActionListener is triggered and an instance of a new class is getting created.

  • Each new class ( the name of the 2 of them are: Journal , Seminar ) has its own GUI code consisting of text fields, buttons, and other swing components.

  • At first, I had the GUI classes of these 2 inside the Journal's and Seminar's Logic classes. But as I understand this is not a good practice, it seems we need to make the program components not connected so tight together.
  • So now I tried to move each GUI method to another class and call them in each of the classes constructors.

NOTE: the final purpose of the program is serializability of objects to file so ignore for now some of the code corresponds to it.

The code isn't functional at the moment.

** QUESTION:**

  • Is the approach I'm following in the entire program "correct" ? or should I find another way?

  • What pieces of knowledge should I pursuit so I can understand how to build this kind of apps efficiently?

  • How I can make the current work?

  • It's my first post here so I tried my best to give this question in the best way I could, let me know if you need any more info on this. Thanks!*

Any help much appreciated.

Menu Class

import javax.swing.*;
    import java.awt.*;
    import java.io.IOException;

public class Menu {

JFrame menu_frame;
JButton ergasia_periodiko_btn = new JButton();
JButton ergasia_sinedrio_btn = new JButton();

Menu() {
    this.menu_frame = new JFrame();
    this.menu_frame.setSize(400,100);
    this.menu_frame.setTitle("Ereunitikos Katalogos");
    this.menu_frame.add(ergasia_periodiko_btn);
    this.menu_frame.add(ergasia_sinedrio_btn);
    this.menu_frame.setLayout(new FlowLayout());
    this.ergasia_periodiko_btn.setText("Periodika");
    this.ergasia_sinedrio_btn.setText("Sinedria");
    this.ergasia_periodiko_btn.addActionListener(e -> new Journal());  //Action Listener to Joyrnal
    this.ergasia_sinedrio_btn.addActionListener(e -> {
        try {
            new Seminar();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }); //Action Listener to Seminar
    this.menu_frame.setLocationRelativeTo(null);
    this.menu_frame.setVisible(true);
}

public static void main(String[] args)
 { new Menu(); }
 }

Journal Class

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
 import java.util.List;

public class Journal implements Serializable
{ 
Journal_GUI gui;  //**Creating instance of journal gui inside here so i can run the gui code in the constructor**
String column_title;
List writers = new ArrayList(2);
String mag_title;
String numberOfPages;
String released_date;
String volume;
String exact_page;

 Journal(){}

 public void fillVars()
{
    this.column_title = gui.column_title_tf.getText();
    this.writers = Collections.singletonList(gui.writers_tf.getText());
    this.mag_title = gui.mag_title_tf.getText();
    this.numberOfPages = gui.numberOfPages_tf.getText();
    this.released_date = gui.released_date_tf.getText();
    this.volume = gui.volume_tf.getText();
    this.exact_page = gui.exact_page_tf.getText();
}

public void insertP() {
    fillVars();
   // try {
       // My_Serialization.serialization("fileToSavePeriodiko.txt", this.toString());

   // }// catch (IOException e) {
     //   e.printStackTrace();
    //}
   }

public void searchP_byTitle(){}
public void searchP_byName(){}

@Override
public String toString() {
    String value = "\n Periodiko column title : " + column_title + "\n writers : " + writers+ "\n Titlos magazine : " + mag_title
            + "\n  Number of Pages : " + numberOfPages + "\n Released Date : " + released_date + "\n Volume : " + volume + "\n Exact Page : " + exact_page +"\n";
    return value;
}
 }

Journal Gui Class

import javax.swing.*;

public class Journal_GUI extends Journal{

JFrame periodikoFrame;
JTextField column_title_tf;
JTextField writers_tf;
JTextField mag_title_tf;
JTextField numberOfPages_tf;
JTextField released_date_tf;
JTextField volume_tf;
JTextField exact_page_tf;

public Journal_GUI(){
    initComponenets();
}


public void initComponenets() {

    periodikoFrame = new JFrame("PERIODIKA");
    periodikoFrame.setSize(500, 500);
    JPanel panel = new JPanel();
    BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
    panel.setLayout(boxlayout);

    column_title_tf = new JTextField("Column Title");
    writers_tf = new JTextField("Writers");
    mag_title_tf = new JTextField("Magazine's Title");
    numberOfPages_tf = new JTextField("Number of Pages");
    released_date_tf = new JTextField("Date of Release");
    volume_tf = new JTextField("Volume");
    exact_page_tf = new JTextField("Exact Page");

    JButton search_mag_btn_byName = new JButton("Search By name");
    JButton search_mag_btn_byTitle = new JButton("Search By Title");
    JButton insert_mag_btn = new JButton("Insert article");

    search_mag_btn_byName.addActionListener(e -> searchP_byName());
    search_mag_btn_byTitle.addActionListener(e -> searchP_byTitle());
    insert_mag_btn.addActionListener(e -> insertP());

    panel.add(column_title_tf);
    panel.add(writers_tf);
    panel.add(mag_title_tf);
    panel.add(numberOfPages_tf);
    panel.add(released_date_tf);
    panel.add(volume_tf);
    panel.add(exact_page_tf);
    panel.add(search_mag_btn_byName);
    panel.add(search_mag_btn_byTitle);
    panel.add(insert_mag_btn);
    periodikoFrame.setLocationRelativeTo(null);
    periodikoFrame.add(panel);
    periodikoFrame.setVisible(true);
}
 }
  • Is the approach I'm following in the entire program "correct" ? or should I find another way?

It's probably correct, but not the easiest to understand & develop

  • What pieces of knowledge should I pursuit so I can understand how to build this kind of apps efficiently?

You should take a look at https://en.wikipedia.org/wiki/SOLID , especially at https://en.wikipedia.org/wiki/Dependency_inversion_principle#Model_View_Controller and https://en.wikipedia.org/wiki/Single_responsibility_principle in your case. This should give you some hint how to build app efficiently ( this one included ).

  • How I can make the current work?

Do you mean to serialize an object to a file ? If that's the case, look at How to write and read java serialized objects into a file

Just a suggestion, when I started developing GUI based desktop applications for the first time I used Eclipse WindowsBuilder plugin, it generates code itself all you have to do is drag and drop the components you need. Or even better you can to start it go with NetBeans, it has pretty good GUI builtin toolkit (drag and drop), use it understand how it generates automatic code and follow that to be good at what you are trying to do here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM