Skip to content

Instantly share code, notes, and snippets.

@L8RFN
Created January 6, 2024 05:23
Show Gist options
  • Save L8RFN/087739632a71777d27d8c127b6df2634 to your computer and use it in GitHub Desktop.
Save L8RFN/087739632a71777d27d8c127b6df2634 to your computer and use it in GitHub Desktop.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame{
JLabel unit= new JLabel("calculator");
JTextField input = new JTextField("Enter the number you want to convert it.");
JTextField output = new JTextField("the result will be displayed here.");
String units [] ={"centimeter","meter"};
JComboBox typeOne = new JComboBox(units);
JComboBox typeTwo = new JComboBox(units);
JButton convert = new JButton("Convert");
JButton clear = new JButton("Clear");
JLabel space = new JLabel(" Unit");
JPanel nor = new JPanel(new GridLayout(1,3));
JPanel cen = new JPanel(new GridLayout(2,2));
JPanel bot = new JPanel(new GridLayout(1,4));
JTextArea border = new JTextArea("Hiiiiiiiiiiiii");
JTextArea border2 =new JTextArea("Hiiiiiiiiiiiii");
JLabel space2 = new JLabel();
JLabel space3= new JLabel();
JLabel space4 = new JLabel();
JLabel space5 = new JLabel();
JLabel space6 = new JLabel();
JLabel space7 = new JLabel();
public GUI(){
nor.add(space);
nor.add(unit);
cen.add(input);
cen.add(output);
cen.add(typeOne);
cen.add(typeTwo);
bot.add(space2,BorderLayout.WEST);//wow, you can use borderlayout.west with a grid layout
bot.add(convert);
bot.add(clear);
bot.add(space7,BorderLayout.WEST);
add(nor,BorderLayout.NORTH);
add(cen,BorderLayout.CENTER);
add(bot,BorderLayout.SOUTH);
add(border,BorderLayout.EAST);
add(border2,BorderLayout.WEST);
convert.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
String in = (String) typeOne.getSelectedItem();
String out = (String) typeTwo.getSelectedItem();
double inNum = Double.parseDouble(input.getText());
double result;
if (in.equals("centimeter")&&out.equals("meter")){
result = inNum/100;
output.setText(result+"");
}
if (in.equals("meter")&&out.equals("meter")){
result = inNum;
output.setText(result+"");
}
if (in.equals("centimeter")&&out.equals("centimeter")){
result = inNum;
output.setText(result+"");
}
if (in.equals("meter")&&out.equals("centimeter")){
result = inNum * 100;
output.setText(result+"");
}
}
});
setVisible(true);
setSize(650,300);
setLocationRelativeTo(null);
setTitle("Unit Calculator");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment