简体   繁体   中英

How to organize java swing application architecture?

I am making a small project in Java. By design, the application will be similar to QTranslate - it is a GUI for various translator APIs. The application will have 1 main form, the translator itself and several auxiliary forms (Settings, language selection, saved words, etc.). The moment is not clear how to implement the interaction of auxiliary forms with the main form? Each auxiliary form will affect the main form. For example, when choosing a language, a new button will be added to the main form. Or when changing the settings, the hot keys will change. Each form is a separate class. Do I understand correctly that the only way to implement this is to make the main form class static and access it from other non-static classes of auxiliary forms?

screenshot of my application

在此处输入图片说明

Making the main form class static would not be the appropriate OOP way i suppose. Instead I would pass your main container to the Constructor of your auxiliary form class, which would be more the OOP way.

Example Code (Parent Frame):

  public class ParentFrame extends JFrame {
    public ParentFrame() {
    this.setSize(400, 100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout(FlowLayout.CENTER));

    JButton button = new JButton("Open Window");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        new ChildFrame(getContentPane()).setVisible(true);
      }
    });
    this.getContentPane().add(button);
  }
  public static void main(String[] args) {
    new ParentFrame().setVisible(true);
  }
}

Example Code (Child Frame):

public class ChildFrame extends JFrame {
  private Container parentContainer;
  public ChildFrame(Container parentContainer) {
    this.parentContainer = parentContainer;
    this.setSize(400, 100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout(FlowLayout.CENTER));
    JButton button = new JButton("Change Frame Color");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JFrame frame = (JFrame) SwingUtilities.getRoot(parentContainer);
        frame.getContentPane().setBackground(Color.RED);
      }
    });
    this.getContentPane().add(button);
  }
}

This just creates a parent frame with a button which opens a child frame with a button. If you click on the button in the child frame it changes the background colour of the parent frame.

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