编写窗体应用程序,安排一个文本框、一个按钮和一个标签,从文本框录入一个数字(0~9),点击按钮将其对应的英文单词(如:zero,one等)显示在标签中。 用java实现
时间: 2024-06-04 19:11:29 浏览: 129
好的,我可以帮你解决这个问题。以下是使用 Java 代码实现:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class NumberToWordsConverter implements ActionListener {
private JFrame frame;
private JTextField textField;
private JButton button;
private JLabel label;
public NumberToWordsConverter() {
frame = new JFrame("Number to Words Converter");
frame.setSize(400, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
textField = new JTextField();
textField.setBounds(50, 30, 100, 20);
frame.add(textField);
button = new JButton("Convert");
button.setBounds(170, 30, 100, 20);
button.addActionListener(this);
frame.add(button);
label = new JLabel();
label.setBounds(50, 70, 300, 20);
frame.add(label);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String[] words = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
String input = textField.getText().trim();
if (input.matches("[0-9]")) {
int number = Integer.parseInt(input);
label.setText(words[number]);
} else {
label.setText("Please enter a single digit number (0-9).");
}
}
public static void main(String[] args) {
new NumberToWordsConverter();
}
}
阅读全文