Advertisement
Guest User

My Problem

a guest
May 25th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. import javax.swing.*;
  2.  
  3. public class Main {
  4.  
  5.     private static JFrame frame = new JFrame("Binaries and Decimals");
  6.     private static JPanel panel = new JPanel();
  7.     private static JTextField text = new JTextField(20);
  8.     private static JTextArea out = new JTextArea();
  9.     private static JButton enter = new JButton("enter");
  10.     private static JButton button = new JButton("convert");
  11.     private static String[] options = {"Binary to Decimal", "Decimal to Binary"};
  12.     private static JComboBox box = new JComboBox(options);
  13.  
  14.     public static void main(String[] args) {
  15.         window();
  16.         enter.addActionListener(e -> mode());
  17.  
  18.     }
  19.  
  20.     private static void mode() {
  21.         out.setText("");
  22.         if (box.getSelectedItem().equals("Binary to Decimal")) {
  23.             bintodec();
  24.         } else if (box.getSelectedItem().equals("Decimal to Binary")) {
  25.             dectobin();
  26.         }
  27.     }
  28.  
  29.     private static void window() {
  30.  
  31.         panel.add(box);
  32.         panel.add(text);
  33.         panel.add(enter);
  34.         panel.add(button);
  35.         out.setEditable(false);
  36.         panel.add(out);
  37.         frame.setContentPane(panel);
  38.         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  39.         frame.setSize(600, 250);
  40.         frame.setResizable(false);
  41.         frame.setVisible(true);
  42.  
  43.  
  44.     }
  45.  
  46.     private static void bintodec() {
  47.         out.setText("");
  48.         String bin = text.getText();
  49.         String dec = "Your number as decimal: " + Integer.parseInt(bin, 2);
  50.         button.addActionListener(e -> out.setText(dec));
  51.         out.revalidate();
  52.  
  53.  
  54.     }
  55.  
  56.     private static void dectobin() {
  57.         out.setText("");
  58.         String in = text.getText();
  59.         int dec = Integer.parseInt(in);
  60.         int waste;
  61.         String bin = "";
  62.         while (dec > 0) {
  63.             waste = dec % 2;
  64.             dec = dec / 2;
  65.             bin = bin + waste;
  66.         }
  67.         String finalBin = "Your number as binary: " + new StringBuilder(bin).reverse().toString();
  68.         button.addActionListener(e -> out.setText(finalBin));
  69.         out.revalidate();
  70.  
  71.     }
  72.  
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement