A collection of simple, focused Java Swing examples designed to demonstrate various concepts in Java GUI development. This repository is a great resource for learning and reference.
- 🚀 Getting Started
- 📚 Swing Concepts Demonstrated
- 🔍 Detailed Example Breakdown
- JFileChooser
- JMenuBar
- MouseListener
- Opening New Windows
- KeyBindings
- JProgressBar
- 💡 Swing Best Practices
- 🤝 Contributing
- 📜 License
- 🙏 Acknowledgements
Requires JDK 8 or higher. Each folder in this repository is a standalone example.
# 1. Clone the repository
git clone https://github.com/<your-username>/java-gui-learning.git
cd java-gui-learning
# 2. Navigate into an example folder, then compile and run
# (Example using the 'selectafile' project)
cd selectafile
javac *.java && java MainNote: The main class to run may vary (e.g.,
Main,MyFrame). Check the source files ifjava Maindoes not work.
This repository covers the following core Java Swing concepts:
| Concept | Description | Example Directory |
|---|---|---|
🖼️ JFrame |
The main window for a Swing application. Shows setup, close operations, and adding components. | selectafile, Menubars, Mouselistener, New window |
🔳 JButton |
A clickable button that handles clicks with an ActionListener. |
selectafile, New window |
📊 JProgressBar |
A component that visually displays the progress of a task. | Progress bar |
🖱️ MouseListener |
Listens for mouse events (click, press, release, enter, exit) on a component. | Mouselistener |
⌨️ KeyBinding |
Binds an Action to a KeyStroke without requiring component focus. More flexible than KeyListener. |
Keybindings |
📂 JFileChooser |
Opens a native file selection dialog to get a file path. | selectafile |
📜 JMenuBar |
A classic top-level menu bar with JMenu, JMenuItem, icons, and keyboard mnemonics. |
Menubars |
| 🪟 New Windows | A common pattern where one window opens another and then disposes itself. | New window |
| 📐 Layout Managers | ||
↳ FlowLayout |
Arranges components in a directional flow, like lines of text. | selectafile, Menubars |
| ↳ Absolute Layout | Manually places components using setLayout(null). Provides pixel-perfect control but is not responsive. |
Mouselistener, New window |
Directory: selectafile
This example demonstrates how to use JFileChooser to create a dialog that lets the user select a file from their local system.
Key Snippet (MyFrame.java):
if(e.getSource()==button){
JFileChooser fileChooser = new JFileChooser();
// Set the default directory to the project folder
fileChooser.setCurrentDirectory(new File("."));
int response = fileChooser.showOpenDialog(null);
if(response == JFileChooser.APPROVE_OPTION){
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
System.out.println(file);
}
}Directory: Keylistener
This example shows how to move a component (JLabel) around the screen using keyboard input. The JFrame implements KeyListener and listens for key presses.
Note: While
KeyListenerworks, it has a major drawback: the component it's attached to must be in focus to receive events. For application-wide keyboard shortcuts, Key Bindings are the preferred, more robust solution (see Best Practices).
Key Snippet (MyFrame.java):
public class MyFrame extends JFrame implements KeyListener {
// ...
public void keyTyped(KeyEvent e) {
// Move the label based on the character typed
switch(e.getKeyChar()){
case 'a': label.setLocation(label.getX()-10, label.getY()); break;
// ... other cases
}
}
}Directory: Basics
This example demonstrates several uses of JOptionPane to create simple, one-line dialog boxes for showing information, asking questions, or getting user input.
-
Use the Event Dispatch Thread (EDT): All interactions with Swing components (creation, modification) should happen on the EDT to prevent concurrency issues. The standard way to do this is by wrapping your main GUI code in
SwingUtilities.invokeLater().public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new MyFrame(); // Create and show the GUI } }); }
-
Prefer Layout Managers over
nullLayout: WhilesetLayout(null)gives you pixel-perfect control, it creates rigid UIs that do not resize gracefully. UseFlowLayout,BorderLayout,GridLayout, or the more powerfulGridBagLayoutfor flexible and maintainable designs. -
Separate Long-Running Tasks: Long tasks (like the
fill()method in theProgress barexample) should not run on the EDT, as they will freeze the GUI. Use aSwingWorkerto perform the task in a background thread and safely publish updates to the progress bar. -
Prefer Key Bindings over
KeyListener: For reacting to keyboard input,KeyBindingsare generally more reliable thanKeyListener.KeyListeneronly works if the component it is registered to has keyboard focus.KeyBindingscan be configured to work at different focus levels (e.g., when the component is in focus, or when it's within the window), making them much more flexible for things like game controls or shortcuts.
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
This project is licensed under the MIT License - see the LICENSE.md file for details.
The structure and content of these examples are inspired by the Java GUI tutorial series from Bro Code.