Open all | Close all
|
Code of simple Swing Java Applications
Below you will find the Java code for creating a simple Swing application.
|
Swing application to Convert Celsius to Fahrenheit (buttons, input fields and labels)
//package swing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Converter implements ActionListener {
JFrame frame;
JPanel panel;
JTextField tempCel;
JLabel celLabel, fahLabel, resultFah;
JButton changeTemp;
public Converter() {
//Create and set up the window.
frame = new JFrame("Change Celsius to Fahrenheit");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(180, 80));
//Create and set up the panel.
panel = new JPanel(new GridLayout(3, 2));
panel.setBorder(BorderFactory.createEmptyBorder(60, //top
60, //left
20, //bottom
60) //right
);
//Add the items.
addItems();
//Set the default button.
frame.getRootPane().setDefaultButton(changeTemp);
//Add the panel to the frame.
frame.getContentPane().add(panel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
private void addItems() {
//Create items.
tempCel = new JTextField(2);
celLabel = new JLabel("Celsius", SwingConstants.LEFT);
resultFah = new JLabel("", SwingConstants.LEFT);
fahLabel = new JLabel("Fahrenheit", SwingConstants.LEFT);
changeTemp = new JButton("Convert");
//Listen to events from the Convert button.
changeTemp.addActionListener(this);
//Add the items to the container.
panel.add(tempCel);
panel.add(celLabel);
panel.add(resultFah);
panel.add(fahLabel);
panel.add(changeTemp);
celLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
fahLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
public void actionPerformed(ActionEvent event) {
//Parse degrees Celsius as a double and convert to Fahrenheit.
int tempFahr =
(int) ((Double.parseDouble(tempCel.getText())) * 1.8 + 32);
resultFah.setText(tempFahr + "");
}
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
Converter converter = new Converter();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
|
|
|