Wednesday, July 9, 2014

FirstSwingExample in-class

Here is the ExampleForm.Java

package com.spconger.SwingExample;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class ExampleForm {
 
 //declare the form objects
 private JFrame frame;
 private JPanel panel;
 private JLabel lblNumber;
 private JTextField txtNumber;
 private JButton btnSubmit;
 private JLabel lblPrime;
 
 private final int OFFSETX=200;
 private final int OFFSETY=300;
 private final int X=420;
 private final int Y=150;
 
 public ExampleForm(){
  createFrame();
 }
 
 private void createFrame(){
  frame = new JFrame();
  frame.add(createPanel());
  frame.setTitle("Prime Number Calculator");
  frame.setBounds(OFFSETX,OFFSETY,X,Y);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }
 
 private JPanel createPanel(){
  panel = new JPanel();
  panel.setLayout(new GridLayout(2,2,5,5));
  
  lblNumber=new JLabel("Enter an integer between 1 and 41");
  txtNumber=new JTextField();
  btnSubmit=new JButton("Get Prime");
  btnSubmit.addActionListener(new SubmitListener());
  lblPrime = new JLabel();
  
  panel.add(lblNumber);
  panel.add(txtNumber);
  panel.add(btnSubmit);
  panel.add(lblPrime);
  
  return panel;
 }
 
 private class SubmitListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent arg0) {
   try{
    int number = Integer.parseInt(txtNumber.getText());
    if(number > 0 && number < 42){
     int prime = number * number - number + 41;
     lblPrime.setText(Integer.toString(prime));
    }//end if
    else{
     JOptionPane.showMessageDialog
                 (null,"Enter an integer between 1 and 41", "Invalid Number",0);
     txtNumber.setText("");
     txtNumber.grabFocus();
    
    }//end else
   
   }//end try
   catch(NumberFormatException e){
    JOptionPane.showMessageDialog
                 (null,"Not a valid number", "Invalid Number",0);
    txtNumber.setText("");
    txtNumber.grabFocus();
   }//end catch
   
  }
  
 }

}

Here is the Program.java

package com.spconger.SwingExample;

public class Program {

 public static void main(String[] args) {
  ExampleForm ex = new ExampleForm();

 }

}

Here is a picture of the form after pressing the button

No comments:

Post a Comment