从ActionListener访问变量并将其转移到新方法中

问题描述 投票:0回答:1

我已经做了一点Java,但有时仍然会格式化方法和变量,这取决于环境。我觉得这可能是一个简单的修复程序,但是由于某些原因,我坚持了下来。我在ActionListener中的按钮上附加了JDialog。激活此ActionListener方法后,它将创建一个字符串dateAndTime以及与TimerTask包中与Timer类相关的几个组件(我一直在考虑将其删除以代替ScheduledExecutorService ,但请放心)。我知道我可以在类中声明任何方法之外的全局变量,并且可以创建传递给方法的参数,这些方法的值在这些方法内部进行本地更新,但是我想知道:如何获取这些方法的值字符串,其指针在按下按钮后会被赋予值,并在其他将来的方法中使用它们?

ActionListener的代码在下面。

getMessageAndTime.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String mm = month.getSelectedItem().toString();
                    String dd = day.getSelectedItem().toString();
                    String yy = year.getSelectedItem().toString();
                    String hr = hour.getSelectedItem().toString();
                    String min = minute.getSelectedItem().toString();
                    String mornOrNight = am_pm.getSelectedItem().toString();

                    String dateAndTime = mm +"-" + dd +"-" + yy + " " + hr +":" + min + " " + mornOrNight;
                    dateFormatter = new SimpleDateFormat("MM-dd-yyyy hh:mm aa");

                    try {
                        date = dateFormatter.parse(dateAndTime);
                    } catch (ParseException ex) {
                        ex.printStackTrace();
                    }

                    timer = new Timer();
                    String contents = message.getText();
                    if (contents.equals("")) {
                        JOptionPane.showMessageDialog(d2, "Announcement field is blank. Please try again.",
                                "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
java string methods actionlistener
1个回答
0
投票

仅在此方法范围之外声明变量。

private String mm = "";
private String dd = "";

 public void methodX()
 {
     getMessageAndTime.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    mm = month.getSelectedItem().toString();
                    dd = day.getSelectedItem().toString();
                    ....
                    ....
                    ....
                }
            });
 }

public void methodY(){
//Now you can access 'mm' and 'dd' here
System.out.println(mm);
}
© www.soinside.com 2019 - 2024. All rights reserved.