Java Program 7:
Write a GUI program using Swing and event handlers in Java where:
The user enters a temperature in Celsius or Fahrenheit.
The user can click a button to convert it to the other scale.
The result is displayed in the GUI.
Includes input validation (non-numeric input handled with exception).
import [Link].*;
import [Link].*;
import [Link].*;
// Temperature Converter using Swing
public class TemperatureConverter extends JFrame implements ActionListener {
JLabel label;
JTextField textField;
JButton cToF, fToC;
JLabel result;
// Constructor
TemperatureConverter() {
// Frame settings
setTitle("Temperature Converter");
setSize(400, 250);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Components
label = new JLabel("Enter Temperature:");
textField = new JTextField(15);
cToF = new JButton("Celsius to Fahrenheit");
fToC = new JButton("Fahrenheit to Celsius");
result = new JLabel("Result will appear here");
// Add action listeners
[Link](this);
[Link](this);
// Add components to frame
add(label);
add(textField);
add(cToF);
add(fToC);
add(result);
setVisible(true);
// Event handling
public void actionPerformed(ActionEvent e) {
try {
// Convert input to double
double temp = [Link]([Link]());
// Celsius to Fahrenheit
if ([Link]() == cToF) {
double fahrenheit = (temp * 9 / 5) + 32;
[Link]("Fahrenheit = " + fahrenheit);
// Fahrenheit to Celsius
else if ([Link]() == fToC) {
double celsius = (temp - 32) * 5 / 9;
[Link]("Celsius = " + celsius);
} catch (NumberFormatException ex) {
// Exception handling for invalid input
[Link](this,
"Please enter a valid numeric value!",
"Invalid Input",
JOptionPane.ERROR_MESSAGE);
// Main method
public static void main(String[] args) {
new TemperatureConverter();
}
Output: