为什么我的ActionListener只能用于我的其中一个按钮?

为什么我的ActionListener只能用于我的其中一个按钮?

问题描述:

这是我的代码:为什么我的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

是的。你肯定做了一些愚蠢的事情。这就是所有的大括号。取下末端的末端支架(}),并立即这个代码后添加:

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

所以就变成这样:

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

这应该修复它。 同时作为旁注: 1.制作你的班级名字的首字母大写。 (例如Plugin)。 2.缩进您的代码以获得更好的可读性。 3.您可能需要添加e.printStackTrace()以便调试catch的部分例外情况。

+1

谢谢它确实修复了它。我真的很蠢,再次感谢 – 33CoolyDude33

+0

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