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.");
}
}
}