获取值并将文本打印到文本字段

时间:2017-04-22 13:29:57

标签: java jtextfield

在这个问题中,我希望用户在第一个文本字段中输入值 用户应该按计算。 要获取用户输入此行的值,应该这样做。

 int j = Integer.parseInt(s.getText());

但我有错误,

其中说:不能引用封闭范围中定义的非最终局部变量。

然后我想在第二个文本字段中打印y1 但我不知道该怎么做

 package ass3;

 import java.awt.FlowLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 import java.awt.GridLayout;

 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JTextField;
 import javax.swing.SwingConstants;

  public class secondsConvert {
    public static void main(String[] args){
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("second convert program");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(8,2));
        JLabel seconds = new JLabel("Enter seconds",SwingConstants.RIGHT);
        frame.add(seconds);
        JTextField s = new JTextField(10);
        frame.add(s);
        JLabel year = new JLabel("Years",SwingConstants.RIGHT);
        frame.add(year);
        JTextField y = new JTextField(10);
        frame.add(y);
        JLabel week = new JLabel("Weeks",SwingConstants.RIGHT);
        frame.add(week);
        JTextField w = new JTextField(10);
        frame.add(w);
        JLabel day = new JLabel("Days",SwingConstants.RIGHT);
        frame.add(day);
        JTextField d = new JTextField(10);
        frame.add(d);
        JLabel hours = new JLabel("Hours",SwingConstants.RIGHT);
        frame.add(hours);
        JTextField h = new JTextField(10);
        frame.add(h);
        JLabel minuts = new JLabel("Minuts",SwingConstants.RIGHT);
        frame.add(minuts);
        JTextField m = new JTextField(10);
        frame.add(m);
        JLabel un = new JLabel("Seconds",SwingConstants.RIGHT);
        frame.add(un);
        JTextField u = new JTextField(10);
        frame.add(u);
        JButton b1 = new JButton("OK");
        frame.add(b1);
        JButton b2 = new JButton("Calculate");
        frame.add(b2);
        ActionListener act = new ActionListener(){
             public void actionPerformed(ActionEvent e) {
                 int j = Integer.parseInt(s.getText());
                 int y1=j/31536000;
                 int a=j%31536000;
             }
        };
        b2.addActionListener(act);
        frame.pack();
        frame.setVisible(true);
}
  }

2 个答案:

答案 0 :(得分:6)

这个答案是针对你的第二个问题。如果你想在年份(y textfield)打印y1,你应该尝试这样。计算后的行为动作列表中

 y.setText(Integer.toString(y1));

答案 1 :(得分:1)

这是因为

问题是匿名内部类会复制他们使用的本地字段,如果字段不是最终字段,则副本可能与原始字段不同,从而导致各种问题。(摘自{{3 }})

您有两种选择: 1.在main方法之前声明变量如:

public class secondsConvert {

JTextField s = new JTextField(10);

public static void main(String[] args)
{
}
}
  1. 将变量声明为final:

    public static void main(String [] args)

    {

    final JTextField s = new JTextField(10);

    }

相关问题