Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- public class Main {
- private static JFrame frame = new JFrame("Binaries and Decimals");
- private static JPanel panel = new JPanel();
- private static JTextField text = new JTextField(20);
- private static JTextArea out = new JTextArea();
- private static JButton enter = new JButton("enter");
- private static JButton button = new JButton("convert");
- private static String[] options = {"Binary to Decimal", "Decimal to Binary"};
- private static JComboBox box = new JComboBox(options);
- public static void main(String[] args) {
- window();
- enter.addActionListener(e -> mode());
- }
- private static void mode() {
- out.setText("");
- if (box.getSelectedItem().equals("Binary to Decimal")) {
- bintodec();
- } else if (box.getSelectedItem().equals("Decimal to Binary")) {
- dectobin();
- }
- }
- private static void window() {
- panel.add(box);
- panel.add(text);
- panel.add(enter);
- panel.add(button);
- out.setEditable(false);
- panel.add(out);
- frame.setContentPane(panel);
- frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- frame.setSize(600, 250);
- frame.setResizable(false);
- frame.setVisible(true);
- }
- private static void bintodec() {
- out.setText("");
- String bin = text.getText();
- String dec = "Your number as decimal: " + Integer.parseInt(bin, 2);
- button.addActionListener(e -> out.setText(dec));
- out.revalidate();
- }
- private static void dectobin() {
- out.setText("");
- String in = text.getText();
- int dec = Integer.parseInt(in);
- int waste;
- String bin = "";
- while (dec > 0) {
- waste = dec % 2;
- dec = dec / 2;
- bin = bin + waste;
- }
- String finalBin = "Your number as binary: " + new StringBuilder(bin).reverse().toString();
- button.addActionListener(e -> out.setText(finalBin));
- out.revalidate();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement