I am doing a java project,I want to handle all the exception in a single class,wherever the exception raises ,I want to handle it in a class can anyone send some sample for this ,
Even it's just one class, you still need to use interface for that. Each interface will have its own listener class which will override all the methods. This is one sample code that you could try to analyze. Hope it's helpful
//variables for data entry controls JTextField textCustName; JTextField textCustCellNo; JTextField textAddress; JTextField textCustAge;
String name, no, add, age;
JButton btnSubmit;
//variables for the layout GridBagLayout gbObject; GridBagConstraints gbc;
public void init() { //initializes the layout variables gbObject = new GridBagLayout(); gbc = new GridBagConstraints(); panelObject = (JPanel)getContentPane(); panelObject.setLayout(gbObject);
setSize(800,200);
//initializes label controls labelCustName = new JLabel("Dealer Name"); labelCustCellNo = new JLabel("Cell Number "); labelCustAddress= new JLabel("Address"); labelCustAge = new JLabel("Age");
//initializes data entry controls textCustName = new JTextField(30); textCustCellNo = new JTextField(15); textCustAge = new JTextField(2); textAddress = new JTextField(45); btnSubmit = new JButton("SUBMIT");
//Add listeners to the controls textCustName.addKeyListener(this); textCustCellNo.addKeyListener(this); textAddress.addKeyListener(this); textCustAge.addKeyListener(this);
// BEGINNING OF KEY LISTENER FUNCTIONS public void keyPressed(KeyEvent e) { Object obj = e.getSource(); if (obj == textCustName) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { String name = textCustName.getText(); if (name.length() == 0) { JOptionPane.showMessageDialog(this,"Name cannot be empty"); //showStatus("cannot be empty"); //return; } else { textCustCellNo.requestFocusInWindow(); } } }
if (obj == textCustCellNo) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { String no = textCustCellNo.getText(); if (no.length() != 10) { JOptionPane.showMessageDialog(this,"Mobile number entered should be of ten digits"); } else { textAddress.requestFocusInWindow(); } } }
if (obj == textAddress) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { textCustAge.requestFocusInWindow(); } }
if (obj == textCustAge) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { int age = Integer.parseInt(textCustAge.getText()); if (age <= 18 || age >= 100) { JOptionPane.showMessageDialog(this,"Wrong Age Input. Please Recheck!"); } else { btnSubmit.requestFocusInWindow(); } } } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) {
//showStatus(" Recently typed characters are : " + e.getKeyChar()); } //END OF KEY LISTENER FUNCTIONS }