Java的TextField无法解决,无法看到

时间:2013-11-25 03:16:16

标签: java swing user-interface actionlistener jtextfield

我一直在努力开发一个类项目,我必须在其中设置面向GUI的转换程序,并且我试图将数据从我的类的方法传递给ActionListener,但是Listener是告诉我文本字段不存在。它在同一个包和类中,我甚至尝试像超类一样扩展它,但无济于事。

    package convertionProg;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;    
    import javax.swing.*;

    public class feetToMeter extends JFrame{

    JTextField ftomTextField = new JTextField(10);

    public static void Ftom(int d)
    {
        JFrame ftomWindow = new JFrame();
        ftomWindow.setTitle("Conversion Program: Feet to Meters");
        ftomWindow.setSize(200, 125);
        ftomWindow.setVisible(true);
        ftomWindow.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);          
        JPanel ftomPanel = new JPanel();
        ftomWindow.add(ftomPanel);          
        JLabel ftomLabel = new JLabel("Enter a distance in meters: ");
        JButton convert = new JButton("Convert");           
        ftomPanel.add(ftomLabel);
        ftomPanel.add(convert);
        ftomPanel.add(ftomTextField);           
        convert.addActionListener(new convertListener());
    }

    private static class convertListener implements ActionListener 
    {   
            public void actionPerformed(ActionEvent e)
            {
                final double CONVERSION = 0.3048;
                String input;   //Store input
                double meters;  //Stores meter output                   
                input = ftomTextField.getText();
                meters = Double.parseDouble(input);
                JOptionPane.showMessageDialog(null, "Distance in Meters is" + meters + "m");
            }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要考虑scope变量。在actionPerformed方法ftomTextField不可见。将ftomTextField声明为全球。

  public class feetToMeter extends JFrame{

    static JTextField ftomTextField = new JTextField(10);// Declare here.

    public static void Ftom(int d){
      ..............
    }
   }

答案 1 :(得分:0)

您已将JTextField ftomTextField = new JTextField(10);声明为本地变量,因此它超出了convertListener类的范围。