# Swing Java Cheat Sheet
## 1. Basic Swing Components
Component | Description | Example
-------------------|---------------------------------------|-----------------------
--------------------
JFrame | Main window | JFrame frame = new
JFrame("Title");
JPanel | Container for grouping components | JPanel panel = new
JPanel();
JButton | Button that triggers actions | JButton button = new
JButton("Click");
JLabel | Displays text or images | JLabel label = new
JLabel("Text");
JTextField | Single-line text input | JTextField textField
= new JTextField(20);
JTextArea | Multi-line text input | JTextArea textArea =
new JTextArea(5, 20);
JCheckBox | Checkable box | JCheckBox checkBox =
new JCheckBox("Check me");
JRadioButton | Radio button | JRadioButton
radioButton = new JRadioButton("Option");
JComboBox | Drop-down list | JComboBox<String>
comboBox = new JComboBox<>(new String[]{"Item 1", "Item 2"});
JList | List of items | JList<String> list =
new JList<>(new String[]{"Item 1", "Item 2"});
JTable | Table for displaying data | JTable table = new
JTable(data, columns);
## 2. Layout Managers
Layout Manager | Description | Example
Usage
-------------------|-----------------------------------------------------|---------
----------------------------------
FlowLayout | Arranges components in a flow (left-to-right) |
panel.setLayout(new FlowLayout());
BorderLayout | Divides area into North, South, East, West, Center |
frame.setLayout(new BorderLayout());
GridLayout | Grid of equally sized cells |
panel.setLayout(new GridLayout(3, 2));
BoxLayout | Aligns components vertically or horizontally |
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
GridBagLayout | Most flexible; complex grid-based layout |
frame.setLayout(new GridBagLayout());
## 3. Event Handling
Event Type | Interface | Example Usage
-------------------|--------------------------|------------------------------------
-------
Button Click | ActionListener | button.addActionListener(e ->
actionPerformed());
Mouse Events | MouseListener | panel.addMouseListener(new
MouseAdapter() {...});
Key Events | KeyListener | textField.addKeyListener(new
KeyAdapter() {...});
Window Events | WindowListener | frame.addWindowListener(new
WindowAdapter() {...});
## 4. Useful Methods
Task | Method
------------------------------------------|----------------------------------------
--------------
Set window size | frame.setSize(400, 300);
Set default close operation |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Center a window | frame.setLocationRelativeTo(null);
Make a window visible | frame.setVisible(true);
Update UI after adding components | panel.revalidate(); panel.repaint();
## 5. Threading in Swing
- **Creating GUI on the EDT:**
```java
SwingUtilities.invokeLater(() -> createAndShowGUI());
```
- **Using SwingWorker for background tasks:**
```java
SwingWorker<Void, Void> worker = new SwingWorker<>() {
@Override
protected Void doInBackground() throws Exception {
// Long-running task here
return null;
}
@Override
protected void done() {
// Update UI after the task is done
}
};
worker.execute();
```
## 6. Look and Feel
- **Set to system's look and feel:**
```java
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
```
## 7. Tips and Tricks
1. **Use Action instead of ActionListener for buttons**: Helps in sharing the
action with menu items, buttons, and other components.
2. **Key Bindings over KeyListener**: Prefer key bindings for more flexible
keyboard event handling.
3. **Avoid Heavy Operations on the EDT**: Use SwingWorker for tasks like file
operations and networking to prevent UI freezing.
4. **Custom Renderers**: Use custom renderers for lists, tables, and combo boxes
for better visuals.
5. **Preferred Size**: Use setPreferredSize() for setting the size of components
when needed.
## 8. Resources
- **Official Java Swing Documentation**:
https://docs.oracle.com/javase/tutorial/uiswing/
- **Swing Utilities Overview**: Explore SwingUtilities for more utility methods to
manage GUI.