Why does my ActionListener only work for one of my buttons?

256 views Asked by At

This is my code:

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

            }
        }
    }
}

When I run it, enter yay into Program Name and exe into Type of file and click both of the OK buttons, I get a new file called exe.txt but no file called yay.txt. Why is this?

1

There are 1 answers

2
Balkrishna Rawool On

Yes. You have definitely done something stupid. And that is there is a mess of curly brackets all over. Remove an end bracket (}) from the end and add it immediately after this code:

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

So it becomes this:

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

That should fix it. Also as a sidenote: 1. Make first letter of your class name capital. (e.g. Plugin). 2. Indent your code for better readibility. 3. You might want to add e.printStackTrace() for debugging in catch part of the exceptions.