程序功能:在容器中添加组件标签、按钮,设计一个JAVA程序,根据用户在文本域中输入的十进制整数,利用消息框显示对应的二进制,八进制,十六进制。
时间: 2023-09-13 15:03:47 浏览: 41
以下是一个简单的Java程序,它会在一个容器中添加一个标签、一个按钮和一个文本域。当用户在文本域中输入一个整数时,点击按钮,程序会在消息框中显示对应的二进制、八进制和十六进制。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberConverter extends JFrame implements ActionListener {
private JTextField inputField;
private JLabel binaryLabel, octalLabel, hexLabel;
private JButton convertButton;
public NumberConverter() {
super("Number Converter");
Container c = getContentPane();
c.setLayout(new GridLayout(4, 2));
JLabel inputLabel = new JLabel("Decimal Number:");
c.add(inputLabel);
inputField = new JTextField();
c.add(inputField);
binaryLabel = new JLabel("Binary:");
c.add(binaryLabel);
convertButton = new JButton("Convert");
convertButton.addActionListener(this);
c.add(convertButton);
octalLabel = new JLabel("Octal:");
c.add(octalLabel);
hexLabel = new JLabel("Hexadecimal:");
c.add(hexLabel);
setSize(400, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == convertButton) {
try {
int decimal = Integer.parseInt(inputField.getText());
String binary = Integer.toBinaryString(decimal);
binaryLabel.setText("Binary: " + binary);
String octal = Integer.toOctalString(decimal);
octalLabel.setText("Octal: " + octal);
String hex = Integer.toHexString(decimal);
hexLabel.setText("Hexadecimal: " + hex.toUpperCase());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid input. Please enter a valid decimal number.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
NumberConverter nc = new NumberConverter();
nc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
运行程序后,你可以在文本域中输入一个十进制整数,点击“Convert”按钮,程序会将其转换为二进制、八进制和十六进制,并在标签上显示结果。如果输入无效的数字,程序会弹出一个错误消息框。