Skip to content

Shylesh1640/java-gui-learning

Repository files navigation

☕ Java Swing GUI Learning Examples

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.

Java Swing


📖 Table of Contents

  • 🚀 Getting Started
  • 📚 Swing Concepts Demonstrated
  • 🔍 Detailed Example Breakdown
    • JFileChooser
    • JMenuBar
    • MouseListener
    • Opening New Windows
    • KeyBindings
    • JProgressBar
  • 💡 Swing Best Practices
  • 🤝 Contributing
  • 📜 License
  • 🙏 Acknowledgements

🚀 Getting Started

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 Main

Note: The main class to run may vary (e.g., Main, MyFrame). Check the source files if java Main does not work.


📚 Swing Concepts Demonstrated

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

🔍 Detailed Example Breakdown

JFileChooser

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);
    }
}

KeyListener

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 KeyListener works, 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
        }
    }
}

JOptionPane

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.

💡 Swing Best Practices

  1. 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
            }
        });
    }
  2. Prefer Layout Managers over null Layout: While setLayout(null) gives you pixel-perfect control, it creates rigid UIs that do not resize gracefully. Use FlowLayout, BorderLayout, GridLayout, or the more powerful GridBagLayout for flexible and maintainable designs.

  3. Separate Long-Running Tasks: Long tasks (like the fill() method in the Progress bar example) should not run on the EDT, as they will freeze the GUI. Use a SwingWorker to perform the task in a background thread and safely publish updates to the progress bar.

  4. Prefer Key Bindings over KeyListener: For reacting to keyboard input, KeyBindings are generally more reliable than KeyListener. KeyListener only works if the component it is registered to has keyboard focus. KeyBindings can 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.

🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

📜 License

This project is licensed under the MIT License - see the LICENSE.md file for details.


🙏 Acknowledgements

The structure and content of these examples are inspired by the Java GUI tutorial series from Bro Code.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages