以下是我的程序。目的是在用户键入数字并按Enter键之后,将罗马数字转换为阿拉伯数字。
这是一项家庭作业,我们被迫JTextAreas代替JTextFields。
JTextAreas
JTextFields
线路中存在我的错误:enterRomanNumber.addActionListener(handler); 该错误显示为:
enterRomanNumber.addActionListener(handler)
“对于类型JTextArea,未定义方法addActionListener(ArabicToRomanGUI.HandlerForTextArea)”
我似乎无法弄清楚为什么会收到此错误或如何纠正它,有人可以建议一下。
import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; public class ArabicToRomanGUI extends JFrame { private static final long serialVersionUID = 1L; private JTextArea enterRomanNumber = new JTextArea(); JLabel label = new JLabel(); JPanel panel = new JPanel(); JFrame frame = new JFrame(); //TestArea contructor adds jtextArea to jframe public ArabicToRomanGUI() { super("Convert a Roman Numeral"); setLayout(new FlowLayout()); //Text field to enter a roman numeral enterRomanNumber = new JTextArea(1,25); enterRomanNumber.setText("Delete this text and Enter a Roman Numerial Here!"); //enterRomanNumber.setAlignmentX(0); //enterRomanNumber.setAlignmentY(0); add(enterRomanNumber); HandlerForTextArea handler = new HandlerForTextArea(); enterRomanNumber.addActionListener(handler); } private class HandlerForTextArea implements ActionListener { //used to process textArea events @Override public void actionPerformed(ActionEvent e) { String userInput = ""; userInput = enterRomanNumber.getText(); userInput = userInput.toUpperCase(); ConversionLogic.ConvertFromRomanToArabic(userInput); //converts user string of Roman numerals to an int in arabic String arabicNumberAsString = ConversionLogic.getConvertedRomanNumeral(); enterRomanNumber.setText(arabicNumberAsString); //user pressed enter in JTextField enterNumberField if(e.getSource() == enterRomanNumber) { //enterRomanNumber.setText(arabicNumberAsString); if (ConversionLogic.getCheckFail() == true) { JOptionPane.showMessageDialog(frame, "The Roman Numeral entered is Invalid", "Error", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "The arabic equivalent is " + arabicNumberAsString + "." , "Conversion Successful", JOptionPane.PLAIN_MESSAGE); } } } } }//end inner class TextAreaHandler
有关更好的答案,请参见 @MadProgrammer 的答案。
我的解决方案:
JTextArea没有ActionListener。
所以只用KeyListener代替
KeyListener
HandlerForTextArea handler = new HandlerForTextArea(); enterRomanNumber.addKeyListener(handler);
实现KeyListener
private class HandlerForTextArea implements KeyListener { @Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub if (arg0.getKeyCode() == VK_ENTER){ // TODO Your bussiness } } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }