Hi All,

Im fairly new to Java and im currently working my way through a couple of books but im stumped with something.

I want to know, or get an example of how i can add an action to a button which outputs to a screen. I just cant seem to find any examples at all.

I plan to use java to make desktop applications with a local access database.

Any help would be greatly appreciated.

Thanks

Paul

Recommended Answers

All 6 Replies

What you mean by "outputs to a screen"? Something like filling in your form?


Im fairly new to Java

Since you are new to Java, its better if you use Netbeans or JBuilder, you simply have to drag and drop the Swing components and, Database connectivity is also fairly simple.

commented: How are they going to learn how to program if they let the IDE do it for them? -2

I wouldn't call it reasonable advice. There are too many students dependent on their IDE and if somebody force them work on different IDE or from command line they are lost.

Thanks for the replies. Interesting to know theres still more than 1 way to skin a cat.

Im using netbeans.

im after an example of something that gives me an understanding of how clicking a button interacts with an access database to add,edit,delete a record and outputs everything to a simple screen, kinda like how a dos window works.

thanks again for your input, im determined to learn java, i have no problem with the maths side and the uml (2).

Regards

Paul

Thanks for the replies. Interesting to know theres still more than 1 way to skin a cat.

Im using netbeans.

im after an example of something that gives me an understanding of how clicking a button interacts with an access database to add,edit,delete a record and outputs everything to a simple screen, kinda like how a dos window works.

thanks again for your input, im determined to learn java, i have no problem with the maths side and the uml (2).

Regards

Paul

There are lots of ways to skin a cat. Setting up the button, having the button clicking call a function, the database querying, and the displaying the results to a console screen, are all separate, though interwoven tasks. You set up a GUI, you stick a button on it, you add an Action Listener to the button, then you have it do what you want it to do when that button is clicked. You mentioned "console" and "DOS", so I assume "display to the screen" means "display to a console screen", not display to somewhere on the GUI. Below is a sample program that may give you some ideas. It has no database connectivity, instead returning Strings. You'll for sure want to change that. Here's a tutorial on JDBC/database querying.

http://java.sun.com/docs/books/tutorial/jdbc/index.html

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class MyFrame extends JFrame implements ActionListener
{
    JButton button;

    public MyFrame ()
    {
        this.setSize (600, 600);
        button = new JButton ("Push me");
        button.addActionListener(this);
        this.setLayout (new FlowLayout ());
        this.add (button);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible (true);
    }


    public static void main(String[] args)
    {
        new MyFrame ();
    }


    public void actionPerformed(ActionEvent e)
    {
        System.out.println ("Button has been pressed.");
        String addressData[] = DatabaseQuery ();

        for (int i = 0; i < addressData.length; i++)
            System.out.println (addressData[i]);
    }


    public String[] DatabaseQuery ()
    // connect to, query DB here.  You'll deal with ResultSets, not Strings
    {
        String addressData[] = new String[3];
        addressData[0] = "Joe Smith 40 Elm St. Los Angeles, CA";
        addressData[1] = "Jim Jones 50 Main St. Houston, TX";
        addressData[2] = "Ted Allen 60 Spring St. San Jose, CA";
        return addressData;
    }
}

Hope this helps.

package src.maintenance.loyalty;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

import src.maintenance.DBConn.DBConnect;
import src.maintenance.Functions.Message;
import src.maintenance.Functions.MyField;
import src.maintenance.Functions.createINI;
import src.maintenance.ResultTableModel.ResultSetTableModel;
import src.maintenance.core.mainform;


/*
 * 05091987revilogadnul
 * 2009
 * 0557 Applied Ideas
 */


public class City_Municipality extends JInternalFrame{
	//	JPanel
	private JPanel jContentPane = null;
	//	Declare JLabel
	private JLabel JLCountry = null;
	private JLabel JLRegion = null;
	private JLabel JLProvince = null;
	private JLabel JLCity_MunCode = null;
	private JLabel JLCity_MunDesc = null;
	//	Declare JComboBox
	public static JComboBox JC_country = null;
	public static JComboBox JC_region = null;
	public static JComboBox JC_province = null;
	//	Declare TextField
	public static MyField JTCity_MunCode = null;
	public static MyField JTCity_MunDesc = null;
	//Table
	private JScrollPane jScrollPane = null;
	private JTable jTable = null;
	private String defaultQuery =   " SELECT city_municipality,description " +
														" FROM addr_ref " +
														" WHERE brgy_village = ' ' and street = ' ' " +
														"and"+
														"			  country != '' " +
														"and"+
														"			  region != '' " +
														"and"+
														"			  province != '' " +
														"and"+
														"			  city_municipality != '' ";
	private static  ResultSetTableModel tableMain = null;
	// buttons
	public static JButton jbtnadd;
	public static JButton jbtnedit;
	public static JButton jbtnExit;
	//variable
	static int xRecord = 0;
	static int xRecordE = 0;
	static int xrecord = 0;
	private int fileCount = 0;
	private int fileCountE = 0;
	private boolean exist = false;
	private static String Country_Code = null;
	private static String Region_Code = null;
	private static String Province_Code = null;
	
	public City_Municipality(){
		super ("City Municipality Maintenace",//title
				false, //rezisable
				true, //closable
				false, //maximizable
				false); //iconifiable
		this.setName("City Municipality Maintenace");
		try {
			setConnection();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		initialize();
	}// end of method City_Municipality
	
	private void setConnection() throws ClassNotFoundException{
		try	{
			tableMain = new ResultSetTableModel(defaultQuery);
		}
		catch(SQLException sqlE){
			Message.messageInfo("Error log has been created");
			StringWriter traceWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(traceWriter, false);
			sqlE.printStackTrace(printWriter);
			createINI.create("City Municipality Maintenace", "setConnection", traceWriter.toString());      
	        dispose();
		}//end of try catch
	}//end of method setConnection()
	
	private void initialize(){
		this.setSize(370, 430);
		this.setContentPane( getcontentJPanel());
		this.setOpaque(true);
		this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
		this.setClosable(true);
		this.setVisible(true);
		this.addInternalFrameListener(new InternalFrameListener(){
			public void internalFrameActivated(InternalFrameEvent arg0) {
				mainform.tree.setEnabled(false);
				mainform.tree.clearSelection();
			}
			public void internalFrameClosed(InternalFrameEvent arg0) {}
			public void internalFrameClosing(InternalFrameEvent arg0) {
				mainform.tree.setEnabled(true);
			}
			public void internalFrameDeactivated(InternalFrameEvent arg0) {
			}
			public void internalFrameDeiconified(InternalFrameEvent arg0) {}
			public void internalFrameIconified(InternalFrameEvent arg0) {}
			public void internalFrameOpened(InternalFrameEvent arg0) {}
		});
		setTitle("City Municipality Maintenace");
		startup();
		getRecordCountE();
		if	(xRecord != fileCount){
			xRecord++;
		}		
		if	(xRecordE  != fileCountE){
			xRecordE++;
		}
		xrecord = xRecordE;
	}//end of method initialize
	
	private void getRecordCountE() throws NullPointerException{
		try	{
			fileCountE = 0;	
			String query =   " SELECT  count(*) " +
										" FROM addr_ref " +
										" WHERE brgy_village = '' and street = '' " +
										"and"+
										"			  country != '' " +
										"and"+
										"			  region != '' " +
										"and"+
										"			  province != '' " +
										"and"+
										"			  city_municipality != '' " +
										"and"+
										"			  description != '' ";
			Statement stmt = mainform.stat;
			ResultSet rs = stmt.executeQuery(query);
			while(rs.next()){
				fileCountE = rs.getInt(1);
			}
			rs.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}//end of try catch
	}//end of method getRecordCountE()
	
	private JPanel getcontentJPanel(){
		if (jContentPane == null){
			//label for country
			JLCountry = new JLabel();
			JLCountry.setHorizontalAlignment(SwingConstants.LEFT);
			JLCountry.setFont(new Font("Dialog", Font.BOLD, 12));
			JLCountry.setText("Country");
			JLCountry.setLocation(new Point(20, 230));
			JLCountry.setSize(new Dimension(91, 20));
			//label for region
			JLRegion = new JLabel();
			JLRegion.setHorizontalAlignment(SwingConstants.LEFT);
			JLRegion.setFont(new Font("Dialog", Font.BOLD, 12));
			JLRegion.setText("Region");
			JLRegion.setLocation(new Point(20, 260));
			JLRegion.setSize(new Dimension(91, 20));
			//label for province
			JLProvince = new JLabel();
			JLProvince.setHorizontalAlignment(SwingConstants.LEFT);
			JLProvince.setFont(new Font("Dialog", Font.BOLD, 12));
			JLProvince.setText("Province");
			JLProvince.setLocation(new Point(20, 290));
			JLProvince.setSize(new Dimension(91, 20));
			//label for city municipality code
			JLCity_MunCode = new JLabel();
			JLCity_MunCode.setHorizontalAlignment(SwingConstants.LEFT);
			JLCity_MunCode.setFont(new Font("Dialog", Font.BOLD, 12));
			JLCity_MunCode.setText("City Municipality Code");
			JLCity_MunCode.setLocation(new Point(20, 320));
			JLCity_MunCode.setSize(new Dimension(150, 20));
		    //label for description
			JLCity_MunDesc = new JLabel();
			JLCity_MunDesc.setHorizontalAlignment(SwingConstants.LEFT);
			JLCity_MunDesc.setFont(new Font("Dialog", Font.BOLD, 12));
			JLCity_MunDesc.setText("Code Description");
			JLCity_MunDesc.setLocation(new Point(20, 350));
			JLCity_MunDesc.setSize(new Dimension(100, 20));
		}// end of if
		jContentPane = new JPanel();
		jContentPane.setLayout(null);
		//Jlabel
		jContentPane.add(JLCountry,null);
		jContentPane.add(JLRegion,null);
		jContentPane.add(JLProvince,null);
		jContentPane.add(JLCity_MunCode,null);
		jContentPane.add(JLCity_MunDesc,null);
		//JComboBox
		jContentPane.add(getJC_country(),null);
		jContentPane.add(getJC_region(),null);
		jContentPane.add(getJC_province(),null);
		// Text Field
		jContentPane.add(getJTCity_MunCode(),null);
		jContentPane.add( getJTCity_MunDesc(),null);
		//Table
		jContentPane.add(getJScrollPane(), null);
		//Button
		jContentPane.add(getjAdd(),null);
		jContentPane.add(getjEdit(),null);
		jContentPane.add(getjExit(),null);
		return jContentPane;
	}// end of method getcontentJPanel()
	
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new Rectangle(20, 10, 320, 150));
			jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			jScrollPane.setViewportView(getJTable());
			jScrollPane.setVisible(true);
		}//end of if
		return jScrollPane;
	}//end of method getJScrollPane()
	
	private JTable getJTable() {
		if (jTable == null) {
			jTable = new JTable(tableMain){

				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				public boolean isCellEditable(int irows, int icols){
					return false;
				}
			};
			
			TableCellRenderer renderer = new Renderer();
			jTable.setDefaultRenderer(Object.class,renderer);
			
			jTable.setSelectionMode(0);
			jTable.getTableHeader().setResizingAllowed(true);
			jTable.getTableHeader().setMaximumSize(new Dimension(23,56));
			jTable.setPreferredScrollableViewportSize(new Dimension(690,300));
			jTable.getTableHeader().setReorderingAllowed(false);
			
			reload();
		}// end of if

		return jTable;
	}//end of method getJTable()
	
	private void reload(){
		try {
			jTable.getColumnModel().getColumn(0).setMaxWidth(0);
			jTable.getColumnModel().getColumn(0).setMinWidth(0);
			jTable.getColumnModel().getColumn(1).setMaxWidth(0);
			jTable.getColumnModel().getColumn(1).setMinWidth(0);
			jTable.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(82);
			jTable.getTableHeader().getColumnModel().getColumn(0).setMinWidth(82);
			jTable.getTableHeader().getColumnModel().getColumn(1).setMaxWidth(220);
			jTable.getTableHeader().getColumnModel().getColumn(1).setMinWidth(220);
			jTable.getColumnModel().getColumn(0).setHeaderValue("Code");
			jTable.getColumnModel().getColumn(1).setHeaderValue("Description");
		} catch (Exception e) {
			e.printStackTrace();
		}//end of try catch
	}//end of method reload
	
	private class Renderer extends DefaultTableCellRenderer{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
		{
			super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			if (column == 1)setHorizontalAlignment(LEFT);
			if (column == 2)setHorizontalAlignment(LEFT);
			setBorder(BorderFactory.createLineBorder(getBackground(), 1));
			return this;
		}// end of method getTableCellRendererComponen
	}//end of class Renderer extends DefaultTableCellRenderer
	
	private JComboBox getJC_country(){
		if(JC_country== null){
			JC_country = new JComboBox();
			JC_country.setSize(new Dimension(260, 20));
			JC_country.setLocation(new Point(80, 230));
			JC_country.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					try{						
						if (JC_country.getSelectedItem().toString().equalsIgnoreCase("(Choose)") == true){
							JC_country.removeAllItems();
							queryCountry();
						}//end of if
						if (JC_country.getSelectedItem().toString().equalsIgnoreCase("(Choose)") == true){							
							Country_Code = "Nothing";
							JC_region.removeAllItems();
							queryRegion();
							JC_region.setSelectedIndex(0);
							JC_province.setSelectedIndex(0);
						}//end of if
						Country_Code = JC_country.getSelectedItem().toString().substring(0, JC_country.getSelectedItem().toString().indexOf("-"));
						String Filter_By_Code = "select city_municipality,description from addr_ref  " +
																"where  country = '"+Country_Code +"'" +
																"and"+
																"			  region != '' " +
																"and"+
																"			  province != '' " +
																"and"+
																"			  city_municipality != '' "+
																"and"+
																"			  brgy_village = '' " +
																"and"+
																"			  street = '' ";
						try{
							tableMain.setQuery(Filter_By_Code);
						}catch(Exception exp){
						}//end of try catch
							JC_region.removeAllItems();
							queryRegion();						
							JC_region.setSelectedIndex(0);
							JC_province.setSelectedIndex(0);
					}catch(Exception e){
					}//end of try catch					
				}// end of actionPerformed
			});
		}//end of JC_country.addActionListener(new ActionListener(){	
		return JC_country;
	}//end of method getJC_country()
	
	private JComboBox getJC_region(){
		if(JC_region== null){
			JC_region = new JComboBox();
			JC_region.setSize(new Dimension(260, 20));
			JC_region.setLocation(new Point(80, 260));
			JC_region.addItem("(Choose)");
			JC_region.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					try{
						if (JC_region.getSelectedItem().toString().equalsIgnoreCase("(Choose)") == true){
							Region_Code = "Nothing";
							JC_province.removeAllItems();
							queryProvince();
							JC_province.setSelectedIndex(0);
						}//end of if
						Region_Code = JC_region.getSelectedItem().toString().substring(0, JC_region.getSelectedItem().toString().indexOf("-"));
						String Filter_By_Code = "select city_municipality,description from addr_ref  " +
																"where  country = '"+Country_Code +"'" +
																"and"+
																"			  region = '"+Region_Code +"'" +
																"and"+
																"			  province != '' " +
																"and"+
																"			  city_municipality != '' "+
																"and"+
																"			  brgy_village = '' " +
																"and"+
																"			  street = '' ";
						try{
							tableMain.setQuery(Filter_By_Code);
						}catch(Exception exp){
						}//end of try catch
							JC_province.removeAllItems();
							queryProvince();
							JC_province.setSelectedIndex(0);
					}catch(Exception exp){
					}//end of try catch
				}
			});
		}	
		return JC_region;
	}
	
	private JComboBox getJC_province(){
		if(JC_province== null){
			JC_province = new JComboBox();
			JC_province.setSize(new Dimension(260, 20));
			JC_province.setLocation(new Point(80, 290));
			JC_province.addItem("(Choose)");
			JC_province.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent arg0) {
					try{
						Province_Code = JC_province.getSelectedItem().toString().substring(0, JC_province.getSelectedItem().toString().indexOf("-"));						
						String Filter_By_Code = "select city_municipality,description from addr_ref  " +
																"where  country = '"+Country_Code +"'" +
																"and"+
																"			  region = '"+Region_Code +"'" +
																"and"+
																"			  province = '"+Province_Code +"'" +
																"and"+
																"			  city_municipality != '' "+
																"and"+
																"			  brgy_village = '' " +
																"and"+
																"			  street = '' ";
					try{
						tableMain.setQuery(Filter_By_Code);
					}catch(Exception exp){}
					}catch(Exception exp){}
				}
			});
		}	
		return JC_province;
	}
	
	private MyField getJTCity_MunCode(){
		if (JTCity_MunCode== null){
			JTCity_MunCode = new MyField(true,5);
//			JTCity_MunCode = new MyField(true,6);
			JTCity_MunCode.setLocation(new Point(160, 320));
			JTCity_MunCode.setSize(new Dimension(60, 20));
			JTCity_MunCode.setCapital(true);
			JTCity_MunCode.addKeyListener(new KeyListener() {
				public void keyPressed(KeyEvent e) {
					InputMap IMP = JTCity_MunCode.getInputMap(JTCity_MunCode.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
                    KeyStroke ent = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
         		    IMP.put(ent, "none");
					if	(e.getKeyCode() == 10){
						try{
	         				  if (jbtnadd.getText().toString().equalsIgnoreCase("Save") == true){
	         					  if (JTCity_MunCode.getText().toString().length() < 2){
	         						  JTCity_MunCode.setText("0"+JTCity_MunCode.getText().toString().trim());
	         					  }
	         					 queryexist();//check if the record is already exist or not
	         					if (exist == true){
		         					   Message.messageInfo("Record Already Exist");
			         				   JTCity_MunCode.grabFocus();   
	         					}else{
	         						JTCity_MunDesc.grabFocus();
	         					}
	         				  }else{
	         					  JTCity_MunDesc.grabFocus();
	         				  }
						}catch(Exception excp){}
					}//end of if
				}//end of keyPressed

				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub
					
				}

				public void keyTyped(KeyEvent arg0) {
					// TODO Auto-generated method stub
					
				}
		});
			JTCity_MunCode.addFocusListener(new FocusListener() {
				public void focusGained(FocusEvent arg0) {
				}
				public void focusLost(FocusEvent arg0) {
					try{
       				  if (jbtnadd.getText().toString().equalsIgnoreCase("Save") == true){
       					  if (JTCity_MunCode.getText().toString().length() < 2){
       						  JTCity_MunCode.setText("0"+JTCity_MunCode.getText().toString().trim());
       					  }
       					 queryexist();//check if the record is already exist or not
       					if (exist == true){
	         					   Message.messageInfo("Record Already Exist");
		         				   JTCity_MunCode.grabFocus();   
       					}else{
       						JTCity_MunDesc.grabFocus();
       					}
       				  }else{
       					  JTCity_MunDesc.grabFocus();
       				  }
					}catch(Exception excp){}
				}
			});
		}
		return JTCity_MunCode;
	}
	
	private MyField getJTCity_MunDesc(){
		if (JTCity_MunDesc == null){
			JTCity_MunDesc = new MyField(true,50);
			JTCity_MunDesc.setLocation(new Point(130, 350));
			JTCity_MunDesc.setSize(new Dimension(210, 20));
			JTCity_MunDesc.addKeyListener(new KeyListener() {
				public void keyPressed(KeyEvent e) {
				
				}

				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub
					
				}

				public void keyTyped(KeyEvent arg0) {
					// TODO Auto-generated method stub
					
				}
		});
		}
		return JTCity_MunDesc;
	}
	
	private JButton getjAdd() {
		if (jbtnadd == null) {
			jbtnadd = new JButton();
			jbtnadd.setText("Add");
			jbtnadd.setBounds(new Rectangle(30, 170, 90, 25));
			jbtnadd.setMnemonic('A');
			jbtnadd.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if(jbtnadd.getText().toString().equalsIgnoreCase("Add") == true){
						jbtnadd.setMnemonic('A');
						try{			
							String Filter_By_Code = "select city_municipality,description from addr_ref  " +
																	"where  country = '"+Country_Code +"'" +
																	"and"+
																	"			  region = '"+Region_Code +"'" +
																	"and"+
																	"			  province = '"+Province_Code +"'" +
																	"and"+
																	"			  city_municipality != '' "+
																	"and"+
																	"			  brgy_village = '' " +
																	"and"+
																	"			  street = '' ";
						try{
							tableMain.setQuery(Filter_By_Code);
						}catch(Exception exp){}
						}catch(Exception exp){}
						Enabled();//enable all components 	
					}else if (jbtnadd.getText().toString().equalsIgnoreCase("Save") == true){
						jbtnadd.setMnemonic('S');
						String insert = DBConnect.Insert("addr_ref",
									"country,region,province,city_municipality,description",
								 "'"+ DBConnect.clean(Country_Code)+"', "  +
								 "'"+ DBConnect.clean(Region_Code)+"', "  +
								 "'"+ DBConnect.clean(Province_Code)+"', "  +
								 "'"+ DBConnect.clean(JTCity_MunCode.getText().toString().trim())+"', "  +
								 "'"+ DBConnect.clean(JTCity_MunDesc.getText().toString().trim())+"'");
						if(JC_country.getSelectedItem().toString().equalsIgnoreCase("(Choose)")){
							Message.messageWarning("Please Choose Country");
							JC_country.grabFocus();
						}else if(JC_region.getSelectedItem().toString().equalsIgnoreCase("(Choose)")){
							Message.messageWarning("Please Choose Region");
							JC_region.grabFocus();
						}else if(JC_province.getSelectedItem().toString().equalsIgnoreCase("(Choose)")){
							Message.messageWarning("Please Choose Province");
							JC_province.grabFocus();
						}else if(JTCity_MunCode.getText().length()==0){
							Message.messageWarning("Please Enter Code");
							JTCity_MunCode.grabFocus();
						}else if(JTCity_MunDesc.getText().length()==0){
							Message.messageWarning("Please Enter Description");
							JTCity_MunDesc.grabFocus();
						}else{
							try{
								queryexist();//check if the record is already exist or not
								if (exist == true){
									Message.messageInfo(null,"Record Already Exist");
									JTCity_MunCode.grabFocus();
								}else{
									Statement stmt = mainform.dbConn.getConnection().createStatement();
									stmt.execute(DBConnect.beginTransaction());
									try{
										tableMain.setInsert(insert);
										tableMain.setQuery(defaultQuery);
										reload();
									}catch(SQLException sqle){
										Message.messageInfo(null,"Record Already Exist");
										JTCity_MunCode.grabFocus();
									}
									JOptionPane.showMessageDialog(null, "Record was successfully saved");
//									startup();
									startupAfterSaving();
									stmt.execute(DBConnect.commitTransaction());
									stmt.close();
								}
							}catch(Exception excp){}
						}
					}else if(jbtnadd.getText().toString().equalsIgnoreCase("Update") == true){
						try{
							jbtnadd.setMnemonic('U');
							String update = DBConnect.Update("addr_ref",
									" description = '"+DBConnect.clean(JTCity_MunDesc.getText().toString().trim())+"' ",
									" country = '"+DBConnect.clean(Country_Code)+"' and" +
									" region = '"+DBConnect.clean(Region_Code)+"' and" +
									" province = '"+DBConnect.clean(Province_Code)+"' and" +
									" city_municipality = '"+DBConnect.clean(JTCity_MunCode.getText().toString().trim())+"'" );
							if(JTCity_MunDesc.getText().length() == 0){
								Message.messageWarning("Please Enter Description");
								JTCity_MunDesc.grabFocus();
							}else{
								try{
									Statement stmt = mainform.dbConn.getConnection().createStatement();
									stmt.execute(DBConnect.beginTransaction());
									try {
										tableMain.setInsert(update);
									} catch (IllegalStateException e2) {
									} catch (SQLException e2) {
									}
									try {
										tableMain.setQuery(defaultQuery);
									} catch (IllegalStateException e2) {
									} catch (SQLException e2) {
									}
									reload();
									JOptionPane.showMessageDialog(null, "Record was successfully updated");
									try{
//									startup();
										startupAfterSaving();
									}catch (NullPointerException ill) {	}
									stmt.execute(DBConnect.commitTransaction());
									stmt.close();
								}catch(Exception excp){}
							}
						}catch(Exception excp){}
					}
				}
			});
		}
		return jbtnadd;
	}
	
	private JButton getjEdit() {
		if (jbtnedit == null) {
			jbtnedit = new JButton();
			jbtnedit.setText("Edit");
			jbtnedit.setBounds(new Rectangle(130, 170, 90, 25));
			jbtnedit.setMnemonic('E');
			jbtnedit.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					 if(jbtnedit.getText().toString().equalsIgnoreCase("Edit") == true){
						 try{
							 mainform.desktop.add(new EditCityMunicipality());
						 }catch(Exception excp){}
					 }else if(jbtnedit.getText().toString().equalsIgnoreCase("Delete") == true){
						 jbtnedit.setMnemonic('D');
						 try{
								int setDialog = Message.messageYesNo("Are you sure you want to delete this record ?");
								if(JOptionPane.YES_OPTION == setDialog){
									String del = DBConnect.delete("addr_ref",
											" country = '"+DBConnect.clean(Country_Code)+"' and" +
											" region = '"+DBConnect.clean(Region_Code)+"' and" +
											" province = '"+DBConnect.clean(Province_Code)+"' and" +
											" city_municipality = '"+DBConnect.clean(JTCity_MunCode.getText().toString().trim())+"'" );
									try{
										Statement stmt = mainform.dbConn.getConnection().createStatement();
										stmt.execute(DBConnect.beginTransaction());
										try {
											tableMain.setInsert(del);
										} catch (IllegalStateException e2) {
										} catch (SQLException e2) {
										}
										try {
											tableMain.setQuery(defaultQuery);
										} catch (IllegalStateException e2) {
										} catch (SQLException e2) {
										}
										reload();
										JOptionPane.showMessageDialog(null, "Record was successfully Deleted");
										try{
											startup();
											}catch (NullPointerException ill) {}
											stmt.execute(DBConnect.commitTransaction());
											stmt.close();
									}catch (Exception exp) {}
								}
						 }catch(Exception excp){}
					 }
				}
			});
		}
		return jbtnedit;
	}
	
	private JButton getjExit() {
		if (jbtnExit == null) {
			jbtnExit = new JButton();
			jbtnExit.setText("Cancel");
			jbtnExit.setBounds(new Rectangle(230, 170, 90, 25));
			jbtnExit.setMnemonic('C');
			jbtnExit.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if(jbtnExit.getText().toString().equalsIgnoreCase("Cancel") == true){
						try{
							jbtnExit.setMnemonic('C');
							tableMain.setQuery(defaultQuery);
							startup();
						}catch(IllegalArgumentException ill){} catch (IllegalStateException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (SQLException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}
			});
		}
		return jbtnExit;
	}
	
	private static void queryCountry(){
		JC_country.addItem("(Choose)");	
		try {
			String query  = DBConnect.Select("addr_ref", "country, description",
																	"region = ''", "country");
			Statement stmt = DBConnect.getConnection().createStatement();
			ResultSet rs = stmt.executeQuery(query);
			while	(rs.next()){
				 JC_country.addItem(rs.getString(1)+"-"+rs.getString(2));
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private static void queryRegion(){
		JC_region.addItem("(Choose)");
		try {
			String query  = DBConnect.Select("addr_ref", "region, description",
																	"country ='"+Country_Code +"'" +
																	" and region != '' " +
																	"and province = ''", "region");
			Statement stmt = DBConnect.getConnection().createStatement();
			ResultSet rs = stmt.executeQuery(query);
			
			while	(rs.next()){
				 JC_region.addItem(rs.getString(1)+"-"+rs.getString(2));
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private static void queryProvince(){
		JC_province.addItem("(Choose)");
		try {
			String query  = DBConnect.Select("addr_ref", "province, description", 
																	"country ='"+Country_Code +"'" +
																	" and region = '"+Region_Code+"'" +
																	" and province != '' " +
																	"and city_municipality = ''", "province");
			Statement stmt = DBConnect.getConnection().createStatement();
			ResultSet rs = stmt.executeQuery(query);
			while	(rs.next()){
				JC_province.addItem(rs.getString(1)+"-"+rs.getString(2));
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void queryexist(){
		try	{
			String Filter_By_Code = "select city_municipality,description from addr_ref  " +
													"where  country = '"+Country_Code +"'" +
													"and"+
													"			  region = '"+Region_Code +"'" +
													"and"+
													"			  province = '"+Province_Code +"'" +
													"and"+
													"			  city_municipality = '"+JTCity_MunCode.getText().toString().trim()+"'" +
													"and"+
													"			  brgy_village = '' " +
													"and"+
													"			  street = '' ";
			Statement stmt = DBConnect.getConnection().createStatement();
			ResultSet rs = stmt.executeQuery(Filter_By_Code);
			if(rs.last() == false){
				exist = false;
			}else{
				exist = true;
			}
			rs.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	static void getRecordE(){
		try{
			String query = "   SELECT  " +
							" country, region," +
							" province, city_municipality, description" +
							" FROM addr_ref " +
							" WHERE brgy_village = '' and street = '' " +
							" AND"+
							"			  country != '' " +
							" AND"+
							"			  region != '' " +
							" AND"+
							"			  province != '' " +
							" AND"+
							"			  city_municipality != '' ";
			Statement stmt = DBConnect.getConnection().createStatement();
			ResultSet rs;
			rs = mainform.stat.executeQuery(query);
			rs.next();
			rs.absolute(xRecordE);
			setFieldsE(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4),rs.getString(5));
			rs.close();
			stmt.close();	
		}catch (Exception e) {
		}
	}
		
	private static void setFieldsE(String country, String region, String province, String city, String desc){
		try{
			JC_country.setSelectedItem(queryCountry_Code_For_Editting(country));
			JC_region.setSelectedItem(queryRegion_Code_For_Editting(region));
			JC_province.setSelectedItem(queryProvince_Code_For_Editting(province));
			JTCity_MunCode.setText(city);
			JTCity_MunDesc.setText(desc);
		}catch (Exception e) {
		}
	}
	
	private void startup(){
		queryCountry();
		jbtnadd.setText("Add");
		jbtnadd.setMnemonic('A');
		jbtnedit.setText("Edit");
		jbtnedit.setMnemonic('E');
		jbtnadd.setEnabled(true);
		jbtnedit.setEnabled(true);
		jbtnExit.setEnabled(true);
		JC_country.setSelectedIndex(0);
		JC_region.setSelectedIndex(0);
		JC_province.setSelectedIndex(0);
		JC_country.setEnabled(false);
		JC_region.setEnabled(false);
		JC_province.setEnabled(false);
		JTCity_MunCode.setText("");
		JTCity_MunDesc.setText("");
		JTCity_MunCode.setEnabled(false);
		JTCity_MunDesc.setEnabled(false);
	}
	
	private void startupAfterSaving(){
//		queryCountry();
		jbtnadd.setText("Add");
		jbtnadd.setMnemonic('A');
		jbtnedit.setText("Edit");
		jbtnedit.setMnemonic('E');
		jbtnadd.setEnabled(true);
		jbtnedit.setEnabled(true);
		jbtnExit.setEnabled(true);
//		JC_country.setSelectedIndex(0);
//		JC_region.setSelectedIndex(0);
//		JC_province.setSelectedIndex(0);
		JC_country.setEnabled(false);
		JC_region.setEnabled(false);
		JC_province.setEnabled(false);
		JTCity_MunCode.setText("");
		JTCity_MunDesc.setText("");
		JTCity_MunCode.setEnabled(false);
		JTCity_MunDesc.setEnabled(false);
	}
	
	private void Enabled(){
		jbtnadd.setText("Save");
		jbtnadd.setMnemonic('S');
		jbtnedit.setEnabled(false);
		jbtnExit.setText("Cancel");
		JC_country.setEnabled(true);
		JC_region.setEnabled(true);
		JC_province.setEnabled(true);
		JTCity_MunCode.setEnabled(true);
		JTCity_MunDesc.setEnabled(true);
		JTCity_MunCode.setText("");
		JTCity_MunDesc.setText("");
	}
	
	private static String queryCountry_Code_For_Editting(String CountryCode ){
		String County_code_desc = null;
		String query  = DBConnect.Select("addr_ref", "country, description",
																"country ='"+CountryCode+"'" +
																" and region = ''", "country");
		try	{
		Statement stmt = DBConnect.getConnection().createStatement();
		ResultSet rs = stmt.executeQuery(query);
			if (rs.next()){
				County_code_desc = rs.getString(1)+"-"+rs.getString(2);
			}
			stmt.execute(DBConnect.commitTransaction());
			stmt.close();
			rs.close();
		}
		catch(Exception e1){
			System.out.println(e1.getMessage());
			Message.messageError("Insufficient Data!");
		}
		return County_code_desc;
	}
	
	private static String queryRegion_Code_For_Editting(String RegionCode ){
		String Region_code_desc = null;
		String query  = DBConnect.Select("addr_ref", "region, description", 
																"country ='"+Country_Code +"'" +
																" and region = '"+RegionCode +"'" +
																" and province = ''", "region");
		try	{
		Statement stmt = DBConnect.getConnection().createStatement();
		ResultSet rs = stmt.executeQuery(query);
			if (rs.next()){
				Region_code_desc = rs.getString(1)+"-"+rs.getString(2);
			}
			stmt.execute(DBConnect.commitTransaction());
			stmt.close();
			rs.close();
		}
		catch(Exception e1){
			System.out.println(e1.getMessage());
			Message.messageError("Insufficient Data!");
		}
		return Region_code_desc;
	}
	
	private static String queryProvince_Code_For_Editting(String ProvinceCode ){
		String Province_code_desc = null;
		String query  = DBConnect.Select("addr_ref", "province, description",
																"country ='"+Country_Code +"'" +
																" and region = '"+Region_Code+"'" +
																" and province = '"+ProvinceCode+"'" +
																" and city_municipality = ''", "province");
		try	{
		Statement stmt = DBConnect.getConnection().createStatement();
		ResultSet rs = stmt.executeQuery(query);
			if (rs.next()){
				Province_code_desc = rs.getString(1)+"-"+rs.getString(2);
			}
			stmt.execute(DBConnect.commitTransaction());
			stmt.close();
			rs.close();
		}
		catch(Exception e1){
			System.out.println(e1.getMessage());
			Message.messageError("Insufficient Data!");
		}
		return Province_code_desc;
	}
}//end of class

/*
 * 05091987revilogadnul 
 * 2009
 * Applied Ideas
 * Maintenance for City Municipality
 */
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.