Add Year

Hi,
I have a query where I am converting a date to a year field and adding 1 onto the year:
to_char(s.active_month, 'YYYY')+1
active_month is in date format DD-MON-YYYY
I get an error message:
ORA-00932: inconsistent datatypes: expected NUMBER got CHAR
00932. 00000 - "inconsistent datatypes: expected %s got %s"
Can anyone help with converting this field to a number?
Thanks
Edited by: sliderrules on 15-Nov-2010 08:56

Hi,
If s.active_month is a DATE (which is the only reasonable way to store data that represents a point in time), then the way to get a DATE exactly one year after it is:
ADD_MONTHS ( s.active_month
        , 12
        )If you want a NUMBER that reflects the year of that date, then use EXTRACT:
EXTRACT ( YEAR FROM  ADD_MONTHS ( s.active_month
                                , 12
        )or, more simply:
EXTRACT (YEAR FROM  s.active_month) + 1You could also use TO_CHAR to convert the DATE to a VARCHAR2, then use TO_NUMBER to convert that VARCHAR2 to a NUMBER, and then add 1.
If s.active_month is not a DATE, then convert it to a DATE, then convert it to a DATE or a NUMBER.
If you'd like help, post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
Sometimes, when you use one datatype in a place where another is required, Oracle will automatically convert the type for you. The problem you posted is one case where Oracle is not doing such an iomplicit conversion for you, but even if it were, it is not a good idea to rely on implicity conversions. Always use explict functions (like EXTRACT or TO_NUMBER) to convert from one data type to another when you need to.

Similar Messages

  • Matrix table add year over year variance

    I am trying to get add a variance column to a matrix report is ssrs 2008 r2. However I am unable to create the custom code needed. I have been working with many examples online but none seem to fit what I am trying to do. Any help would be great. I am trying
    to calculate the diff at a month level year over year. Like month 1 2013 – month 1 2014
    I have a matrix table with three column grouping
    Quarter
    Month
    Year
    Design view of table
    Quarter
    Month
    Year
    Customer
    Job Location
    Job id
    Example of what I need (Variance)
    1
    1
    variance
    1
    1
    variance
    1
    1
    2
    2
    2013
    2014
    2013
    2014
    Acme
    Acme Philadelphia
    jj123
    100
    150
    50
    150
    100
    -50
    Dataset
    select
    Fisc_year
    ,(case
    when
    datepart(month,dt)
    = 11 then 1
    when
    datepart(month,dt)
    = 12 then 2
    when
    datepart(month,dt)
    = 1 then 3
    when
    datepart(month,dt)
    = 2 then 4
    when
    datepart(month,dt)
    = 3 then 5
    when
    datepart(month,dt)
    = 4 then 6
    when
    datepart(month,dt)
    = 5 then 7
    when
    datepart(month,dt)
    = 6 then 8
    when
    datepart(month,dt)
    = 7 then 9
    when
    datepart(month,dt)
    = 8 then 10
    when
    datepart(month,dt)
    = 9 then 11
    when
    datepart(month,dt)
    = 10 then 12
    end)
    as Mnth
    ,fisc_qrtr
    as Qrt
    ,Customer_Name
    ,Job_Name
    ,sum(REVENUE)
    as REVENUE
    from tbl_whatever
    where Customer_name
    = @Customername
    and Fisc_year
    = @Fyear

    Hi SQLtl,
    To achieve your requirement, we can directly use expression. For more details, please refer to the following steps:
    Right-click the column contains Year field to insert a column with Outside Group-Right.
    Then type the following expression to the corresponding cells:
    =Sum(iif(Fields!Year.Value="2014",Fields!REVENUE.value,0))-Sum(iif(Fields!Year.Value="2013",Fields!REVENUE.value,0))
    Besides, we can also use custom code to achieve the same goal, please see:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/5f44a0b5-144b-4e6e-b81e-d9b025427748/how-to-get-the-difference-between-two-columns-in-a-column-group?forum=sqlreportingservices
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    If you have any feedback on our support, please click
    here.
    Katherine Xiong
    TechNet Community Support

  • How to add years to date-field ?

    hi,
    i have a field z_date type d.
    now i have to add 25 years to it, and 35 years, and so on.........
    how to handle this ?
    reg, Martin

    Hi,
    Above posts would not check for leap year dates... so while calculating it might give wrong dates...
    use the FM given below to calculate date with year's...
    data w_date type sy-datum.
    w_date = sy-datum.
    CALL FUNCTION 'J_1H_CAL_DATE_IN_INTERVAL'
      EXPORTING
        date            = w_date
        days            = 0
        months          = 0
       SIGNUM          = '+'
        years           = 30
    IMPORTING
       CALC_DATE       = w_date.
    Regards,
    Siddarth

  • ICal adds year to my birthday

    I've just checked iCal for my birthday this month, January 2015.
    iCal says I'm 73 this month, one year more than is true, I was born in 1942, it should show 72.
    iCal gets its birth dates from Contacts, I changed the date on my contacts card and it was immediately reflected in iCal.
    Changed it back to correct date, still showed in iCal as wrong date - one year added.
    Same issue on iPad 3, however birthday on iPhone 3GS is one year behind!
    Mavericks 10.9.5, iMac 2009

    TY Kilted person.
    Yeah, curious isn't it, was never much good at maths.
    Funny thing is my sister did the same thing, thought she was 30 but was 29 so had 2 30th birthday parties.
    Probably an alien conspiracy.

  • PE51,  add' Year to Date' amount as an additional column on pay slip

    Hi everyone, I am new to PE51 pay slip forms.
    PE51, I tested standard form KF01 and able to see payslip.
    But how to add YTD amount as an additional column to wage type?
    Thank you for your help,
    Karen

    Please search this forum as there are many threads relating to the configuration of the Remuneration Statement (or Pay Slip).
    There may be additional information in the Wiki, and I know that there is some very explicit documentation on the web.
    But to get you started, always copy SAP's Standard (whether it is a Form, a Schema, a Program, etc...) into a Z version, and make your changes to the Z version.  In this case it would be to form ZF01.
    In the Change Window section, find your WT among the different groups, and make sure that it is pulling information from tables RT, RTS and CRT.

  • Add years to query

    Hi all,
    I have a function collecting years from another table and creating a dynamic sql statement to included all years.
    Also I set some variables in the where statement. At the end of the function I use execute immediate.
    The issue with this method is time, it's taking almost double the time using execute immediate.
    I can provide some data sample if you like.
    Thanks in advanced.
    Best,

    Here is my code:
    create table general(
    general_id number,
    general_type nvarchar2(10),
    start_year number,
    end_year number,
    CONSTRAINT "PK_GENERAL" PRIMARY KEY (general_id)
    insert into general(general_id, general_type, start_year, end_year)
    values (1, 'data 1', 2009, 2012);
    insert into general(general_id, general_type, start_year, end_year)
    values (2, 'data 2', 2011, 2015);
    create table activity(
    activity_id number,
    general_id number,
    customer_id number,
    fy number,
    value1 number,
    CONSTRAINT "PK_ACTIVITY" PRIMARY KEY (activity_id)
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(1,1,1,2009,10);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(2,1,1,2010,20);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(3,1,1,2011,30);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(4,1,1,2012,40);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(5,1,2,2009,50);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(6,1,2,2010,60);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(7,1,2,2011,70);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(8,1,2,2012,80);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(9,2,1,2011,90);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(10,2,1,2012,100);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(11,2,1,2013,110);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(12,2,1,2014,120);
    insert into activity(activity_id,general_id,customer_id,fy,value1)
    values(13,2,1,2015,130);
    create table rates(
    rate_id number,
    customer_id number,
    fy number,
    amount number,
    CONSTRAINT "PK_RATES" PRIMARY KEY (rate_id)
    insert into rates(rate_id,customer_id, fy, amount)
    values(1,1,2009, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(2,1,2010, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(3,1,2011, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(4,1,2012, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(5,1,2013, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(6,1,2014, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(7,1,2015, 0.23);
    insert into rates(rate_id,customer_id, fy, amount)
    values(8,2,2009, 0.41);
    insert into rates(rate_id,customer_id, fy, amount)
    values(9,2,2010, 0.41);
    insert into rates(rate_id,customer_id, fy, amount)
    values(10,2,2011, 0.41);
    insert into rates(rate_id,customer_id, fy, amount)
    values(11,2,2012, 0.41);
    insert into rates(rate_id,customer_id, fy, amount)
    values(12,2,2013, 0.41);
    insert into rates(rate_id,customer_id, fy, amount)
    values(13,2,2014, 0.41);
    insert into rates(rate_id,customer_id, fy, amount)
    values(14,2,2015, 0.41);Here is my select statement:
    select
    NVL(SUM(CASE WHEN rnk = 1 then nvl(totalAmount, 0) else 0 end),0) year_1, --How to do this line dynamic for all years?
    NVL(SUM(CASE WHEN rnk = 2 then nvl(totalAmount, 0) else 0 end),0) year_2,
    NVL(SUM(CASE WHEN rnk = 3 then nvl(totalAmount, 0) else 0 end),0) year_3,
    NVL(SUM(CASE WHEN rnk = 4 then nvl(totalAmount, 0) else 0 end),0) year_4,
    NVL(SUM(CASE WHEN rnk = 5 then nvl(totalAmount, 0) else 0 end),0) year_5,
    NVL(SUM(CASE WHEN rnk = 6 then nvl(totalAmount, 0) else 0 end),0) year_6
    from (
       select a.fy, a.value1, r.amount, a.value1 * r.amount as totalAmount,
       dense_rank() over (partition by a.general_id order by a.fy ) rnk
       from activity a
       join rates r on r.customer_id = a.customer_id and r.fy = a.fy
       join general g on g.general_id = a.general_id
       where a.general_id = 1
       and a.fy between g.start_year and g.end_year
    )Result:
            YEAR_1     YEAR_2     YEAR_3     YEAR_4     YEAR_5     YEAR_6
         22.8              29.2              35.6                42            0             0I hope this help to clarify my issue.
    Thanks!
    Edited by: user9542267 on Oct 19, 2012 1:20 PM

  • How can I add year to mail reply attribution

    Pre-Lion one could modify  /System/Library/Frameworks/Message.framework/Versions/\
    B/Resources/English.lproj/Delayed.strings .
    However it is now binary under Lion.
    'year' is vital, especially in a business environment.

    Tx for the quick reply.
    I am able to edit using nano.
    I didn't go into the gory details in case there was an easy answer (8-)#
    The previous instruction, for the ASCII file, was on
    http://hints.macworld.com/article.php?story=20050505001300161
    based on:
    "REPLY_ATTRIBUTION" = "On %1$@, at %2$@, %3$@ wrote:nn";
    "REPLY_ATTRIBUTION" is near the top of the file within a section of other commands.
    I have a later section with:
    Kerberos Version 4_^P^_On %1$@, at %2$@, %3$@ wrote:
    ... and two newlines after 'wrote:' followed by:
    _^P1
    Looking at other entries, I suspect "^P^_" is the start marker and the second "_" is the end marker.
    My attribution currently is:
    "On Jan 31, at 18:06 | Jan31, Apple Support Communities Updates wrote:" followed by two newlines.
    Presumably %1$@ == "Jan 31"
                         %2$@ == "18:06: | Jan 31"
                         %3$@ == "Apple Support Communities Updates"
    Any suggestions on what  to modify this to? 
    Surely there must be some non-hacking way, especially as the attribution is so broken?
    Without 'year' it makes no sense at all.
    Tony

  • Add years to a given date

    I've two colunms in one of my tables: date & term
    I want to calculate the end date now. but column date is of formate date and column term is of type int. How can I calculate the sum of these two?
    If I have f.i. date = 02/11/2008 and term = 6. then I've to get 02/11/2014. How can I achieve this?
    tnx in advance

    If you are on the last day of the month, add_months function consider you want the nth month in same situation, e.g. the last day of the target month.
    Whereas to_yminterval is more mathematical approach and get the same day as the source, that's one of the reason it might fail.
    We could merge the two functions in a function :
    SQL> create or replace function my_add_months(p_date date, p_months number) return date as
      2  begin
      3      return p_date+to_yminterval('00-'||p_months);
      4  exception when others then return add_months(p_date,p_months);
      5  end;
      6  /
    Function created.
    SQL>
    SQL> select my_add_months(date '2008-02-29',10) , my_add_months(date '2008-02-29',72) from dual;
    MY_ADD_MONTHS(D MY_ADD_MONTHS(D
    29-DEC-08       28-FEB-14Nicolas.
    Edited by: N. Gasparotto on Sep 3, 2008 10:32 AM

  • How can I default Firefox to open Google's "past year" search option every time?

    Hp 8510W "workstation" laptop.<br />
    Winxppro32<br />
    Firefox 17.0<br />
    No other OS installed.<br />
    WISH LIST...
    ...to set Google's default date range to "past year" under ALL circumstance. Open from desktop, open in newtab, and default to "past year" when opening a second time from Google's top toolbar.
    I'm 2/3 there. That last one has me stumped.
    There might be a more elegant overall fix to this problem. A single plugin perhaps. If anyone is aware of such please let me/us know. There appear to be many complex regedit and recoding suggestions, but I cannot/will-not go that deep into this just to fix this eminently simple shortcoming of Firefox/Google.
    I tried the Google forums to no avail. Google, and it's forum members, just flat out do not have anything to offer here. The simplest remedy ought to be on their end but unfortunately it does not appear to be at all forthcoming.
    So I got halfway there via re-setting the home page in Firefox's Tools...Options...General...
    ...Home Page: https://www.google.com/webhp?tbs=qdr:y
    This defaults Google's date range to "past year" every time Google is opened from Firefox's desktop icon. 'y' can be changed to 'w' 'm' etc for week, month, etc. Default to year just works for 90 percent of my own searches.
    Further, I pasted the same URL into Firefox's about:config values line for...
    browser.newtab.url; https://www.google.com/webhp?tbs=qdr:y
    This enables the same "past year" defaulted Google home page to open with every new tab. That may not be for everyone, but that's my preference as well.
    If I decide I need a shorter or deeper date range I can still drop down the box and choose it to override the default.... same as before..... it's just that the new default is "past year" instead of "anytime". All is good, almost.
    ===================
    Like I said, that gets me 2/3 to my goal. The limitation I've discovered is that when opening any subsequent search via the present Google page's toolbar for
    Images
    Maps
    Play
    YouTube
    News
    Gmail
    Drive
    Calendar
    More
    ... and then returning to "search" on that same bar, Google opens in it's default "anytime" date range.
    So just for the sake of eliminating the obvious I went back into about:config. I did a "Search" for "Google" and found six new likely candidates for resetting the value from Google to.....
    https://www.google.com/webhp?tbs=qdr:y
    These were....in order of likelihood .....
    browser.search.defaultenginename;<br />
    https://www.google.com/webhp?tbs=qdr:y
    browser.search.order.1;<br />
    https://www.google.com/webhp?tbs=qdr:y
    browser.startup.homepage;<br />
    https://www.google.com/webhp?tbs=qdr:y
    browser.contentHandlers.types.0.title;<br />
    https://www.google.com/webhp?tbs=qdr:y
    browser.contentHandlers.types.0.uri;<br />
    https://www.google.com/webhp?tbs=qdr:y
    browser.safebrowsing.provider.0.name;<br />
    https://www.google.com/webhp?tbs=qdr:y
    I went back and navigated to a new Google home page by opening it from the desktop and then navigating to "images" and then back again to "search" and discovered, to my dismay, that it still opened the Google search page with "anytime" defaulted.
    Soooooo.... can anyone guide me over this last hurdle?

    You can create a searchplugins folder in the Firefox Profile Folder and copy the google.xml file from that same folder in the Firefox program folder to that folder and rename the file to something like google-year.xml "Google (Year)".
    This is better then to edit the original files
    You can use this button to go to the Firefox profile folder:
    *Help > Troubleshooting Information > Profile Directory: Show Folder
    You need to open the file in a plain text editor and change the shortname and description and add (Year) like "Google (Year)"<br />
    Then you need to extend the Param line and append the code to add the tbs=qdr:y param.<br />
    You should do this in all three sections (suggestion, keyword search, context search).
    <pre><nowiki><Param name="tbs" value="qdr:y"/></nowiki></pre>
    Then you should see an extra search engine in you click the search engine icon on the location bar that shows the results from the past year.
    Make a backup copy of the file, so you can easily restore this file if you ever need a new profile.

  • Non standard Year member in Planning Years dimension

    We have a non standard (to Planning) member of the Years dimension called 'No Year'. In order to add it initially, I had to go to the back end of Planning (HSP_OBJECT and HSP_UNIQUE_NAMES tables) and modify the members there. This was in version 9. The order of the Years members was then FY95 through FY14, then came No Year, then FY15. This worked for our start and end years within Planning, as our start year was FY09 and our end year was No Year, which allowed us to Plan through FY14 and also entered non-year specific data to No Year on forms. It also allowed us to omit 'No Year' from our scripts using a range of years FY09:FY14 (using substitution variables). Now that the year has rolled over (and, incidentally, we've upgraded to version 11), and our Planning years are FY10 through FY15, I would like to move No Year to be after FY15. However, I don't seem to be able to do that by updating the underlying tables above. I make the changes to the two tables, but it is not reflected in Planning (they display in the same order), and if I try to edit either of the two members in Planning (No Year or FY15), it gives me an error saying the member already exists. Does anyone know how I can accomplish moving the No Year member? I need to do it not only this year, but to have a process my client can follow each year, moving that member in the outline to be directly after the last Planning year.
    Thanks,
    Sabrina

    If you want to go about hacking the tables and changing the order of 'No Year'.
    If you run the following SQL against your planning application
    select * from hsp_object where object_type = 38
    You will see the position column and will have values like 1000000 = First place, 1000010 = Second Place and so on.
    To alter the position then you need to note down the position value of 'No Year' and 'FY15'
    update hsp_object set position = '1000070'
    where object_type = 38 and object_name='No Year'
    update hsp_object set position = '1000080'
    where object_type = 38 and object_name='FY14'
    Restart planning. Now this is all done at your own risk and when you app goes boom don't blame me :)
    If 'No Year' was added in the correct way when you add year's it should always stay as the last position.
    Planning assigns object ids between set ranges, normal year values (FY..) are 50002 onwards
    No Year is out of that range e.g 50412
    When No Year is added correctly then planning will add a new to the normal range of values for year (last year value + 1) and then alters the position order
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How to add members for existing outline

    Are there any ways to add year members(jan,feb,mar...)
    every year to an existing outlines other than manually adding.

    The choice to use 2 dimensions (Years,Months) or a single dimension with months rolling up to years really depends on the purpose of the App. For many accounting related apps, it's preferable to have the information in 1 dimension so that YTD and quarterly rollups are simpler - instead of being a combination of members across 2 dimensions.
    I would recommend making a simple Excel file with 2 columns - first column has your Year, second column has your month. Save it as a txt file, then use a dimension build load rule to build the children.

  • SSRS Expression Month at a glance

    I have a report that I am trying to regress the payment sums out month by month. I know how to do this in SQL, but no idea in SSRS. Below is what I would like the table to look like.
    Year                             Month                 
    Total Payments       Month1            Month2             Month 3
    2012                              1                      
    10,000.00                2000.00          2000.00            6000.00
                                         2                      
    15,000.00                5000.00           1000.00           9000.00
    And this would go on. I have the report built to drill down by year and month and show the sum of the payments. What I can not figure out is how to break out the payments collected month by month. I hope this makes sense.

    Okay after much playing with this I have starting having success. This is what I want to do.
    =sum(IIF(Fields!MPaidDate.Value = Month(Dateadd(DateInterval.Month, 1, Fields!Date_Recieved.Value))
    and Fields!YPaidDate.Value = Year(Fields!Date_Recieved.Value), Fields!Amount_Paid.Value,0))
    My month 1 column I left out the dateadd and I got back the right values. But when I try to add 1 month with date add it returns false.
    Why do you need to write conditional expressions like this?Isnt it enough to bring MONTH(datecolumn) as a field in your dataset and use matrix control in your report? Add year to rowgroup and Month to column group to get data split up into monthwise. And inside
    data part add three columns to show your measure value ie.#of orders ,
        Balance 
     &  Total Paid  
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Use of New logical Level Key in OBIEE

    Hi all,
    can anybody tell me what is the use of newlogicallevel key in hierarchies(OBIEE).
    why we need to set a newlogical level key for each level in hierarchies.
    pls explain in detail....
    regards
    bharath

    You may get info as below if you use Admin tool help file
    Level keys. Each logical level (except the topmost level defined as a Grand Total level) needs to have one or more attributes that compose a level key. The level key defines the unique elements in each logical level. The dimension table logical key has to be associated with the lowest level of a dimension and has to be the level key for that level.
    A logical level may have more than one level key. When that is the case, specify the key that is the primary key of that level. All dimension sources which have an aggregate content at a specified level need to contain the column that is the primary key of that level. Each logical level should have one level key that will be displayed when an Answers or Intelligence Dashboard user clicks to drill down. This may or may not be the primary key of the level. To set the level key to display, select the Use for drill down check box on the Level Key dialog box.
    Be careful using level keys such as Month whose domain includes values January, February, and so on—values that are not unique to a particular month, repeating every year. To define Month as a level key, you also need to include an attribute from a higher level, for example, Year. To add Year, click the Add button in this dialog and select the logical column from the dialog that is presented.

  • Can someone pls help me with this code

    The method createScreen() creates the first screen wherein the user makes a selection if he wants all the data ,in a range or single data.The problem comes in when the user makes a selection of single.that then displays the singleScreen() method.Then the user has to input a key data like date or invoice no on the basis of which all the information for that set of data is selected.Now if the user inputs a wrong key that does not exist for the first time the program says invalid entry of data,after u click ok on the option pane it prompts him to enter the data again.But since then whenever the user inputs wrong data the program says wrong data but after displaying the singlescreen again does not wait for input from the user it again flashes the option pane with the invalid entry message.and this goes on doubling everytime the user inputs wrong data.the second wrong entry of data flashes the error message twice,the third wrong entry flashes the option pane message 4 times and so on.What actually happens is it does not wait at the singlescreen() for user to input data ,it straight goes into displaying the JOptionPane message for wrong data entry so we have to click the optiion pane twice,four times and so on.
    Can someone pls help me with this!!!!!!!!!
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    public class MainMenu extends JFrame implements ActionListener,ItemListener{
    //class     
         FileReaderDemo1 fd=new FileReaderDemo1();
         FileReaderDemo1 fr;
         Swing1Win sw;
    //primary
         int monthkey=1,counter=0;
         boolean flag=false,splitflag=false;
         String selection,monthselection,dateselection="01",yearselection="00",s,searchcriteria="By Date",datekey,smonthkey,invoiceno;
    //arrays
         String singlesearcharray[];
         String[] monthlist={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
         String[] datelist=new String[31];
         String[] yearlist=new String[100];
         String[] searchlist={"By Date","By Invoiceno"};
    //collection
         Hashtable allinvoicesdata=new Hashtable();
         Vector data=new Vector();
         Enumeration keydata;
    //components
         JButton next=new JButton("NEXT>>");
         JComboBox month,date,year,search;
         JLabel bydate,byinvno,trial;
         JTextField yeartext,invtext;
         JPanel panel1,panel2,panel3,panel4;
         JRadioButton single,range,all;
         ButtonGroup group;
         JButton select=new JButton("SELECT");
    //frame and layout declarations
         JFrame jf;
         Container con;
         GridBagLayout gridbag=new GridBagLayout();
         GridBagConstraints gc=new GridBagConstraints();
    //constructor
         MainMenu(){
              jf=new JFrame();
              con=getContentPane();
              con.setLayout(null);
              fr=new FileReaderDemo1();
              createScreen();
              setSize(500,250);
              setLocation(250,250);
              setVisible(true);
    //This is thefirst screen displayed
         public void createScreen(){
              group=new ButtonGroup();
              single=new JRadioButton("SINGLE");
              range=new JRadioButton("RANGE");
              all=new JRadioButton("ALL");
              search=new JComboBox(searchlist);
              group.add(single);
              group.add(range);
              group.add(all);
              single.setBounds(100,50,100,20);
              search.setBounds(200,50,100,20);
              range.setBounds(100,90,100,20);
              all.setBounds(100,130,100,20);
              select.setBounds(200,200,100,20);
              con.add(single);
              con.add(search);
              con.add(range);
              con.add(all);
              con.add(select);
              search.setEnabled(false);
              single.addItemListener(this);
              search.addActionListener(new MyActionListener());     
              range.addItemListener(this);
              all.addItemListener(this);
              select.addActionListener(this);
         public class MyActionListener implements ActionListener{
              public void actionPerformed(ActionEvent a){
                   JComboBox cb=(JComboBox)a.getSource();
                   if(a.getSource().equals(month))
                        monthkey=((cb.getSelectedIndex())+1);
                   if(a.getSource().equals(date)){
                        dateselection=(String)cb.getSelectedItem();
                   if(a.getSource().equals(year))
                        yearselection=(String)cb.getSelectedItem();
                   if(a.getSource().equals(search)){
                        searchcriteria=(String)cb.getSelectedItem();
         public void itemStateChanged(ItemEvent ie){
              if(ie.getItem()==single){
                   selection="single";     
                   search.setEnabled(true);
              else if (ie.getItem()==all){
                   selection="all";
                   search.setEnabled(false);
              else if (ie.getItem()==range){
                   search.setEnabled(false);
         public void actionPerformed(ActionEvent ae){          
              if(ae.getSource().equals(select))
                        if(selection.equals("single")){
                             singleScreen();
                        if(selection.equals("all"))
                             sw=new Swing1Win();
              if(ae.getSource().equals(next)){
                   if(monthkey<9)
                        smonthkey="0"+monthkey;
                   System.out.println(smonthkey+"/"+dateselection+"/"+yearselection+"it prints this");
                   allinvoicesdata=fr.read(searchcriteria);
                   if (searchcriteria.equals("By Date")){
                        System.out.println("it goes in this");
                        singleinvoice(smonthkey+"/"+dateselection+"/"+yearselection);
                   else if (searchcriteria.equals("By Invoiceno")){
                        invoiceno=invtext.getText();
                        singleinvoice(invoiceno);
                   if (flag == false){
                        System.out.println("flag is false");
                        singleScreen();
                   else{
                   System.out.println("its in here");
                   singlesearcharray=new String[data.size()];
                   data.copyInto(singlesearcharray);
                   sw=new Swing1Win(singlesearcharray);
         public void singleinvoice(String searchdata){
              keydata=allinvoicesdata.keys();
              while(keydata.hasMoreElements()){
                        s=(String)keydata.nextElement();
                        if(s.equals(searchdata)){
                             System.out.println(s);
                             flag=true;
                             break;
              if (flag==true){
                   System.out.println("vector found");
                   System.exit(0);
                   data= ((Vector)(allinvoicesdata.get(s)));
              else{
                   JOptionPane.showMessageDialog(jf,"Invalid entry of date : choose again");     
         public void singleScreen(){
              System.out.println("its at the start");
              con.removeAll();
              SwingUtilities.updateComponentTreeUI(con);
              con.setLayout(null);
              counter=0;
              panel2=new JPanel(gridbag);
              bydate=new JLabel("By Date : ");
              byinvno=new JLabel("By Invoice No : ");
              dateComboBox();
              invtext=new JTextField(6);
              gc.gridx=0;
              gc.gridy=0;
              gc.gridwidth=1;
              gridbag.setConstraints(month,gc);
              panel2.add(month);
              gc.gridx=1;
              gc.gridy=0;
              gridbag.setConstraints(date,gc);
              panel2.add(date);
              gc.gridx=2;
              gc.gridy=0;
              gc.gridwidth=1;
              gridbag.setConstraints(year,gc);
              panel2.add(year);
              bydate.setBounds(100,30,60,20);
              con.add(bydate);
              panel2.setBounds(170,30,200,30);
              con.add(panel2);
              byinvno.setBounds(100,70,100,20);
              invtext.setBounds(200,70,50,20);
              con.add(byinvno);
              con.add(invtext);
              next.setBounds(300,200,100,20);
              con.add(next);
              if (searchcriteria.equals("By Invoiceno")){
                   month.setEnabled(false);
                   date.setEnabled(false);
                   year.setEnabled(false);
              else if(searchcriteria.equals("By Date")){
                   byinvno.setEnabled(false);
                   invtext.setEnabled(false);
              monthkey=1;
              dateselection="01";
              yearselection="00";
              month.addActionListener(new MyActionListener());
              date.addActionListener(new MyActionListener());
              year.addActionListener(new MyActionListener());
              next.addActionListener(this);
              invtext.addKeyListener(new KeyAdapter(){
                   public void keyTyped(KeyEvent ke){
                        char c=ke.getKeyChar();
                        if ((c == KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_DELETE)){
                             System.out.println(counter+"before");
                             counter--;               
                             System.out.println(counter+"after");
                        else
                             counter++;
                        if(counter>6){
                             System.out.println(counter);
                             counter--;
                             ke.consume();
                        else                    
                        if(!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))){
                             getToolkit().beep();
                             counter--;     
                             JOptionPane.showMessageDialog(null,"please enter numerical value");
                             ke.consume();
              System.out.println("its at the end");
         public void dateComboBox(){          
              for (int counter=0,day=01;day<=31;counter++,day++)
                   if(day<=9)
                        datelist[counter]="0"+String.valueOf(day);
                   else
                        datelist[counter]=String.valueOf(day);
              for(int counter=0,yr=00;yr<=99;yr++,counter++)
                   if(yr<=9)
                        yearlist[counter]="0"+String.valueOf(yr);
                   else
                        yearlist[counter]=String.valueOf(yr);
              month=new JComboBox(monthlist);
              date=new JComboBox(datelist);
              year=new JComboBox(yearlist);
         public static void main(String[] args){
              MainMenu mm=new MainMenu();
         public class WindowHandler extends WindowAdapter{
              public void windowClosing(WindowEvent we){
                   jf.dispose();
                   System.exit(0);
    }     

    Hi,
    I had a similar problem with a message dialog. Don't know if it is a bug, I was in a hurry and had no time to search the bug database... I found a solution by using keyPressed() and keyReleased() instead of keyTyped():
       private boolean pressed = false;
       public void keyPressed(KeyEvent e) {
          pressed = true;
       public void keyReleased(KeyEvent e) {
          if (!pressed) {
             e.consume();
             return;
          // Here you can test whatever key you want
       //...I don't know if it will help you, but it worked for me.
    Regards.

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

Maybe you are looking for

  • IMessage on MacBook Pro - how to use mobile number?

    So I upgraded to 10.8.2 on ML and IOS 6 on other devices. I notice on the iPhone that my iMessages can be received by default only to the mobile number. I previously turned iMessage off because frankly it was a complete PITA and more trouble than it

  • Error -1074118610 occurred at niUSRP Fetch Rx Data (CDB Cluster).vi

       I researched this error in forum ,however, I don't reach the solutions.  Error -1074118610 occurred at niUSRP Fetch Rx Data (CDB Cluster).vi The received data is out of sequence. This may be a symptom of overflows due to an inability to maintain s

  • Using Predicate filters in a Custom component

    Hello, I have a cusom datagrid component, which gets it's data from a XMLListCollection object. The xmlList is a simple <employess><employe1><fname/><lname/></emloye1></employees> I have a text input as a part of this custom component. I am creating

  • Definitive fix for revving fans/freeze?

    Is there a definitive fix for the revving fan & freeze issues in the early edition G5s (dual 2Ghz)? Also, does the above mention problem have any relation to the defective video cards in the same machines? -- no video signal on cold starts. card need

  • Lightroom 4.3 zu/mit Photoshop CS 2

    Kann ich Fotos von Lightroom 4.3 zu/mit Photoshop CS 2 austauschen ? Mein Problem: CS 2 auf meinem System wird nicht von Lightroom 4.4 in VOREINSTELLUNGEN / EXTERNE BEARBEITUNG  erkannt, die Photoshop-Menues sind nicht aktiv. Erst wenn ich CS 2 als z