Problem with SimpleDateFormat

Hi all,
I would like to parse a time (00:00:00) in String format into a Date obj. I am using the following code to achieve it. however, the result come out is not what i expect.
   String fromTimeStr = "00:00:00";
   TimeZone sg = TimeZone.getTimeZone("Asia/Singapore");
   System.out.println("Timezone "+sg);
   SimpleDateFormat DF = new SimpleDateFormat("HH:mm:ss");
   DF.setTimeZone(sg);
   Date time = DF.parse(fromTimeStr);
   System.out.println("DAte time"+ time);the output is as followed:
Timezone sun.util.calendar.ZoneInfo[id="Asia/Singapore",offset=28800000,dstSavings=0,useDaylight=false,transitions=8,lastRule=null]
DAte timeThu Jan 01 00:30:00 GMT+08:00 1970
From what i know, the timezone of Singapore is fallen within the GMT+8 zone; thus the result should be Jan 01 00:00:00 GMT+08:00 1970
My system timezone is "Kuala Lumpur\Singapore GMT+8".
Could someone enlighten me what there is 30 minutes extra from the output.
Thanks

jnaish wrote:
This is basically what I'm doing:
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatError
     private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
     private Date dateOfBirth;
     public static void main(String[] args)
          DateFormatError x = new DateFormatError();
          x.run();
     public void run()
          String dob = "10/06/1989";
          try
               dateOfBirth = sdf.parse(dob);
          catch (Exception e)
          sdf.format(dateOfBirth);
          System.out.println(dateOfBirth.toString());
}Edited by: jnaish on Feb 4, 2009 12:07 PMHey jnaish, thanks for the SSCCE, but your problem is probably already resolved after phdk's post. Just a small side note: never "swallow exceptions". Never ever! To "swallow an exception" is this:
try {
  // something that may throw an exception
} catch(AnException e) {
  // do nothing with it: ie, swallow it
}because whenever something goes wrong, you will not notice it since nothing is even printed to the screen: this makes debugging your code very hard! Always at least print the stack trace:
try {
  // something that may throw an exception
} catch(AnException e) {
  e.printStackTrace();
}so you will see some helpful message on your screen when something goes wrong.
Good luck!

