简体   繁体   English

如何在java中使用来自不同方法的变量?

[英]How do I use variables from different method in java?

First off let me say that I am very new to java so this is really simple but I have this date object and I made an actionlistener method but it won't let me use the object in there.首先让我说我对 Java 很陌生所以这真的很简单但是我有这个日期对象并且我做了一个 actionlistener 方法但是它不会让我在那里使用这个对象。 How do I make it so that I can access in the method?我如何制作它以便我可以在方法中访问?

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

You are currently having a problem with the scope of your variables.您当前的变量范围存在问题。 You cannot use variables from your another method in the method public void actionPerformed(ActionEvent e) .您不能在方法public void actionPerformed(ActionEvent e)使用来自另一个方法的变量。 Above you used:上面你用过:

jta = new JTextArea(100, 100);
jta.setPreferredSize(new Dimension(460,420));
jta.setLineWrap(true);
jta.setWrapStyleWord(true);

The variable jta is local to that method and cannot be accessed by other methods.变量jta是该方法的本地变量,不能被其他方法访问。 The same goes for Date date = new Date(); Date date = new Date(); . . If you want to continue to use these variables down below create an object contains these variables.如果要继续使用这些变量,请在下面创建一个包含这些变量的对象。 It could look something like this:它可能看起来像这样:

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

}

You're having a scope problem.你有一个范围问题。 You can't access variables from other functions unless they are first declared as globals, or passed around in function parameters你不能从其他函数访问变量,除非它们首先被声明为全局变量,或者在函数参数中传递

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM