使用java编写一个有界面的进制互相转换应用程序在windows上使用
时间: 2023-05-29 17:06:30 浏览: 115
以下是使用Java Swing编写的一个简单的进制转换应用程序。该应用程序可以将二进制、八进制、十进制和十六进制之间进行转换,并提供了一个简单的用户界面。
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NumberConverter extends JFrame implements ActionListener {
private JTextField inputField, outputField;
private JButton binButton, octButton, decButton, hexButton;
public NumberConverter() {
super("Number Converter");
// Create input field
inputField = new JTextField();
inputField.addActionListener(this);
// Create output field
outputField = new JTextField();
outputField.setEditable(false);
// Create buttons
binButton = new JButton("Bin");
binButton.addActionListener(this);
octButton = new JButton("Oct");
octButton.addActionListener(this);
decButton = new JButton("Dec");
decButton.addActionListener(this);
hexButton = new JButton("Hex");
hexButton.addActionListener(this);
// Create layout
JPanel contentPane = new JPanel(new BorderLayout());
JPanel inputPanel = new JPanel(new BorderLayout());
inputPanel.add(new JLabel("Enter number: "), BorderLayout.WEST);
inputPanel.add(inputField, BorderLayout.CENTER);
contentPane.add(inputPanel, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(1, 4));
buttonPanel.add(binButton);
buttonPanel.add(octButton);
buttonPanel.add(decButton);
buttonPanel.add(hexButton);
contentPane.add(buttonPanel, BorderLayout.CENTER);
JPanel outputPanel = new JPanel(new BorderLayout());
outputPanel.add(new JLabel("Result: "), BorderLayout.WEST);
outputPanel.add(outputField, BorderLayout.CENTER);
contentPane.add(outputPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
// Set window properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
String input = inputField.getText();
if (e.getSource() == binButton) {
outputField.setText(Integer.parseInt(input, 2) + "");
} else if (e.getSource() == octButton) {
outputField.setText(Integer.parseInt(input, 8) + "");
} else if (e.getSource() == decButton) {
outputField.setText(Integer.parseInt(input, 10) + "");
} else if (e.getSource() == hexButton) {
outputField.setText(Integer.parseInt(input, 16) + "");
} else {
outputField.setText("");
}
} catch (NumberFormatException ex) {
outputField.setText("Invalid input");
}
}
public static void main(String[] args) {
new NumberConverter();
}
}
```
运行该程序后,将会看到一个简单的窗口,用户可以在其中输入数字并将其转换为二进制、八进制、十进制或十六进制。例如,输入十进制数字“42”,按下“Hex”按钮,将会显示十六进制数字“2A”。
阅读全文