[英]How do I use variables from different method in java?
首先让我说我对 Java 很陌生所以这真的很简单但是我有这个日期对象并且我做了一个 actionlistener 方法但是它不会让我在那里使用这个对象。 我如何制作它以便我可以在方法中访问?
jp = new JPanel();
jta = new JTextArea(100, 100);
jta.setPreferredSize(new Dimension(460,420));
jta.setLineWrap(true);
jta.setWrapStyleWord(true);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
jb = new JButton("Tommorow");
jl = new JLabel();
jf = new JFrame();
jf.setBackground(Color.BLUE);
jl.setText(dateFormat.format(date));
add(jl, BorderLayout.NORTH);
add(jp);
jp.add(jb, BorderLayout.EAST);
add(jta);
jb.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
jta.setText("");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
您当前的变量范围存在问题。 您不能在方法public void actionPerformed(ActionEvent e)
使用来自另一个方法的变量。 上面你用过:
jta = new JTextArea(100, 100);
jta.setPreferredSize(new Dimension(460,420));
jta.setLineWrap(true);
jta.setWrapStyleWord(true);
变量jta
是该方法的本地变量,不能被其他方法访问。 Date date = new Date();
. 如果要继续使用这些变量,请在下面创建一个包含这些变量的对象。 它可能看起来像这样:
public class MyClass {
private JTextArea textArea;
private Date date;
public MyClass(JTextArea textArea, Date date) {
this.textArea = textArea;
this.date = date;
}
public JTextArea getTextArea() {
return this.textArea;
}
public Date getDate() {
return this.date;
}
}
你有一个范围问题。 你不能从其他函数访问变量,除非它们首先被声明为全局变量,或者在函数参数中传递
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.