【发布时间】:2016-07-04 01:38:41
【问题描述】:
这是我第一次设计 GUI,我相信这可能是一个简单的问题。我试图让程序在使用System.exit(0) 按下取消按钮时关闭,但我不确定将它放在我的代码中的哪个位置。我必须创建一个单独的方法吗?我可以在我的ActionPreformed 方法中实现它吗?
//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.");
}
}
}
【问题讨论】:
标签: java swing user-interface button