Repository navigation
Expand file tree
/
Copy pathGreetingFormApp.java
More file actions
42 lines (38 loc) · 1.48 KB
/
Copy pathGreetingFormApp.java
File metadata and controls
42 lines (38 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GreetingFormApp extends JFrame implements ActionListener {
private JTextField nameField; // Field for user input
private JButton greetButton; // Button to trigger greeting
private JLabel messageLabel; // Label to display greeting
public GreetingFormApp() {
setTitle("Greeting Form");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
nameField = new JTextField(15);
greetButton = new JButton("Greet");
messageLabel = new JLabel("Enter your name and press Greet.", SwingConstants.CENTER);
greetButton.addActionListener(this);
JPanel inputPanel = new JPanel();
inputPanel.add(new JLabel("Name:"));
inputPanel.add(nameField);
inputPanel.add(greetButton);
setLayout(new BorderLayout());
add(inputPanel, BorderLayout.NORTH);
add(messageLabel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText().trim();
if (name.isEmpty()) {
messageLabel.setText("Please enter a name.");
} else {
messageLabel.setText("Hello, " + name + "!");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GreetingFormApp().setVisible(true));
}
}