0

This is my first time designing a GUI and I believe this is probably a simple question. I am trying to get the program to close when the cancel button is pressed using System.exit(0) but I am not sure where to put it in my code. Do I have to create a separate method? Can I implement it in my ActionPreformed method?

//importing required packages
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.*;

//implements ActionListener
public class primecalc implements ActionListener{

    public static void main(String[] args) throws Exception {

        //create object instance
        primecalc p= new primecalc();
    }

    private JTextField Calculate,Value;
    private JButton calculateb,cancelb;
    private JLabel l1,l2;
    private JFrame frame;

    public primecalc()
    {
        //Desiging GUI
        Calculate = new JTextField(30);
        Value = new JTextField(30);
        l1 = new JLabel("Prime Number Calculator");
        calculateb = new JButton("Calculate");
        calculateb.addActionListener(this);//button performs specific action
        cancelb = new JButton("Cancel");
        cancelb.addActionListener(this);//button performs specific action

        //layout
        JPanel north = new JPanel(new GridLayout(3,2));
        north.add(new JLabel("Enter a number: "));
        north.add(Calculate);
        north.add(new JLabel("Result: "));
        north.add(Value);
        north.add(calculateb);
        north.add(cancelb);

        //frame
        JFrame frame = new JFrame("Prime Number Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(north,BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event)//buttons action is performed here
    { 
        String input =Calculate.getText();
        int n1;
        boolean Prime;
        try{
            n1=Integer.parseInt(input);
            Prime=true;
            for(int i=2;i<n1;i++){
                if((n1 % i) == 0){
                    Prime=false;
                    break;
                }
            }
            if(n1==1 || n1==0){
                Prime=false;  
            }
            if(Prime){
                Value.setText("This is a prime number.");              
            }else{
                Value.setText("This is not a prime number.");              
            }
        }catch(NumberFormatException nfe){
            Value.setText("The input is invalid, please try again.");
        }
    }
}
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
nbhuiya
  • 39
  • 1
  • 8
  • See if this helps http://stackoverflow.com/questions/8632705/how-to-close-a-gui-when-i-push-a-jbutton – Rykuno Mar 17 '16 at 15:50

5 Answers5

2

You need to check the source of event and then decide what to do.

@Override
public void actionPerformed(ActionEvent event) {
    if (event.getSource() == cancelb) {
        System.exit(0);
    }
    // you continue your code from here

With this approach you need only to test which button have started the event.

josivan
  • 1,963
  • 1
  • 15
  • 26
1
cancelb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
          doSomething()....
          System.Exit(0);
        }
      });
Phil
  • 29
  • 2
1

do this,

@Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("Cancel")){
                System.exit(0);
        }   

    }
Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55
1

Use different anonymous ActionListener for each button

        // Designing GUI
        calculate = new JTextField(30);
        value     = new JTextField(30);

        l1 = new JLabel("Prime Number Calculator");     

        ActionListener calculatebListener = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                     // Paste your code here
                }
        };

        calculateb = new JButton("Calculate");
        calculateb.addActionListener(calculatebListener);


        ActionListener cancelbListener = new ActionListener() {

             @Override
             public void actionPerformed(ActionEvent e) {
                   System.exit(0);
              }
        };

        cancelb = new JButton("Cancel");
        cancelb.addActionListener(cancelbListener);
        ...
RubioRic
  • 2,442
  • 4
  • 28
  • 35
-1

For your pupose I'd suggest to simply add a MouseListener or a MouseAdapter to your button

myButton.addMouseListener(new MouseAdapter() {
     @Override
     public void mousePressed(MouseEvent e) {
        System.exit(0);
     }
  });
Raven
  • 2,951
  • 2
  • 26
  • 42
  • It is not appropriate to use a `MouseListener` on a button for this purpose. Buttons support `ActionListener`s for exactly this purpose. – khelwood Mar 17 '16 at 15:43