Re: decimal to binary converter - java
sam20e wrote:
hi i need a help... i wanna write a java programmee to display the
binary number of the entered decimal number.
for ex : in t text area u should type a desimal number and press
"Convert" button to display its binary in the next txt field
need help mates, i need to write a programme.. i need the "JAVA CODES"
p.s : should use only 1 statement; stack
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Converter
extends JPanel
implements ActionListener
{
protected JTextField textField;
protected JTextArea textArea;
protected JButton button;
public Converter()
{
super(new BorderLayout());
textField = new JTextField(20);
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
textArea.setLineWrap(true);
button = new JButton("Convert");
button.addActionListener(this);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(textField, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
}
private String convert(String text)
{
Integer i;
try
{
i = Integer.valueOf(text);
}
catch (NumberFormatException e)
{
return "Not a valid integer";
}
return Integer.toHexString(i);
}
public void actionPerformed(ActionEvent evt)
{
textArea.replaceRange("", 0, textArea.getText().length());
String text = convert(textField.getText());
textArea.append(text);
textField.selectAll();
textField.replaceSelection("");
textField.requestFocusInWindow();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Converter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Converter());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}