How To Structure a Swing Application

前端 未结 2 668

I don\'t really have much experience with swing, or GUI design in general for that matter (a few WPF applications in university is about the height of it), however I have been t

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 15:50

    Reading the comments, I think I can answer this question. A true answer would require a book.

    1. Break up your GUI into as many nested JPanels as it takes to describe your GUI. A simple nested JPanel that uses a BorderLayout is preferable to a complicated JPanel that uses a GridBagLayout. To be clear, I'm not criticizing a GridBagLayout. It's useful when creating a form. But it's not the only Swing layout manager.

    2. Put each nested JPanel into its own class.

    3. Use composition when using Swing components. Use inheritance if and only if your class will override one of the JComponent methods.

    4. Each JPanel has its own JButton, JLabel, etc. components. JBUtton A is defined for JPanel A, and JButton B is defined for JPanel B, even if the user of the GUI thinks they are the same button. You can minimize the duplication by creating a GUI model that contains the text of the labels and buttons. You must eliminate the duplication of action code (the code that's executed when the button is pressed) by writing common ActionListeners that JButton A and JButton B can execute.

    5. A Swing application must start with a call to SwingUtilities.invokelater(). This ensures that the Swing components are defined and used on the Event Dispatch thread (EDT).

    6. Only one JFrame is used in a Swing application.

    7. Each JPanel must have a Swing layout manager defined.

    8. Certain components, like JList and JTable, work better when enclosed in a JScrollPane.

    I'm sure I've forgotten a few things, but this should be a good start.

提交回复
热议问题