Java源程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test25 extends JFrame implements ActionListener {
JTextField txtDec;
JTextField txtBin;
JTextField txtOct;
JTextField txtHex;
public Test25(){
super("十进制整数转换");
txtDec = new JTextField(15);
txtBin = new JTextField(15);
txtOct = new JTextField(15);
txtHex = new JTextField(15);
txtBin.setEditable(false);
txtOct.setEditable(false);
txtHex.setEditable(false);
this.setLayout(new FlowLayout());
this.add(new JLabel(" 十进制"));
this.add(txtDec);
this.add(new JLabel(" 二进制"));
this.add(txtBin);
this.add(new JLabel(" 八进制"));
this.add(txtOct);
this.add(new JLabel("十六进制"));
this.add(txtHex);
txtDec.addActionListener(this);
this.setSize(250, 150);
this.setResizable(false);
this.setVisible(true);
}
public static void main(String[] args) {
new Test25();
}
@Override
public void actionPerformed(ActionEvent e) {
JTextField txt = (JTextField)e.getSource();
if(txt.getText() == null || txt.getText().trim().equals("")){
JOptionPane.showMessageDialog(this, "十进制数不能为空");
return;
}
int num;
try{
num = Integer.parseInt(txt.getText());
if(num < 0){
num *= -1;
txtBin.setText("-" + Convert.format(num, 2));
txtOct.setText("-" + Convert.format(num, 8));
txtHex.setText("-" + Convert.format(num, 16));
}
else{
txtBin.setText(Convert.format(num, 2));
txtOct.setText(Convert.format(num, 8));
txtHex.setText(Convert.format(num, 16));
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(this, "十进制数错误");
return;
}
}
}
class Convert{
private static String[] bins = {"0", "1"};
private static String[] octs = {"0", "1", "2", "3", "4", "5", "6", "7"};
private static String[] hexs = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
public static String format(int num, int r){
StringBuffer buff = new StringBuffer();
if(r == 2){
while(num > 0){
buff.append(bins[num%r]);
num /= r;
}
}
else if(r == 8){
while(num > 0){
buff.append(octs[num%r]);
num /= r;
}
}
else if(r == 16){
while(num > 0){
buff.append(hexs[num%r]);
num /= r;
}
}
buff.reverse();
return buff.toString();
}
}
运行测试: