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
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.
Reading the comments, I think I can answer this question. A true answer would require a book.
Break up your GUI into as many nested JPanel
s 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.
Put each nested JPanel
into its own class.
Use composition when using Swing components. Use inheritance if and only if your class will override one of the JComponent
methods.
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 ActionListener
s that JButton
A and JButton
B can execute.
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).
Only one JFrame
is used in a Swing application.
Each JPanel must have a Swing layout manager defined.
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.