请编写图像界面程序,
用户在第一文本行输入数字,
有三个按钮,分别是计算2进制,8进制,16进制,
点击其中一个按钮,第一个文本行中的数据转换为相应进制的数显示在第二个文本行中。
import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.WindowConstants; public class Test3 extends JFrame{ public Test3() { setTitle("整数进制转换"); setLayout(null); setBounds(0, 0, 400, 300); Container container = getContentPane(); JTextField jTextField1 = new JTextField(40); JTextField jTextField2 = new JTextField(40); JButton jButton2 = new JButton("2进制转化"); JButton jButton8 = new JButton("8进制转化"); JButton jButton16 = new JButton("16进制转化"); jTextField1.setBounds(80, 20, 200, 30); jTextField2.setBounds(80, 180, 200, 30); jButton16.setBounds(20, 100, 100, 30); jButton8.setBounds(220, 100, 100, 30); jButton2.setBounds(120, 100, 100, 30); container.add(jTextField1); container.add(jTextField2); container.add(jButton2); container.add(jButton8); container.add(jButton16); String string = "q23"; setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jTextField1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jTextField1.setText("触发事件"); } }); //2进制 jButton2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object object = jTextField1.getText(); String str = object.toString(); int i = Integer.parseInt(str); jTextField2.setText(Integer.toBinaryString(i)); jTextField1.requestFocus(); } }); //8进制 jButton8.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object object = jTextField1.getText(); String str = object.toString(); int i = Integer.parseInt(str); jTextField2.setText(Integer.toOctalString(i)); jTextField1.requestFocus(); } }); //16进制 jButton16.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object object = jTextField1.getText(); String str = object.toString(); int i = Integer.parseInt(str); jTextField2.setText(Integer.toHexString(i)); jTextField1.requestFocus(); } }); } public static void main(String[] args) { new Test3(); } }
结果如下:
二进制:
八进制:
十六进制: