簡體   English   中英

從 ActionListener 訪問變量並將其傳輸到新方法

[英]Accessing variable from ActionListener and transferring it to new method

我已經做了一點 Java,但即使有時方法和變量的格式也會讓我感到困惑,這取決於具體情況。 我覺得這可能是一個簡單的修復,但出於某種原因我堅持它。 我有一個ActionListener附加到JDialog的按鈕。 當此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);
                    }
                }
            });

只需在此方法的范圍之外聲明您的變量。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM