Implementing the Left Navigation Bar in a Java Swing Desktop WeChat Clone
Java offers several GUI frameworks, with AWT, Swing, and JavaFX being the primary choices. AWT provides basic functionality, while JavaFX has a steeper learning curve. Swing serves as a lightweight, easy-to-use framework suitable for building desktop applications. It includes a comprehensive set of classes for creating diverse GUI components such as images, text fields, and lists.
This guide builds upon the foundation of a main application window, focusing on constructing the left-side naivgation panel.
Layout Analysis of the Navigation Bar
The left navigation bar can be divided into two primary sections: an upper area containing the user avatar and five menu items, and a lower area for additional options like mini-programs. A BoxLayout is ideal for this vertical arrangement. The upper panel can be anchored to the NORTH and the lower panel to the SOUTH within a BorderLayout for the main container.
The background color should match the WeChat theme, which uses a dark gray with the hex value #2E2E2E (RGB: 46, 46, 46).
Setting the Main Container Layout and Color:
// Configure the main panel with BorderLayout
setLayout(new BorderLayout(0, 40));
// Add the top and bottom sub-panels
add(upperMenuPanel, BorderLayout.NORTH);
add(lowerMenuPanel, BorderLayout.SOUTH);
// Define and apply the background color
Color navBackground = new Color(46, 46, 46);
setBackground(navBackground);
Constructing the Upper Menu Panel
This panel holds the avatar and menu items in a vertical stack, making BoxLayout with a Y_AXIS orientation appropriate.
// Set vertical box layout for the upper panel
upperMenuPanel.setLayout(new BoxLayout(upperMenuPanel, BoxLayout.Y_AXIS));
Displaying the Avatar Image
A JLabel component can be used to display an image. The image resource is typically loaded from the project's resources.
// Load the image resource path
String avatarImagePath = Objects.requireNonNull(
getClass().getResource("/assets/avatar.png")
).getPath();
// Create an ImageIcon
ImageIcon avatarIcon = new ImageIcon(avatarImagePath);
// Create a label to hold the icon
JLabel avatarLabel = new JLabel(avatarIcon);
// Add the label to the upper panel
upperMenuPanel.add(avatarLabel);