How To Structure a Swing Application

前端 未结 2 666

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:45

    What if you were to set up an abstract class that creates the 50% shared code, and then extend from that?

    For example:

    abstract class BasePopupPanel extends JPanel {
    
        public void initialize() {
            // Initialize all the shared code here.
            // eg. add(new JButton("TEST");
        }
    }
    

    And now you create the actual popup panels:

    public class GiraffePopupPanel extends BasePopupPanel {
    
        public void initialize() {
            super.initialize();
            // Here you do all the initializations for this class.
        }
    }
    

    You can create as many of these as you would like. When it comes time to add them...

    ...let's say you have a method that is called displayPopup, then the signature would look like this:

    public void displayPopup(BasePopupPanel popup) {
        // do stuff regarding JDialogs, etc.
        // ...
        popup.initialize();
        // do more stuff...
    }
    

    I hope that gives you one view on how you could refactor your classes.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题