简体   繁体   中英

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. 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) . 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. The same goes for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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