2015-06-14 23 views
1

這是我的代碼:爲什麼我的ActionListener只能用於我的其中一個按鈕?

import java.io.*; 
import javax.swing.*; 
import java.awt.event.* ; 

class plugin extends JFrame implements ActionListener { 
    JPanel pnl = new JPanel(); 

    public static void main(String args[]) { 
     plugin gui = new plugin(); 
    } 

    JTextField progname = new JTextField("Program Name"); 
    JButton pnameok = new JButton("Ok"); 

    JTextField endtxt = new JTextField("Type of file"); 
    JButton endok = new JButton("Ok"); 

    JButton stop = new JButton("Stop the Server"); 

    public plugin() { 
     super(); 
     add(pnl); 
     pnl.add(stop); 
     pnl.add(progname); 
     pnl.add(pnameok); 

     pnl.add(endtxt); 
     pnl.add(endok); 

     pnameok.addActionListener(this); 
     endok.addActionListener(this); 

     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setVisible(true); 
    } 

    public void actionPerformed(ActionEvent event) { 

     if(event.getSource() == endok) { 
      try { 
       String end = endtxt.getText(); 
       FileWriter endfile = new FileWriter(end + ".txt"); 
      } 
      catch(IOException e) { 
       boolean uselessend = true; 
      } 

      if(event.getSource() == pnameok) { 
       try { 
        String pname = progname.getText(); 
        FileWriter pnamefile = new FileWriter(pname + ".txt"); 
       } 
       catch(IOException e1) { 
        boolean uselesspname = true; 
        try { 
         FileWriter pnamefileuse = new FileWriter("error"); 
        } 
        catch(IOException e2) { 
         boolean completeandutterfail = true; 
        } 
       } 

      } 
     } 
    } 
} 

當我運行它,進入yay到節目名稱和exe到文件的類型,然後單擊兩個OK按鈕,我得到一個新的文件名爲exe.txt但沒有文件名爲yay.txt 。爲什麼是這樣?

+0

您是否嘗試通過在每個for循環中打印某些內容來調試它,以確保在單擊按鈕時它們都被正確執行? – smac89

+0

是的,並且在pnameok的for循環中,它沒有執行那 – 33CoolyDude33

回答

2

是的。你肯定做了一些愚蠢的事情。這就是所有的大括號。取下末端的末端支架(}),並立即這個代碼後添加:

catch(IOException e) { 
    boolean uselessend = true; 
} 

所以就變成這樣:

catch(IOException e) { 
    boolean uselessend = true; 
    } 
} 

這應該修復它。 同時作爲旁註: 1.製作你的班級名字的首字母大寫。 (例如Plugin)。 2.縮進您的代碼以獲得更好的可讀性。 3.您可能需要添加e.printStackTrace()以便調試catch的部分例外情況。

+1

謝謝它確實修復了它。我真的很蠢,再次感謝 – 33CoolyDude33

+0

@ 33CoolyDude33。也許你想接受我的答案,如果它解決了。 –

相關問題