Java Swing Components - Complete Study Guide
JFrame - Main Application Window
Purpose:
- The base window for all Swing GUIs.
Constructors:
- JFrame()
- JFrame(String title)
Methods:
- setSize(int width, int height): Sets the frame size.
- setTitle(String title): Sets window title.
- setVisible(boolean): Makes frame visible.
- setDefaultCloseOperation(int): Defines close behavior.
Example:
JFrame frame = new JFrame("My App");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
[Frame with title bar and close button]
JPanel - Container for Components
Purpose:
- Used to organize and group components.
Constructors:
- JPanel()
- JPanel(LayoutManager layout)
Java Swing Components - Complete Study Guide
Methods:
- add(Component c)
- setLayout(LayoutManager l)
- setBorder(Border b)
Example:
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JButton("Click"));
Tip:
- Combine multiple JPanels for complex UIs.
[Panel with buttons in a flow layout]
JLabel - Display Non-Editable Text or Icon
Purpose:
- Used to label components or display text.
Constructors:
- JLabel()
- JLabel(String text)
- JLabel(Icon icon)
Methods:
- setText(String text)
- setIcon(Icon icon)
Example:
Java Swing Components - Complete Study Guide
JLabel label = new JLabel("Username:");
[Label next to a text field]
JTextField - Single Line Input
Purpose:
- Accepts single-line user input.
Constructors:
- JTextField()
- JTextField(String text)
- JTextField(int columns)
Methods:
- getText()
- setText(String)
Example:
JTextField tf = new JTextField(20);
String input = tf.getText();
[Text field in a login form]