Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // school work
- import java.awt.*; //using awt's layouts
- import java.awt.event.*; //using awt's event classes and listener interfaces
- import javax.swing.*; //using swing's components and container
- //a swing application extends from javax.swing.JFrame
- public class SwingTemperatureConverter extends JFrame {
- private JTextField tfCelsius, tfFahrenheit;
- private float celsius, fahrenheit;
- public SwingTemperatureConverter() {
- //swing components should be added to the content-pane of the JFrame
- Container cp = getContentPane();
- //set this container to grid layout of 2 rows and 2 columns
- cp.setLayout(new GridLayout(2, 2, 10, 3));
- //components are added left-to-right, top-to-bottom
- cp.add(new JLabel("Celsius "));
- tfCelsius = new JTextField(10);
- tfCelsius.setHorizontalAlignment(JTextField.RIGHT);
- cp.add(tfCelsius);
- tfCelsius.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- celsius = Float.parseFloat(tfCelsius.getText());
- fahrenheit = (float) (9.0 / 5.0 * (celsius + 32));
- //tfFahrenheit.setText(fahrenheit + "");
- //String.format("%.1f", fahrenheit);
- tfFahrenheit.setText(String.format("%.1f", fahrenheit));
- }
- });
- cp.add(new JLabel("Fahrenheit "));
- tfFahrenheit = new JTextField(10);
- tfFahrenheit.setHorizontalAlignment(JTextField.RIGHT);
- cp.add(tfFahrenheit);
- tfFahrenheit.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- fahrenheit = Float.parseFloat(tfFahrenheit.getText());
- celsius = (float) (5.0 / 9.0 * (fahrenheit - 32));
- //tfCelsius.setText(celsius + "");
- tfCelsius.setText(String.format("%.1f", celsius));
- }
- });
- setDefaultCloseOperation(EXIT_ON_CLOSE); // for the "window-close" button
- setTitle("Swing Temperature Converter");
- setSize(300, 170);
- setVisible(true);
- }
- // The entry main() method
- public static void main(String[] args) {
- // For thread safety, use the event-dispatching thread to construct UI
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- new SwingTemperatureConverter(); // Let the constructor does the job
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement