首先让我说我是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();
}
答案 0 :(得分:1)
您目前的变量范围有问题。您无法在方法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;
}
}
答案 1 :(得分:0)
你有范围问题。您不能从其他函数访问变量,除非它们首先声明为全局变量,或者在函数参数中传递