Similar Messages

  • Problem with SimpleDateFormat.parse()

    Hello
    I have a problem with the parse-function in SimpleDateFormat.
    When i try to parse the date Fri Jul 15 17:23:41 2005 with this pattern EEE MMM d HH:mm:ss yyyy i get the exception java.text.ParseException: Unparseable date: "Fri Jul 15 17:23:41 2005".
    This is my code:
    SimpleDateFormat df=new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
    try {
      df.parse(strDate);
    } catch (ParseException e) {
      e.printStackTrace();
    }Can someone explain me what i did wrong?
    Thanks
    Matthias

    Since your name is "Matthias" it is possible that your locale is one that does not use the English language. If that is the case then your problem is that "Fri" or "Jul" are not correct abbreviations in your language.
    Easiest way to test this idea is to format a date (such as now) using that SimpleDateFormat object and see what the output looks like.

  • Strange problem with SimpleDateFormat.parse method

    I got something strange with this method.
    String pattern = "yyyy/MM/dd";
    String mydate = "2007/00/10";
    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    Date newdate = formatter.parse(mydate);
    I get "2006/12/10"
    is this correct.

    dongyisu wrote:
    and there no exception get thrown outYes it does. I ran this:
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class DateFormatTest
       public static final String DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
       public static void main(String[] args)
          DateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
          formatter.setLenient(false);
          for (int i = 0; i < args.length; ++i)
             try
                Date date = formatter.parse(args);
    System.out.println("input: " + args[i] + " date: " + date);
    catch (ParseException e)
    System.err.println(args[i] + " is not a valid date");
    and got this when I input "2007/00/10":
    com.intellij.rt.execution.application.AppMain DateFormatTest 2007/00/10
    2007/00/10 is not a valid date
    Process finished with exit code 0%

  • New problems with simpledateformat

    sorry guys to my previous post i had solved the issue of formatting my date format..
    but i have a new problem now is that when i enter the 13 mnth 2006 simpledateformat auto helped me rectify to jan of 2007.. and i look through the simpledateformat class it does not have any methods to help me check the validity of the date i am inputting.. is there any other class i have to use to check the validity??

    hmm SimpleDateFormat doesn't have a set lenient
    method only calendar has that...Scroll down some more.

  • Problem with SimpleDateFormat (CommandLine vs WebApp)

    Hello Friends,
    I have a strange problem. Not sure what is the mistake from my side. I have simple class that returns formatted date based on TimeZone. It gives me different result if run on command line vs when used in web app. Below is the code & other information.
    import java.util.*;
    import java.text.*;
    public class Test {
         public static String getDateFormatted(String tZone) {
              DateFormat dfm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss z");
              dfm.setTimeZone(TimeZone.getTimeZone(tZone));
              return dfm.format(new Date());     
         public static void main(String ar[]) {
              System.out.println(getDateFormatted(ar[0]));
    Output From Command Prompt
    java Test PST
    06-October-2008 20:37:01 PDT
    Output From webapp running on Weblogic Server Version 10.0
    06-October-2008 23:37:04 GMT-04:00
    Java version from my command prompt
    java version "1.6.0_06"
    Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
    Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode, sharing)
    To confirm if this problem is due to JRockit that is used as default for Weblogic, I changed Java Home in setDomainEnv.cmd to Sun JDK. But still no luck.
    set BEA_JAVA_HOME=C:\bea\jrockit_150_11
    set SUN_JAVA_HOME=C:\bea\jdk150_11
    if "%JAVA_VENDOR%"=="BEA" (
         set JAVA_HOME=%SUN_JAVA_HOME%
    ) else (
         if "%JAVA_VENDOR%"=="Sun" (
              set JAVA_HOME=%SUN_JAVA_HOME%
         ) else (
              set JAVA_VENDOR=Sun
              set JAVA_HOME=C:\bea\jdk150_11
    Thanks & Appreciate any suggestions

    how are you getting the tZone in web application?
    are you taking it from the request?
    in that case the timezone will be according to the settings in the browser.

  • Problem with writing and reading using serialization

    I am having a problem with writing and reading an object that has another object in it. The purpose of the class is to write a order that has multiple items in it. And there will be several orders. This is for an IB project, where one of the requirements is to utilize a hierarchical composite data structure. That is, it is "one that contains more than one element and at least one of the elements is a composite data structure. Examples are, an array or linked list of records, a record that has one field that is another record, or an array". The code is shown below:
    The error produced is
    java.lang.NullPointerException
         at SamsonRubberIndustries.CustomerOrderDetails.createCustOrdDetailsScreen(CustomerOrderDetails.java:150)
         at SamsonRubberIndustries.CustomerOrderDetails$1.run(CustomerOrderDetails.java:78)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    public class CustOrdObject implements Serializable {
         public int CustID;
         public int CustOrderID;
         public Object OrderDate;
         public InnerCustOrdObject[] innerCustOrdObj;
         public float GrandTotal;
         public int MaxItems;
         public CustOrdObject() {}
         public CustOrdObject(InnerCustOrdObject[] innerCustOrdObj,
    int CustID, int CustOrderID, Object OrderDate,
    float GrandTotal, int innerarrlength, int innerarrpos, int MaxItems) {
              this.CustID = CustID;
              this.CustOrderID = CustOrderID;
              this.OrderDate = OrderDate;
              this.GrandTotal = GrandTotal;          
              this.MaxItems = MaxItems;
              this.innerCustOrdObj = new InnerCustOrdObject[MaxItems];
         public InnerCustOrdObject[] getInnerCustOrdObj() {
              return innerCustOrdObj;
         public void setInnerCustOrdObj(InnerCustOrdObject[] innerCustOrdObj) {
              this.innerCustOrdObj = innerCustOrdObj;
         public int getCustID() {
              return CustID;
         public void setCustID(int custID) {
              CustID = custID;
         public int getCustOrderID() {
              return CustOrderID;
         public void setCustOrderID(int custOrderID) {
              CustOrderID = custOrderID;
         public Object getOrderDate() {
              return OrderDate;
         public void setOrderDate(Object orderDate) {
              OrderDate = orderDate;
         public void setGrandTotal(float grandTotal) {
              GrandTotal = grandTotal;
         public float getGrandTotal() {
              return GrandTotal;
         public int getMaxItems() {
              return MaxItems;
         public void setMaxItems(int maxItems) {
              MaxItems = maxItems;
    public class InnerCustOrdObject implements Serializable{
         public int ItemNumber;
         public float UnitPrice;
         public int QuantityRequired;
         public float TotalPrice;
         public InnerCustOrdObject() {}
         public InnerCustOrdObject(int ItemNumber, float
    UnitPrice, int QuantityRequired, float TotalPrice){
              this.ItemNumber = ItemNumber;
              this.UnitPrice = UnitPrice;
              this.QuantityRequired = QuantityRequired;
              this.TotalPrice = TotalPrice;
         public int getItemNumber() {
              return ItemNumber;
         public void setItemNumber(int itemNumber) {
              ItemNumber = itemNumber;
         public int getQuantityRequired() {
              return QuantityRequired;
         public void setQuantityRequired(int quantityRequired) {
              QuantityRequired = quantityRequired;
         public float getTotalPrice() {
              return TotalPrice;
         public void setTotalPrice(float totalPrice) {
              TotalPrice = totalPrice;
         public float getUnitPrice() {
              return UnitPrice;
         public void setUnitPrice(float unitPrice) {
              UnitPrice = unitPrice;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems;
         private static boolean FileExists, recFileExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.dat");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                 innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord-1);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              //TotPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++CurrentRecord;
                             //readOrder();
                             //readInnerOrderRecord(CurrentRecord);
                             setInnerFieldText(currentItem);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             //readOrder();
                             setInnerFieldText(currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             writeRecordNumber(MaxRecord);
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             currentItem++;
                             setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              System.err.println("currentItem" + currentItem);
              getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07
    Message was edited by:
    Kilik07

    ok i got reading to work to a certain extent... but the prob is i cnt seem to save my innerCustOrdObj proprly...when ever i look for a record using the gotorecordbtn, the outerobject, which is the orderDetails, seems to change but the innerCustOrdObj remains the same... heres the new code..
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems = 1;
         private static boolean FileExists, recFileExists;
         private static boolean RecordExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.ser");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                   //CurrentRecord--;
                   //System.out.println("Current Rec Here"+CurrentRecord);
                   if(orderDetails[CurrentRecord] == null){
                        System.err.println("CustomerOrderObj 1 is null !!");
                   }else{
                        System.err.println("CustomerOrderObj 1 is  not null !!");
                   if(orderDetails[CurrentRecord].getInnerCustOrdObj() == null){
                        System.err.println("InnerCustomerOrderObj is null !!");
                   }else{
                        System.err.println("InnerCustomerOrderObj is  not null !!");
                   innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord);
                   getInnerFieldText(MaxItems);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              //CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              TotPriceTxt.setEditable(false);
              TotPriceTxt.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt){
                        TotPriceTxt.setText(""+Integer.parseInt(UnitPriceTxt.getText())*Integer.parseInt(QuantityReqTxt.getText()));
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println("Current Record " + CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             CurrentRecord = MaxRecord;
                             orderDetails[CurrentRecord] = new CustOrdObject();
                             writeRecordNumber(MaxRecord);
                             MaxItems = 1;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        setInnerFieldText(MaxItems);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             MaxItems++;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             System.out.println("Max Items "+MaxItems);
                             currentItem = MaxItems;
                             orderDetails[CurrentRecord].setMaxItems(MaxItems);
                             ///setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              gotorecordbtn = new JButton("Go To Record", createGotoButtonIcon());
              gotorecordbtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt){
                         * The text from the GotorecordTxt textfield will be taken and assigned
                         * to a temporary integer variable called Find. 
                        int Find = Integer.parseInt(CustOrderIDTxt.getText());
                        for(int j=1; j <= MaxRecord; j++){
                              * Using a for loop, each record can be read using the readCustRecord
                              * method.
                             getFieldText(j);
                              * An if condition is utilized to check whether the temporary stored variable, Find,
                              * matches a field in a record. If this record is found, then using the RecordExists
                              * which was declared at the top, either a true or false statement can be assigned
                              * If the record exists, then a true statement will be assigned, if not a false
                              * statement will be assigned.
                             if(orderDetails[j].getCustOrderID() == Find){
                                  RecordExists = true;
                                  break;
                             }else{
                                  RecordExists = false;
                        if(RecordExists == false){
                              * If the RecordExists is assigned a false statement, then a message will be
                              * displayed to show that the record does not exist.
                             JOptionPane.showMessageDialog(null, "Record Does Not Exist!", "Error Message", JOptionPane.ERROR_MESSAGE, createErrorIcon());
                        }else{
                             getFieldText(Find);
              buttonpanel.add(gotorecordbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setMaxItems(MaxItems);
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              orderDetails[orderID].getInnerCustOrdObj();
              System.err.println("currentItem" + currentItem);
              //getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   /*               System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());*/
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07

  • Problem with SimepleDateFormat for the military pattern....

    i have the code, which has to display date in the military format i.e., "yyyyMMddhhmm".
    java.util.Date date = new SimpleDateFormat("yyyyMMddhhmm").parse("200709201700");
    System.out.println("Expected Date : " + date);
    but output displays everytime i.e., Thu Sep 20 17:00:00 IST 2007
    is there any problem with the pattern???

    By military format you mean 24 hour clock time, right? I believe "hh" in SimpleDateFormat is for 12 hour clock time and "HH" is for 2 digits of 24 hour clock time.
    EDIT: Also, you're just parsing the string into a Date object. When you're printing, it'll simply use the toString() for Date, giving you an output as you see. If you want the output also to be formatted in the same way, you need to use the format() method of SimpleDateFormat with the same pattern on the Date.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    Edited by: nogoodatcoding on Oct 3, 2007 6:03 PM

  • Problem with date pattern

    Hi all,
    I have a little maddening problem with oracle.jbo.domain.Date.
    I have a viewObject with an attribute (fechaCompra) type Date and I need the time too so in controlHints I have defined:
    format type: Simple Date
    Format: yyyy-MM-dd 'at' hh:mm:ss
    Right, on runTime now i see ok the data and in the inputDate appears the calendar and the hour .
    But when I take the value of this attribute, to call a void that takes a oracle.jbo.domain.Date type, raises an error when parses the value of the atribute.
    All this doesn't happen when in the view object the controlHints are defined like this:
    format type: Simple Date
    Format: yyyy-MM-dd
    Any idea?
    Thanks in advance,
    Rowan

    hello,
    My guess would be that when you drop your formatted date into the methode the parse function is called from String to date, this work with no time attached.
    But fails with the time attached. I would double check the specific class you pass to each method to be sure they are correct.
    hat you mention parse gives an even bigger hint that you are using the parse function from oracle.jbo.domain.Date, which takes a string.
    This function will fail with your custom patterns.
    //get the value
    String value = .....
    //Not 100% sure if the at needs to be escaped or not
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd at hh:mm:ss");
    //Prolly needs a try catch, writing this by hand
    java.util.Date utilDate = sdf.parse(value);
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    oracle.jbo.domain.Date jboDate = new oracle.jbo.domain.Date(sqlDate);
    //pass to your method-Anton

  • Problem with date format dd/mm/yyyy. But I need to convert yyyy-mm-dd.

    Dear friends,
    I have the problem with date format. I receiving the date with the format dd/mm/yyyy. But I can upload to MySQL only in the format of yyyy-mm-dd.
    how should I handle this situation, for this I've created these code lines.But I have some problem with these line. please help me to solve this problem.
    String pattern = "yyyy-mm-dd";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
    Date date = format.parse("2006-02-12");
    System.out.println(date);
    } catch (ParseException e) {
    e.printStackTrace();
    System.out.println(format.format(new Date()));
    this out put gives me Tue Apr 03 00:00:00 IST 2007
    But I need the date format in yyyy-mm-dd.
    regards,
    maza
    thanks in advance.

    Thanks Dear BalusC,
    I tried with this,
    rs.getString("DATA_SCAD1")// where the source from .xls files
    String pattern = "yyyy-MM-dd";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
    Date date = format.parse("DATA_SCAD1");
    System.out.println(date);
    } catch (ParseException e) {
    e.printStackTrace();
    System.out.println(format.format(new Date()));
    this out put gives me Tue Apr 03 00:00:00 IST 2007
    But I want to display the date format in yyyy-mm-dd.
    regards,
    maza

  • Problem with SDO_FILTER combined with Timestamp and Order By using JDBC

    I'm having a problem with using SDO_FILTER. I've included a test driver below. It seems that I'm having a problem with combining the SDO_FILTER, Timestamp, ORDER BY and a nested table using the Oracle 11.1.0.7.0 driver against Oracle 11g. The below query queryNoWork results in the following error:
    Caused by: java.sql.SQLException: ORA-01422: exact fetch returns more than requested number of rows
    ORA-06512: at "MDSYS.SDO_3GL", line 1320
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
    at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3488)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1374)
    at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.execute(WrappedPreparedStatement.java:299)
    All of the other query variations seem to work. The GEOM column referenced is a Linestring that has only 2 points, start and end. Any help on this would be greatly appreciated. Thanks!
    import java.math.BigDecimal;
    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.Driver;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Enumeration;
    public class QueryTester
         public static void main(String[] args)
              try
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                   ArrayList<Object> queryParameters = new ArrayList<Object>();
                   queryParameters.add(new BigDecimal(0));
                   queryParameters.add(new Double(0));
                   queryParameters.add(new BigDecimal(180));
                   queryParameters.add(new Double(90));
                   queryParameters.add(new java.sql.Date(sdf.parse("2005-12-25").getTime()));
                   queryParameters.add(new java.sql.Date(sdf.parse("2005-12-26").getTime()));               
                   BigDecimal one = new BigDecimal(1);
                   DriverManager.registerDriver((Driver) Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
                   Enumeration<Driver> drivers = DriverManager.getDrivers();
                   while(drivers.hasMoreElements())
                        System.out.println(drivers.nextElement().getClass().getName());
                   Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@xxxx:1521:xxxx", "xxxx", "xxxx");
                   String queryNoWork = "select * from (select ROWNUM rowcount, a.* from (select * from TRACK_SEGMENTS where ( ( sdo_filter(GEOM, sdo_geometry(2003, 8307, null, sdo_elem_info_array(1, 1003, 3), sdo_ordinate_array(?, ?, ?, ?) ), 'MASK=ANYINTERACT') = 'TRUE' and END_DATE >= ?and START_DATE < ?) and 1 = 1 and 1 = 1) and ((START_DATATYPE = 'maritime_dense')) ORDER BY ID ) a) where rowcount between 1 and 30000";
                   String queryWorks0 = "select * from (select ROWNUM rowcount, a.* from (select * from TRACK_SEGMENTS where ( ( sdo_relate(GEOM, sdo_geometry(2003, 8307, null, sdo_elem_info_array(1, 1003, 3), sdo_ordinate_array(?, ?, ?, ?) ), 'MASK=ANYINTERACT') = 'TRUE' and END_DATE >= ?and START_DATE < ?) and 1 = 1 and 1 = 1) and ((START_DATATYPE = 'maritime_dense')) ORDER BY ID ) a) where rowcount between 1 and 30000";
                   String queryWorks1 = "select * from (select ROWNUM rowcount, a.* from (select * from TRACK_SEGMENTS where ( ( sdo_filter(GEOM, sdo_geometry(2003, 8307, null, sdo_elem_info_array(1, 1003, 3), sdo_ordinate_array(?, ?, ?, ?) ), 'MASK=ANYINTERACT') = 'TRUE' and END_DATE >= TO_TIMESTAMP('2005-12-25','YYYY-MM-DD') and START_DATE < TO_TIMESTAMP('2005-12-26','YYYY-MM-DD')) and 1 = 1 and 1 = 1) and ((START_DATATYPE = 'maritime_dense')) ORDER BY ID ) a) where rowcount between 1 and 30000";
                   String queryWorks2 = "select * from (select ROWNUM rowcount, a.* from (select * from TRACK_SEGMENTS where ( ( sdo_filter(GEOM, sdo_geometry(2003, 8307, null, sdo_elem_info_array(1, 1003, 3), sdo_ordinate_array(?, ?, ?, ?) ), 'MASK=ANYINTERACT') = 'TRUE' and END_DATE >= ?and START_DATE < ?) and 1 = 1 and 1 = 1) and ((START_DATATYPE = 'maritime_dense')) ) a) where rowcount between 1 and 30000";
                   String queryWorks3 = "select * from TRACK_SEGMENTS where ( ( sdo_filter(GEOM, sdo_geometry(2003, 8307, null, sdo_elem_info_array(1, 1003, 3), sdo_ordinate_array(?, ?, ?, ?) ), 'MASK=ANYINTERACT') = 'TRUE' and END_DATE >= ?and START_DATE < ?) and 1 = 1 and 1 = 1) and ((START_DATATYPE = 'maritime_dense')) ORDER BY ID";
                   String query = queryWorks0;
                   PreparedStatement s = conn.prepareStatement(query);
                   int parameterIndex = 0;
                   for (Object object : queryParameters) {
                        if (object instanceof Timestamp)
                             s.setDate(++parameterIndex, (Date) object);
                        else
                             s.setObject(++parameterIndex, object);
                   s.execute();
                   ResultSet results = s.getResultSet();
                   results.next();
                   System.out.println("executed query - " + results.getLong(1));
              catch (Exception e)
                   e.printStackTrace();
    }

    Is the TRACK_SEGMENTS table partitioned ?
    It looks like in the case where the SQL does not work, it is not using the Spatial index. So can you add some index hints
    in the query to force it to use the spatial index TRACK_SEGMENTS table ?
    siva

  • Date problem with IST(+5:30) timezone

    Hi,
    I'm having problem with Timezone IST, which is GMT + 05:30.
    SimpleDateFormat returns incorrect date when timezone on client machine is other than IST.
    When Timezone on machine is IST, correct value is returned.
    See the below example. All four dates are same ( LKT is also + 05:30).
    When timezone on machine is IST, all four dates are displayed same.
    For any other timezone, IST date is displayed incorrectly, rest 3 are displayed correctly.
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Test {
        public static void main(String[] args) throws ParseException {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy");
            Date date1 = simpleDateFormat.parse("Wed Sep 02 02:17:41 +0530 2009");
            Date date2 = simpleDateFormat.parse("Wed Sep 02 02:17:41 IST 2009");
            Date date3 = simpleDateFormat.parse("Tue Sep 01 13:47:41 PDT 2009");
            Date date4 = simpleDateFormat.parse("Wed Sep 02 02:17:41 LKT 2009");
            System.out.println(date1.toString());
            System.out.println(date2.toString());
            System.out.println(date3.toString());
            System.out.println(date4.toString());
            System.out.println("Date1 equals Date2? " + date1.equals(date2));
            System.out.println("Date1 equals Date3? " + date1.equals(date3));
            System.out.println("Date1 equals Date4? " + date1.equals(date4));
            System.out.println("Date1.getTime() " + date1.getTime());
            System.out.println("Date2.getTime() " + date2.getTime());
            System.out.println("Date3.getTime() " + date3.getTime());
            System.out.println("Date4.getTime() " + date4.getTime());
    Output when timezone on client is GMT IST (GMT + 05:30):
    Wed Sep 02 02:17:41 IST 2009
    Wed Sep 02 02:17:41 IST 2009
    Wed Sep 02 02:17:41 IST 2009
    Wed Sep 02 02:17:41 IST 2009
    Date1 equals Date2? true
    Date1 equals Date3? true
    Date1 equals Date4? true
    Date1.getTime() 1251838061000
    Date2.getTime() 1251838061000
    Date3.getTime() 1251838061000
    Date4.getTime() 1251838061000
    Output when timezone on client is GMT (Casablanca):
    Tue Sep 01 15:47:41 ACT 2009
    Tue Sep 01 19:17:41 ACT 2009
    Tue Sep 01 15:47:41 ACT 2009
    Tue Sep 01 15:47:41 ACT 2009
    Date1 equals Date2? false
    Date1 equals Date3? true
    Date1 equals Date4? true
    Date1.getTime() 1251838061000
    Date2.getTime() 1251850661000
    Date3.getTime() 1251838061000
    Date4.getTime() 1251838061000
    Output when timezone on client is PDT ( -0800, -0700 for this date due due Daylight saving):
    Tue Sep 01 13:47:41 PDT 2009
    Tue Sep 01 17:17:41 PDT 2009
    Tue Sep 01 13:47:41 PDT 2009
    Tue Sep 01 13:47:41 PDT 2009
    Date1 equals Date2? false
    Date1 equals Date3? true
    Date1 equals Date4? true
    Date1.getTime() 1251838061000
    Date2.getTime() 1251850661000
    Date3.getTime() 1251838061000
    Date4.getTime() 1251838061000
    IS this a bug in java??
    Regards

    Your program is in error. PDT and LKT are not valid time zone ids in Java. There may be other problems, also, I didn't check.
    I know this program produces valid results, you can try it
    import java.text.DateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    public class DateTest
        public static void main(String[] args)
            Date current = new Date();
            DateFormat df =
                DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL);
            System.out.println("Default TZ: " + df.format(current));
            df.setTimeZone(TimeZone.getTimeZone("IST"));
            System.out.println(df.format(current));
            df.setTimeZone(TimeZone.getTimeZone("GMT"));
            System.out.println(df.format(current));
            df.setTimeZone(TimeZone.getTimeZone("Etc/GMT-5"));
            System.out.println(df.format(current));
    }This program lists all of Java's time zones
    import java.util.*;
    public class TimezoneList
        public static void main(String[] args)
            int msPerHr = 3600 * 1000;
            String[] ids = TimeZone.getAvailableIDs();
            for (int n = 0; n < ids.length; n++)
                TimeZone tz = TimeZone.getTimeZone(ids[n]);
                System.out.print(
                    "TZ: " + ids[n] + "  " + (double) tz.getRawOffset() / msPerHr + "  ");
                System.out.println(
                    tz.useDaylightTime() ? "DST=" + (double) tz.getDSTSavings() / msPerHr : "");
    }

  • Problem with java print

    Hi, I'm have problems with java print (g2d). For example i want to print a String "ABC**************************DEF" on paper size 80mm width (invoice paper). I can print all that string with paper A4 size, but with paper size 80mm i have problem with that String, the result is "C*****************D" lost AB and EF. I think i had problem with paper size, pls help me. Thank you so much.
    My code is below:
    package app.util;
    To change this template, choose Tools | Templates
    and open the template in the editor.
    @author HUU NGHIA
    // Printing Sample code
    // This code demonstrates the Java 2 print mechanism
    import com.connection.Product;
    import java.awt.;
    import java.awt.print.;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Vector;
    // Define a class that is called per page that needs printing. It implements
    // the one and only method in the Printable interface : print. Note that
    // this is quite separate from the PrinterJob class print() method.
    // This method does not actually do any printing. All it does is write text
    // and/or graphics onto the passed page (graphics context). The calling
    // printer job object will then pass this page to the printer.
    public class PrinterController {
    public static void print(Vector<Product> products) {
    // Create an object that will hold all print parameters, such as
    // page size, printer resolution. In addition, it manages the print
    // process (job).
    PrinterJob job = PrinterJob.getPrinterJob();
    // It is first called to tell it what object will print each page.
    job.setPrintable(new PrintObject(products));
    // Then it is called to display the standard print options dialog.
    if (job.printDialog()) {
    // If the user has pressed OK (printDialog returns true), then go
    // ahead with the printing. This is started by the simple call to
    // the job print() method. When it runs, it calls the page print
    // object for page index 0. Then page index 1, 2, and so on
    // until NO_SUCH_PAGE is returned.
    try {
    job.print();
    } catch (PrinterException e) {
    e.printStackTrace();
    class PrintObject implements Printable {
    Vector<Product> products;
    public PrintObject(Vector<Product> products) {
    this.products = products;
    public int print(Graphics g, PageFormat f, int pageIndex) {
    Graphics2D g2 = (Graphics2D) g; // Allow use of Java 2 graphics on
    // the print pages :
    System.out.println("f.getImageableX(): " f.getImageableX());
    // A simple circle to go on the second page (index = 1).
    switch (pageIndex) {
    case 0:
    printInvoiceTemplate(g2, products);
    return PAGE_EXISTS;
    // case 1 : g2.setColor(Color.red); // Page 2 : print a circle
    // g2.draw(circle);
    // return PAGE_EXISTS;
    default:
    return NO_SUCH_PAGE; // No other pages
    public String getDate(){
    Date d = new Date();
    SimpleDateFormat sp = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    return sp.format(d);
    private void printInvoiceTemplate(Graphics2D g2, Vector<Product> products) {
    //System.out.println("#######" cardInfo.getTranType());
    int alignY = 40;
    int alignXCenter = 60;
    int enterSpace = 15;
    int xProductName = 10;
    int xUnit = 85;
    int xAmt = 110;
    int xTotal = 155;
    int yEndData = 0;
    int totalAll = 0;
    g2.setColor(Color.black); // Page 1 : print a rectangle
    g2.setFont(new Font("Verdana", 0, 8));
    g2.drawString("ABC", alignXCenter, alignY);
    g2.drawString("123WWW", alignXCenter, alignY enterSpace *1);
    g2.drawString("Phone: (08)62891633", alignXCenter, alignY enterSpace*2);
    g2.setFont(new Font("Verdana", 1, 12));
    g2.drawString("Invoice", alignXCenter - 10, alignY enterSpace*4);
    products = new Vector<Product>();
    for (int i = 0; i < 10; i+) {
    Product product = new Product();
    product.setProductName("ZESTORETIC TAB 20MG B/28" i);
    product.setUnit("v"+i);
    product.setAmt(5+i);
    product.setPrice(50000+i);
    products.add(product);
    for (int i = 0; i < products.size(); i+) {
    System.err.println(i);
    int total = products.get(i).getAmt()*products.get(i).getPrice();
    g2.drawString(i+1+"."products.get(i).getProductName(), xProductName+2, alignY enterSpace(8+(i*2)));
    g2.drawString(products.get(i).getUnit(), xUnit+5, alignY enterSpace*(9(i*2)));
    g2.drawString(products.get(i).getAmt()"x"+AppUtils.formatPrice(products.get(i).getPrice())"", xAmt+5, alignY enterSpace*(9(i*2)));
    g2.drawString(AppUtils.formatPrice(total), xTotal+15, alignY enterSpace*(9(i*2)));
    yEndData = 9+(i*2);
    totalAll = totalAll total;
    System.out.println(yEndData);
    g2.drawLine(xProductName, alignY enterSpace*(yEndData 1), 210, alignY enterSpace*(yEndData 1));
    g2.drawString(AppUtils.formatPrice(totalAll)" VND", xAmt, alignY enterSpace*(yEndData 2));
    g2.drawString("Thank you", alignXCenter, alignY enterSpace*(yEndData 4));
    g2.drawString("***", alignXCenter 30, alignY enterSpace*(yEndData + 5));
    public static void main(String[] args) {
    PrinterController.print(null);
    }

    When you posted you didn't use code tags, as a result the forum software has interpreted some of your characters in your program as screen formatting codes and has corrupted your post--the most easily observable change is the bolded characters in you post. Please repost your code using code tags so people will be helping with uncorrupted code.

  • Problem with af:selectInputDate (no calendar popup)

    Hi All,
    I have a problem with the af:selectInputDate component and the calendar popup when using a custom converter. My converter converts the date in a way, that it always has a four digit year depending on the short date format and the corresponding locale, e.g. 01/18/2007 instead of 01/18/07 for en-us. It looks like when I am using my converter with the component in the following way some javascript is not generated by the af:selectInputDate which results in an javascript error when clicking on the popup button:
    <h:panelGroup>
    <af:selectInputDate id="idPatientBirthDate" columns="12" simple="true" value="#{PatientDetails.patient.birthDate}">
    <f:converter converterId="BirthdateConverter" />
    </af:selectInputDate>
    <h:message for="idPatientBirthDate" errorClass="errorMessageStyle"></h:message>     
    </h:panelGroup>
    The following javascript is not generated using the above jsf:
    <script>
    if(window['_dfs'] == (void 0)){var _dfs=new Object();}_dfs["_id43:general:idPatientBirthDate"]='M/d/yyyy';function __id43Validator(){return true;}
    </script>
    I am using version 10.1.3.0.4 of ADF faces.
    My BirthdateConverter is a standard converter that implements the Converter interface and is not doing any magical. It works perfectly for other components. An interesting fact is, that the above javascript gets generated when I am using no converter at all or the standard date/time converters like f:convertDateTime provided by the RI. However, these don't provide the functionality I need.
    I have the bad feeling, that I am missing something. Does anyone else ran across this problem?
    Thanks,
    Herbert

    Frank,
    Thank you for your answer. I'm not using ADF BC, so is there a possible workaround? My model provides a standard java.util.Date. My converter looks like:
    public class BirthdateConverter implements Converter {
      public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String sDate) {
        Locale locale = facesContext.getCurrentInstance().getExternalContext().getRequestLocale();
        String pattern = AppUtil.getFourDigitYearPattern(DateFormat.SHORT);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
        java.util.Date d = sdf.parse(sDate);
        // converter logic
        return d;
      public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object) {
        if (object == null)
          return null;
        if (!(object instanceof Date))
          return object.toString();
        Locale locale = facesContext.getCurrentInstance().getExternalContext().getRequestLocale();
        String pattern = AppUtil.getFourDigitYearPattern(DateFormat.SHORT);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
        return sdf.format((java.util.Date)object);
    }AppUtil.getFourDigitYearPattern(DateFormat.SHORT) provides a date pattern, e.g. "M/d/yyyy" for locale en-us. In the above code I did not include try-catch blocks to make it more readable.
    Herbert
    Message was edited by:
    user575859

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

Maybe you are looking for

  • Sorting Date

    Hi All, Kindly help me in resolving the below query:- select to_char(rcv.creation_date,'MON-YY') "Receipt Creation Date" from table_name rcv where rcv.creation_date BETWEEN NVL(:p_date_from,'01-JAN-1900') AND NVL(:p_date_to,'31-DEC-4712') order by 1

  • IPhoto '11 9.2.2 Library Size Limit

    Is there a limit for either the size of a Library or the number of photos that can be imported into iPhoto '11 9.2.2?

  • Deploy .sca files in CE 7.1

    Hi All, I downloaded the following .sca files from service market place. DICMS01_0-20002719.SCA for SP1.sca DICBS01_0-20002718.SCA for SP1.sca DIDTR01_0-20002717.SCA for SP1.sca How can i deploy these files in the CE server? Kerthi

  • Should I bail out now?

    Early on Friday morning I signed up for BT Infinity and a little later got an email confirming the order and directing me to the online tracking.  By late on Saturday afternoon the tracking was still saying that no order existed. I decided to call su

  • Im trying to switch my samsung intensity for a LG octane because I lost my intensity.

    When I try to input the Device ID for the LG octane, i click enter and a window pops up saying this phone requires me to change my plan. It's a basic phone so I don't understand why it's telling me this. Help!