Swing is a graphical user interface (GUI) toolkit for Java that provides a set of reusable GUI components, such as buttons, text fields, labels, and more. Here are some of the commonly used Swing components:
- JButton: A button that can be clicked to perform an action.
- JTextField: A text field that allows the user to input text.
- JLabel: A label that displays text or an icon.
- JCheckBox: A checkbox that can be selected or deselected.
- JRadioButton: A radio button that can be selected from a group of options.
- JComboBox: A drop-down list of options.
- JList: A list of items that can be selected.
Here is an example Swing application that receives a number through a JTextField and displays the square of the number in another JTextField when the SQUARE button is pressed:
import java.awt.*;
import java.awt.event.*;
public class SquareCalculator extends JFrame implements ActionListener {
private JTextField numberField;
private JTextField squareField;
public SquareCalculator() {
// Set up the JFrame
setTitle("Square Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
// Create the components
JLabel numberLabel = new JLabel("Number:");
numberField = new JTextField(10);
JButton squareButton = new JButton("SQUARE");
squareButton.addActionListener(this);
JLabel squareLabel = new JLabel("Square:");
squareField = new JTextField(10);
squareField.setEditable(false);
// Add the components to the JFrame
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(numberLabel);
panel.add(numberField);
panel.add(squareButton);
panel.add(squareLabel);
panel.add(squareField);
add(panel);
// Show the JFrame
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("SQUARE")) {
try {
int number = Integer.parseInt(numberField.getText());
int square = number * number;
squareField.setText(Integer.toString(square));
} catch (NumberFormatException ex) {
squareField.setText("Invalid input");
}
}
}
public static void main(String[] args) {
new SquareCalculator();
}
}
In this example, we create a JFrame and add four Swing components to it: a JLabel for the "Number" text, a JTextField for the user to enter a number, a JButton to calculate the square, and another JLabel for the "Square" text. We also create another JTextField to display the square of the number.
When the user clicks the "SQUARE" button, the actionPerformed() method is called. It retrieves the number from the numberField JTextField, calculates the square, and displays the result in the squareField JTextField.
If the user enters an invalid input (such as a non-numeric value), the catch block catches the NumberFormatException and displays an error message in the squareField JTextField.
Overall, this Swing application demonstrates how to create and use Swing components to create a simple GUI application in Java.
No comments:
Post a Comment
If you have any doubts, please let me know