import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame implements ActionListener{
private static final int Bin=0,Oct=1,Hex=2;
private int flag=0;
private JComboBox comboBox=new JComboBox(new String[]{"二进制转换","八进制转换","十六进制转换"});
private JLabel l1=new JLabel("十进制"),l2=new JLabel("二进制");
private JButton b1=new JButton("=====>"),b2=new JButton("<=====");
private JTextArea tf1=new JTextArea(5,30),tf2=new JTextArea(5,30);
public MainFrame() {
super("转换");
Container c=this.getContentPane();
c.setLayout(new BorderLayout(10,10));
comboBox.setEditable(false);
comboBox.addActionListener(this);
c.add(comboBox,BorderLayout.NORTH);
b1.addActionListener(this);
b2.addActionListener(this);
JPanel panel=new JPanel(new GridLayout(3, 1, 5, 5));
JPanel panel1=new JPanel();
panel1.add(l1);
panel1.add(tf1);
panel.add(panel1);
panel1=new JPanel();
panel1.add(b1);
panel1.add(b2);
panel.add(panel1);
panel1=new JPanel();
panel1.add(l2);
panel1.add(tf2);
panel.add(panel1);
c.add(panel,BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame=new MainFrame();
frame.setResizable(false);
frame.setBounds(200, 200, 500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==comboBox){
flag=comboBox.getSelectedIndex();
switch(flag){
case Bin:l2.setText("二进制");break;
case Oct:l2.setText("八进制");break;
case Hex:l2.setText("十六进制");break;
default:break;
}
return;
}
if(e.getSource()==b1){
encode();
}
if(e.getSource()==b2){
decode();
}
}
private void encode(){
try{
switch(flag){
case Bin:tf2.setText(Integer.toBinaryString(Integer.parseInt(tf1.getText())));break;
case Oct:tf2.setText(Integer.toOctalString(Integer.parseInt(tf1.getText())));break;
case Hex:tf2.setText(Integer.toHexString(Integer.parseInt(tf1.getText())));break;
}
}catch(Exception e){e.printStackTrace();return;}
}
private void decode(){
try{
switch(flag){
case Bin:tf1.setText(String.valueOf(Integer.valueOf(tf2.getText(),2)));break;
case Oct:tf1.setText(String.valueOf(Integer.valueOf(tf2.getText(),8)));break;
case Hex:tf1.setText(String.valueOf(Integer.valueOf(tf2.getText(),16)));break;
}
}catch(Exception e){e.printStackTrace();return;}
}
}
楼主共给出了四种进制。
每一种进制,都要转换成其它三种,共需要编写12种转换函数。
分数,有点低。