java实现进制转换gui
时间: 2023-07-29 13:07:46 浏览: 140
好的,我可以为您提供一个简单的Java进制转换GUI实现,以下是代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ConverterGUI extends JFrame implements ActionListener {
private JTextField inputField, outputField;
private JButton binaryButton, decimalButton, hexadecimalButton;
public ConverterGUI() {
super("进制转换器");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
inputField = new JTextField(10);
outputField = new JTextField(10);
outputField.setEditable(false);
binaryButton = new JButton("二进制");
decimalButton = new JButton("十进制");
hexadecimalButton = new JButton("十六进制");
binaryButton.addActionListener(this);
decimalButton.addActionListener(this);
hexadecimalButton.addActionListener(this);
JPanel panel = new JPanel();
panel.add(inputField);
panel.add(binaryButton);
panel.add(decimalButton);
panel.add(hexadecimalButton);
panel.add(outputField);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String input = inputField.getText();
if (e.getSource() == binaryButton) {
try {
int decimal = Integer.parseInt(input, 2);
outputField.setText(Integer.toString(decimal));
} catch (NumberFormatException ex) {
outputField.setText("无效输入");
}
} else if (e.getSource() == decimalButton) {
try {
int decimal = Integer.parseInt(input);
outputField.setText(Integer.toBinaryString(decimal));
} catch (NumberFormatException ex) {
outputField.setText("无效输入");
}
} else if (e.getSource() == hexadecimalButton) {
try {
int decimal = Integer.parseInt(input, 16);
outputField.setText(Integer.toString(decimal));
} catch (NumberFormatException ex) {
outputField.setText("无效输入");
}
}
}
public static void main(String[] args) {
ConverterGUI gui = new ConverterGUI();
}
}
```
这个程序创建了一个简单的GUI,有一个文本框、三个按钮和另一个文本框。用户在第一个文本框中输入数字,然后选择要将数字转换为的进制。程序根据用户的选择将数字转换为二进制、十进制或十六进制,并将结果显示在第二个文本框中。
阅读全文