java实现进制转换gui
时间: 2023-07-29 18:07:46 浏览: 176
好的,我可以为您提供一个简单的Java GUI程序,用于将十进制数转换为其他进制。以下是代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Converter extends JFrame implements ActionListener {
// GUI Components
private JTextField decimalField;
private JLabel binaryLabel, octalLabel, hexLabel;
public Converter() {
// Set up the GUI
setTitle("Decimal to Other Bases Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 200));
// Create GUI components
decimalField = new JTextField(10);
JButton convertButton = new JButton("Convert");
convertButton.addActionListener(this);
binaryLabel = new JLabel("Binary: ");
octalLabel = new JLabel("Octal: ");
hexLabel = new JLabel("Hexadecimal: ");
// Add components to the content pane
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(4, 1));
contentPane.add(decimalField);
contentPane.add(convertButton);
contentPane.add(binaryLabel);
contentPane.add(octalLabel);
contentPane.add(hexLabel);
// Display the GUI
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Get the decimal input
int decimal = Integer.parseInt(decimalField.getText());
// Convert to binary, octal, and hexadecimal
String binary = Integer.toBinaryString(decimal);
String octal = Integer.toOctalString(decimal);
String hex = Integer.toHexString(decimal);
// Display the results
binaryLabel.setText("Binary: " + binary);
octalLabel.setText("Octal: " + octal);
hexLabel.setText("Hexadecimal: " + hex);
}
public static void main(String[] args) {
new Converter();
}
}
```
该程序创建了一个简单的GUI窗口,其中包含一个文本框和一个“转换”按钮,以及三个标签用于显示二进制、八进制和十六进制结果。当用户单击“转换”按钮时,程序将获取文本框中输入的十进制数,并使用Java的内置转换函数将其转换为其他进制。然后,程序将结果显示在相应的标签中。
阅读全文