jTable_sales_cotation.setTableHeader(null);
Tuesday, December 24, 2013
java JTable resize Table Column
try {
//get table model
DefaultTableModel model = (DefaultTableModel) jTable_sales_cotation.getModel();
model.addRow(new Object[]{
item_code, item_description, quantity, unit, price,
discount, line_total });
jTable_sales_cotation.setAutoResizeMode(jTable_sales_cotation.AUTO_RESIZE_OFF);
jTable_sales_cotation.getColumnModel().getColumn(0).setPreferredWidth(70);
jTable_sales_cotation.getColumnModel().getColumn(1).setPreferredWidth(270);
jTable_sales_cotation.getColumnModel().getColumn(2).setPreferredWidth(50);
jTable_sales_cotation.getColumnModel().getColumn(3).setPreferredWidth(52);
jTable_sales_cotation.getColumnModel().getColumn(4).setPreferredWidth(110);
jTable_sales_cotation.getColumnModel().getColumn(5).setPreferredWidth(78);
jTable_sales_cotation.getColumnModel().getColumn(6).setPreferredWidth(90);
//DB operation
//log.main(query);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error: " + e, "Error in connectivity", JOptionPane.ERROR_MESSAGE);
}
update_total();
// __Update_table();
// __clear();
//get table model
DefaultTableModel model = (DefaultTableModel) jTable_sales_cotation.getModel();
model.addRow(new Object[]{
item_code, item_description, quantity, unit, price,
discount, line_total });
jTable_sales_cotation.setAutoResizeMode(jTable_sales_cotation.AUTO_RESIZE_OFF);
jTable_sales_cotation.getColumnModel().getColumn(0).setPreferredWidth(70);
jTable_sales_cotation.getColumnModel().getColumn(1).setPreferredWidth(270);
jTable_sales_cotation.getColumnModel().getColumn(2).setPreferredWidth(50);
jTable_sales_cotation.getColumnModel().getColumn(3).setPreferredWidth(52);
jTable_sales_cotation.getColumnModel().getColumn(4).setPreferredWidth(110);
jTable_sales_cotation.getColumnModel().getColumn(5).setPreferredWidth(78);
jTable_sales_cotation.getColumnModel().getColumn(6).setPreferredWidth(90);
//DB operation
//log.main(query);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error: " + e, "Error in connectivity", JOptionPane.ERROR_MESSAGE);
}
update_total();
// __Update_table();
// __clear();
java Multiple DB Table Insert Statement and Rollback
try {
//DB OPERATION
//TURN OFF AUTO COMMIT
conn.setAutoCommit(false);
//CREATE DB SAVEPOINT
Savepoint save1 = conn.setSavepoint();
try{
java.sql.Statement pst = conn.createStatement();
pst.executeUpdate("INSERT INTO sales_dcl_orders ("
+ "order_no, trans_type, version, type,"
+ "debtor_no, branch_code, reference, customer_ref,"
+ "comments, ord_date, order_type, ship_via,"
+ "delivery_address, contact_phone, contact_email, deliver_to,"
+ "freight_cost, from_stk_loc, delivery_date, payment_terms,"
+ "total, insert_date,user_name) VALUES "
+ "('"+ max_id + "','" + 32+ "','" + 0 + "','" + 0 + "'"
+ ",'" + cus_id + "','" + branch_id + "','" + reference + "','" + customer_ref + "'"
+ ",'" + comments + "','" + Ord_Date + "','" + Order_Type_id + "','" + Ship_Vaia_Id + "'"
+ ",'" + Delv_Address + "','" + Phone + "','" + "" + "','" + deliver_to + "'"
+ ",'" + shipping_charge + "','" + From_Loc_Id + "','" + val_date + "','" + Payment_tarm_id + "'"
+ ",'" + inv_total + "','" + u.todays_datetime() + "','" + Dashboard.user_id + "')",Statement.RETURN_GENERATED_KEYS);
pst.executeUpdate("INSERT INTO audit_trail ("
+ "type, trans_no, user_id, description,"
+ "fiscal_year, gl_date, type_details ) VALUES "
+ "('"+ 32 + "','" + max_id + "','" + Dashboard.user_id + "','" + "" + "'"
+ ",'" + fiscal_year_id + "','" + u.todays_date() + "','" + "Sales Quotation" + "')",Statement.RETURN_GENERATED_KEYS);
// get details from table and send to DB
int rowcount = jTable_sales_cotation.getRowCount();
String item_code;
String item_desc;
String item_unit;
String item_quentity;
String item_price;
String item_discount;
while(rowcount > 0){
rowcount--;
item_code = jTable_sales_cotation.getModel().getValueAt(rowcount, 0).toString();
item_desc = jTable_sales_cotation.getModel().getValueAt(rowcount, 1).toString();
item_quentity = jTable_sales_cotation.getModel().getValueAt(rowcount, 2).toString();
item_unit = jTable_sales_cotation.getModel().getValueAt(rowcount, 3).toString();
item_price = jTable_sales_cotation.getModel().getValueAt(rowcount, 4).toString();
item_discount = jTable_sales_cotation.getModel().getValueAt(rowcount, 5).toString();
pst.executeUpdate("INSERT INTO sales_dcl_order_details ("
+ "order_no, trans_type, stk_code, description, unit,"
+ "unit_price, quantity, discount_percent, insert_date ) VALUES "
+ "('"+ max_id + "','" + 32+ "','" + item_code + "','" + item_desc + "','" + item_unit + "'"
+ ",'" + item_price + "','" + item_quentity + "','" + item_discount + "','" + u.todays_datetime() + "')",Statement.RETURN_GENERATED_KEYS);
}
//ALL DONE, COMMIT DB CHANGES
conn.commit();
JOptionPane.showMessageDialog(this, "Successful", "Successful", JOptionPane.PLAIN_MESSAGE);
} catch (Exception e) {
pst.close();
conn.rollback(save1);
conn.setAutoCommit(true);
JOptionPane.showMessageDialog(this, "Failed 3" +e, "Error in connectivity", JOptionPane.ERROR_MESSAGE);
return;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e, "Invalid", JOptionPane.ERROR_MESSAGE);
}
//TURN ON AUTO COMMIT
try {
conn.setAutoCommit(true);
} catch (SQLException ex) {
// Logger.getLogger(PurchaseOrder.class.getName()).log(Level.SEVERE, null, ex);
}
}
//DB OPERATION
//TURN OFF AUTO COMMIT
conn.setAutoCommit(false);
//CREATE DB SAVEPOINT
Savepoint save1 = conn.setSavepoint();
try{
java.sql.Statement pst = conn.createStatement();
pst.executeUpdate("INSERT INTO sales_dcl_orders ("
+ "order_no, trans_type, version, type,"
+ "debtor_no, branch_code, reference, customer_ref,"
+ "comments, ord_date, order_type, ship_via,"
+ "delivery_address, contact_phone, contact_email, deliver_to,"
+ "freight_cost, from_stk_loc, delivery_date, payment_terms,"
+ "total, insert_date,user_name) VALUES "
+ "('"+ max_id + "','" + 32+ "','" + 0 + "','" + 0 + "'"
+ ",'" + cus_id + "','" + branch_id + "','" + reference + "','" + customer_ref + "'"
+ ",'" + comments + "','" + Ord_Date + "','" + Order_Type_id + "','" + Ship_Vaia_Id + "'"
+ ",'" + Delv_Address + "','" + Phone + "','" + "" + "','" + deliver_to + "'"
+ ",'" + shipping_charge + "','" + From_Loc_Id + "','" + val_date + "','" + Payment_tarm_id + "'"
+ ",'" + inv_total + "','" + u.todays_datetime() + "','" + Dashboard.user_id + "')",Statement.RETURN_GENERATED_KEYS);
pst.executeUpdate("INSERT INTO audit_trail ("
+ "type, trans_no, user_id, description,"
+ "fiscal_year, gl_date, type_details ) VALUES "
+ "('"+ 32 + "','" + max_id + "','" + Dashboard.user_id + "','" + "" + "'"
+ ",'" + fiscal_year_id + "','" + u.todays_date() + "','" + "Sales Quotation" + "')",Statement.RETURN_GENERATED_KEYS);
// get details from table and send to DB
int rowcount = jTable_sales_cotation.getRowCount();
String item_code;
String item_desc;
String item_unit;
String item_quentity;
String item_price;
String item_discount;
while(rowcount > 0){
rowcount--;
item_code = jTable_sales_cotation.getModel().getValueAt(rowcount, 0).toString();
item_desc = jTable_sales_cotation.getModel().getValueAt(rowcount, 1).toString();
item_quentity = jTable_sales_cotation.getModel().getValueAt(rowcount, 2).toString();
item_unit = jTable_sales_cotation.getModel().getValueAt(rowcount, 3).toString();
item_price = jTable_sales_cotation.getModel().getValueAt(rowcount, 4).toString();
item_discount = jTable_sales_cotation.getModel().getValueAt(rowcount, 5).toString();
pst.executeUpdate("INSERT INTO sales_dcl_order_details ("
+ "order_no, trans_type, stk_code, description, unit,"
+ "unit_price, quantity, discount_percent, insert_date ) VALUES "
+ "('"+ max_id + "','" + 32+ "','" + item_code + "','" + item_desc + "','" + item_unit + "'"
+ ",'" + item_price + "','" + item_quentity + "','" + item_discount + "','" + u.todays_datetime() + "')",Statement.RETURN_GENERATED_KEYS);
}
//ALL DONE, COMMIT DB CHANGES
conn.commit();
JOptionPane.showMessageDialog(this, "Successful", "Successful", JOptionPane.PLAIN_MESSAGE);
} catch (Exception e) {
pst.close();
conn.rollback(save1);
conn.setAutoCommit(true);
JOptionPane.showMessageDialog(this, "Failed 3" +e, "Error in connectivity", JOptionPane.ERROR_MESSAGE);
return;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e, "Invalid", JOptionPane.ERROR_MESSAGE);
}
//TURN ON AUTO COMMIT
try {
conn.setAutoCommit(true);
} catch (SQLException ex) {
// Logger.getLogger(PurchaseOrder.class.getName()).log(Level.SEVERE, null, ex);
}
}
Java Hash Map Set and get Data
Set Hash Map
private TreeMap <String, String> itemMap = new TreeMap<String, String>();
private TreeMap <String, String> itemMap1 = new TreeMap<String, String>();
private void FillCombo_Items(){
//int row = jTable_Roles.getSelectedRow();
// jCombo_Items.removeAllItems();
itemMap.clear();
itemMap1.clear();
String S;
String sql = "Select stock_id,description,units from inventory_dcl_stock_master ORDER BY description ASC";
try {
pst = conn.prepareStatement(sql);
ResultSet rs_item = pst.executeQuery();
jCombo_Items.addItem("");
while(rs_item.next()){
S = rs_item.getString("description");
jCombo_Items.addItem(S);
itemMap.put(rs_item.getString("stock_id"), S);
itemMap1.put(S, rs_item.getString("units"));
}
}catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error in connecitivity " +e);
}
}
Get Data From it
stock_name = (String) jCombo_Items.getSelectedItem();
stock_id = getKeyForValue(stock_name,itemMap);
unit = getValueForKey(stock_name,itemMap1);
private TreeMap <String, String> itemMap = new TreeMap<String, String>();
private TreeMap <String, String> itemMap1 = new TreeMap<String, String>();
private void FillCombo_Items(){
//int row = jTable_Roles.getSelectedRow();
// jCombo_Items.removeAllItems();
itemMap.clear();
itemMap1.clear();
String S;
String sql = "Select stock_id,description,units from inventory_dcl_stock_master ORDER BY description ASC";
try {
pst = conn.prepareStatement(sql);
ResultSet rs_item = pst.executeQuery();
jCombo_Items.addItem("");
while(rs_item.next()){
S = rs_item.getString("description");
jCombo_Items.addItem(S);
itemMap.put(rs_item.getString("stock_id"), S);
itemMap1.put(S, rs_item.getString("units"));
}
}catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error in connecitivity " +e);
}
}
Get Data From it
stock_name = (String) jCombo_Items.getSelectedItem();
stock_id = getKeyForValue(stock_name,itemMap);
unit = getValueForKey(stock_name,itemMap1);
Java View Hashmap Data
Download Gson
https://code.google.com/p/google-gson/
Gson gson = new Gson();
System.out.println(gson.toJson(itemMap1));
Output:
{"17inch VGA Monitor":"ea","32MB VGA Card":"ea","52x CD Drive":"ea","Assembly Labour":"hrs","Black Fluid":"ea","Blue Fluid":"ea","Fluid 2":"ea","MK-Comx":"ea","P4 Business System":"ea","RX-35V":"ea","RX-55V":"ea","Red Fluid":"ea","s o d a":"ea"}
https://code.google.com/p/google-gson/
Gson gson = new Gson();
System.out.println(gson.toJson(itemMap1));
Output:
{"17inch VGA Monitor":"ea","32MB VGA Card":"ea","52x CD Drive":"ea","Assembly Labour":"hrs","Black Fluid":"ea","Blue Fluid":"ea","Fluid 2":"ea","MK-Comx":"ea","P4 Business System":"ea","RX-35V":"ea","RX-55V":"ea","Red Fluid":"ea","s o d a":"ea"}
Sunday, September 15, 2013
Java Xml modify
package Utility;
/**
*
* @author Sakib
*/
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXMLFile {
public static void main(String argv[]) {
try {
String filepath = "c:\\temp\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node company = doc.getFirstChild();
// Get the staff element , it may not working if tag has spaces, or
// whatever weird characters in front...it's better to use
// getElementsByTagName() to get it directly.
// Node staff = company.getFirstChild();
// Get the staff element by tag name directly
Node staff = doc.getElementsByTagName("staff").item(1);
// update staff attribute
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem("id");
nodeAttr.setTextContent("2");
// append a new node to staff
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
staff.appendChild(age);
// loop the staff child node
NodeList list = staff.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
// get the salary element, and update the value
if ("salary".equals(node.getNodeName())) {
node.setTextContent("2000000");
}
//remove firstname
// if ("firstname".equals(node.getNodeName())) {
// staff.removeChild(node);
// }
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
/**
*
* @author Sakib
*/
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXMLFile {
public static void main(String argv[]) {
try {
String filepath = "c:\\temp\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node company = doc.getFirstChild();
// Get the staff element , it may not working if tag has spaces, or
// whatever weird characters in front...it's better to use
// getElementsByTagName() to get it directly.
// Node staff = company.getFirstChild();
// Get the staff element by tag name directly
Node staff = doc.getElementsByTagName("staff").item(1);
// update staff attribute
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem("id");
nodeAttr.setTextContent("2");
// append a new node to staff
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
staff.appendChild(age);
// loop the staff child node
NodeList list = staff.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
// get the salary element, and update the value
if ("salary".equals(node.getNodeName())) {
node.setTextContent("2000000");
}
//remove firstname
// if ("firstname".equals(node.getNodeName())) {
// staff.removeChild(node);
// }
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
Java XML Read
package Utility;
/**
*
* @author Sakib
*/
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bfname) {
System.out.println("First Name : " + new String(ch, start, length));
bfname = false;
}
if (blname) {
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;
}
if (bsalary) {
System.out.println("Salary : " + new String(ch, start, length));
bsalary = false;
}
}
};
saxParser.parse("c:\\temp\\file.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Subscribe to:
Posts (Atom)