Explain the following swing components with an example program:
i)JLabel ii)JTextField iii) JScrollPane iv) JTable
Answer:-
Here’s a clear explanation of each Swing component you listed, along with a simple example program that uses all four components in a single GUI:
i) JLabel
- A display-only component used to show text or images.
- It cannot be edited by the user.
ii) JTextField
- A component that allows the user to enter a single line of text.
iii) JScrollPane
- A scrollable view of another component (like a panel, text area, or table).
- Adds horizontal and/or vertical scrollbars as needed.
iv) JTable
- A component used to display tabular data (rows and columns).
- Can be placed inside a
JScrollPane
for scrollable tables.
✅ Example Program: Using JLabel, JTextField, JScrollPane, JTable
import javax.swing.*; import java.awt.*; public class SwingComponentsExample { public static void main(String[] args) { // Create frame JFrame frame = new JFrame("Swing Components Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 300); frame.setLayout(new FlowLayout()); // JLabel JLabel label = new JLabel("Enter your name:"); frame.add(label); // JTextField JTextField textField = new JTextField(20); frame.add(textField); // JTable with sample data String[][] data = { {"1", "Alice", "90"}, {"2", "Bob", "85"}, {"3", "Charlie", "88"}, }; String[] columnNames = {"ID", "Name", "Marks"}; JTable table = new JTable(data, columnNames); // JScrollPane for the table JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(400, 100)); frame.add(scrollPane); // Show frame frame.setVisible(true); } }
Explanation of Output
- A label prompting user input.
- A text field to type a name.
- A scrollable table showing ID, name, and marks of students.
Summary Table
Component | Description |
---|---|
JLabel | Displays non-editable text/image |
JTextField | Allows single-line text input |
JScrollPane | Adds scrollbars to large components |
JTable | Displays data in tabular format |