2015-10-06 72 views
0

我正在嘗試創建一個工作相關的項目和有一些問題的GUI。添加動作監聽器或者如果語句JPane

我想我的GUI有一個JTextField和三個按鈕。我希望用戶能夠在文本字段中鍵入某個數字,然後根據他們點擊哪個按鈕來執行某些操作。

我遇到的問題是我的ActionListener與JTextField似乎沒有工作。當我測試它時,我得不到任何結果。任何幫助將不勝感激,下面是我的代碼。

package nacha; 

import java.awt.Component; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.BoxLayout; 
import javax.swing.JComboBox; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class Testing 

{ 
    static String code = null; 
    public static void main(String args[]){ 

     int sixBatch1TotalCounter=1; 
     int sixBatch1Total=2; 
     int main = 1000001; 




     final JTextField reasonCode = new JTextField(10); 

     JPanel p = new JPanel(); 


p.add(new JLabel("<html>" + 
       "Entry Detail: "+ 
       "<br>"+main+ 
       "<br>Entry Detail "+sixBatch1TotalCounter+" of "+sixBatch1Total+ 
       "<br><br>Please type 1-21 to apply reason code and addenda record to the entry detail record."+ 
       "<br>To omit displayed entry detail from the return, simply leave the input line blank and press enter."+ 
       "<br><br>Reason Code Descriptions:"+ 
       "<br>R01 - Insufficient Funds"+ 
       "<br>R02 - Account Closed"+ 
       "<br>R03 - No Account"+ 
       "<br>R04 - Invalid Account Number"+ 
       "<br>R05 - Unauthorized Debit to Consumer Account Using Corporate SEC Code"+ 
       "<br>R06 - Returned per ODFI Request"+ 
       "<br>R07 - Auth Revoked by Customer"+ 
       "<br>R08 - Payment Stopped"+ 
       "<br>R09 - Uncollected Funds"+ 
       "<br>R10 - Customer Advises Not Authorized" 
       )); 

     p.add(reasonCode); 

     p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS)); 

     Object[] choices = {"Next","Next Batch","Submit"}; 
     Object defaultChoice = choices[0]; 



     JOptionPane.showOptionDialog(null, p, "Return Builder",JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE,null,choices,defaultChoice); 

     reasonCode.addActionListener(new ActionListener(){ 

      public void actionPerformed(ActionEvent ev){ 

       System.out.println(reasonCode.getText()); 

      } 

     }); 



     } 

    } 

回答

2

你不設置的ActionListener直到showOptionDialog又回來了,當對話框已經關閉。此外,整個事情應該從EventThread運行。

+0

感謝您的評論,但我仍然有點困惑。我明白你對ActionListener的意思,但不明白你的意思。 – jesric1029

+0

爲什麼你需要在文本字段上使用ActionListener,如果你想要做的是採取一些行動取決於哪個按鈕的OptionDialog被按下?並且您不保存showOptionDialog調用的結果,因此您無法確定按下哪個按鈕。 – FredK

+0

你的回答足以讓我朝着正確的方向前進,並且讓它工作。非常感謝! – jesric1029