Minggu, 02 Juni 2013

Program Java untuk Mengkonversi Suhu

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class KonversiSuhu extends JFrame {

private JLabel lblTitle;
private JTextField txtInput;
private JTextField txtOutput;
private JComboBox cboInputScale;
private JComboBox cboOutputScale;
private JLabel lblArrow;
private JButton btnOk;

public KonversiSuhu() {
setLayout(null);
setTitle("Konversi Suhu");
setSize(400, 300);

lblTitle = new JLabel();
lblTitle.setText("KONVERSI SUHU");
lblTitle.setLocation(150, 20);
lblTitle.setSize(150, 20);

txtInput = new JTextField();
txtInput.setLocation(50, 80);
txtInput.setSize(80, 20);

txtOutput = new JTextField();
txtOutput.setLocation(250, 80);
txtOutput.setSize(80, 20);
txtOutput.setEditable(false);

cboInputScale = new JComboBox();
cboInputScale.addItem("Celcius");
cboInputScale.addItem("Fahrenheit");
cboInputScale.addItem("Kelvin");
cboInputScale.addItem("Reaumure");
cboInputScale.setLocation(50, 110);
cboInputScale.setSize(90, 20);

cboOutputScale = new JComboBox();
cboOutputScale.addItem("Celcius");
cboOutputScale.addItem("Fahrenheit");
cboOutputScale.addItem("Kelvin");
cboOutputScale.addItem("Reaumure");
cboOutputScale.setLocation(250, 110);
cboOutputScale.setSize(90, 20);

lblArrow = new JLabel();
lblArrow.setText(">>>");
lblArrow.setLocation(180, 100);
lblArrow.setSize(50, 20);

btnOk = new JButton();
btnOk.setText("OK");
btnOk.setLocation(160, 160);
btnOk.setSize(60, 20);

ButtonHandler handler = new ButtonHandler();
btnOk.addActionListener(handler);

add(lblTitle);
add(txtInput);
add(txtOutput);
add(cboInputScale);
add(cboOutputScale);
add(lblArrow);
add(btnOk);
}

public static void main(String[] args) {
KonversiSuhu app = new KonversiSuhu();
app.setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent event) {
try {
float input = Float.parseFloat(txtInput.getText());

int inputScale = getScale(cboInputScale.getSelectedIndex());
int outputScale = getScale(cboOutputScale.getSelectedIndex());

int inputFrz = getFrzPoint(cboInputScale.getSelectedIndex());
int outputFrz = getFrzPoint(cboOutputScale.getSelectedIndex());

float result = ((input - inputFrz) * outputScale / inputScale) + outputFrz;

txtOutput.setText(Float.toString(result));
} catch (NumberFormatException numberFormatException) {
JOptionPane.showMessageDialog(null, "Anda harus menginput bilangan");
}
}

public int getScale(int index) {
switch(index) {
case 1: return 9;
case 3: return 4;
default: return 5;
}
}

public int getFrzPoint(int index) {
switch(index) {
case 1: return 32;
case 2: return 273;
default: return 0;
}
}

}

}


#Semoga bermanfaat :)