【问题标题】:Accessing variable from ActionListener and transferring it to new method从 ActionListener 访问变量并将其传输到新方法
【发布时间】:2020-07-06 18:03:24
【问题描述】:

我已经做了一点Java,但有时方法和变量的格式也会让我感到困惑,这取决于具体情况。我觉得这可能是一个简单的修复,但由于某种原因,我坚持下去。我在 JDialog 的按钮上附加了一个 ActionListener 。当这个 ActionListener 方法被激活时,它会创建一个字符串 dateAndTime ,以及与 Timer 包中的 TimerTask 类相关的几个组件(我正在考虑删除这些以代替 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 swing methods actionlistener


    【解决方案1】:

    只需在此方法范围之外声明变量即可。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多