Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write an applet that converts between decimal, hex, and binary numbers, as shown

ID: 3542724 • Letter: W

Question

Write an applet that converts between decimal, hex, and binary numbers, as shown in Figure 18.18b. When you enter a decimal value in the decimal-value text field and press the Enter key, its corresponding hex and binary numbers are displayed in the other two text fields. Likewise, you can enter values in the other fields and convert them accordingly.

Write an applet that converts between decimal, hex, and binary numbers, as shown in Figure 18.18b. When you enter a decimal value in the decimal-value text field and press the Enter key, its corresponding hex and binary numbers are displayed in the other two text fields. Likewise, you can enter values in the other fields and convert them accordingly.

Explanation / Answer

import java.awt.*;

02

import java.applet.*;

03

import java.awt.event.*;

04

05

public class DecConverter extends Applet implements ActionListener, ItemListener

06

{

07

CheckboxGroup cbg = new CheckboxGroup();

08

Checkbox cb1, cb2, cb3, cb4;

09

TextField number;

10

int num=0;

11

String msg="", text="";

12

public void init()

13

{

14

Panel p1 = new Panel();

15

Panel p2 = new Panel();

16

Checkbox cb1= new Checkbox("Hex",cbg,false);

17

Checkbox cb2= new Checkbox("Oct",cbg,false);

18

Checkbox cb3= new Checkbox("Binary",cbg,false);

19

Checkbox cb4= new Checkbox("Decimal",cbg,true);

20

number= new TextField(30);

21

Label nl= new Label("number: ", Label.RIGHT);

22

number.addActionListener(this);

23

p1.add(nl);p1.add(number);p2.add(cb1); p2.add(cb2); p2.add(cb3); p2.add(cb4);

24

setLayout(new GridLayout(2,1));

25

add(p1); add(p2);

26

cb1.addItemListener(this);

27

cb2.addItemListener(this);

28

cb3.addItemListener(this);

29

cb4.addItemListener(this);

30

setLayout(new GridLayout(2,1,0,1));

31

}

32

public void actionPerformed(ActionEvent ae)

33

{

34

text=number.getText();

35

num=Integer.parseInt(text);

36

}

37

38

public void itemStateChanged(ItemEvent ie)

39

{

40

if(cb4.getState())

41

{

42

msg=text+" in decimal is "+num;

43

}

44

else if(cb3.getState())

45

{

46

msg=text+" in binary is "+Integer.toBinaryString(num);

47

48

}   

49

else if(cb2.getState())

50

{

51

msg=text+" in octal is "+Integer.toOctalString(num);

52

53

}

54

else

55

{

56

msg=text+" in hexadecimal is "+Integer.toHexString(num);

57

58

}

59

repaint();

60

}

61

public void paint(Graphics g)

62

{

63

64

g.drawString(msg,60,100);

65

}

66

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote