gpt4 book ai didi

Java的TextField无法解析,看不到

转载 作者:行者123 更新时间:2023-12-01 13:48:09 29 4
gpt4 key购买 nike

我一直在尝试处理一个类项目,在该项目中我必须设置一个面向 GUI 的转换程序,并且我试图将数据从我的类的方法传递到 ActionListener,但监听器是告诉我文本字段不存在。它位于同一个包和类中,我什至尝试像父类(super class)一样扩展它,但无济于事。

    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");
}
}
}

最佳答案

您需要考虑变量的范围。在 actionPerformed 方法中,ftomTextField 不可见。将 ftomTextField 声明为全局。

  public class feetToMeter extends JFrame{

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

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

关于Java的TextField无法解析,看不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184141/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com