Help with menus and variables in different classes.

1) how do I change variables in different classes? My situation..
I have a few tabbed panels/planes, that ask for different user inputs. I want the last tabbed panel/plane to have the inputs on 1 plane. Is that confusing?
Code:
        JTabbedPane tp = new JTabbedPane();
        tp.addTab ("Kitchen", new KitchenPanel());
        tp.addTab ("Living Room", new LivingRoomPanel());
        tp.addTab ("Master Bedroom", new MasterBedPanel());
        tp.addTab ("Bedroom 1", new Bedroom1Panel());
        tp.addTab ("Bedroom 2", new Bedroom2Panel());
        tp.addTab ("Misc Use", new MiscPanel());
        tp.addTab ("Totals", new TotalsPanel());not the full thing obviously, but just so u see what im working with.
2) How do popup menus work? I have a menu (File -> About | File -> How to Contact)
I want The File->About menu item, to prompt a dialog
The File -> How to to prompt a dialog
Contact Menu(Not Item) to load a webpage
thanks again for the help, and i hope its not to confusing
Edited by: 2point2ek on May 25, 2009 9:51 PM

It's better to think in terms of transferring data between object, rather than between classes.
What you need is for the tab pane objects to have a reference to some common object to which the data is to be sent. This common object might be the total pane. It's generally better design to keep the data in separate objects from the presentation (in this case the totals pane), but at this stage that's probably just going to confuse you.
The simplest way to get this reference in is to the pane objects is as a constructor argument, which the constructor of your pane objects saves in a field. As you create each pane you pass it a reference and it stores that reference for when it needs to save data.
Then, when you click detect the action by which the user tells the program to store the data he's entered the pane class should call a method on the central data object, passing all the data from that pane. If there's a lot of it, wrap it up in an object (typically called a "data transfer object").
The central data object would be responsible for dealing with this data, amending totals etc.. It might delegate responsibility for updating the display to a separate total pane object.

Similar Messages

  • Java interfaces and containers in different classes

    Hi in trying to create an interface in Java that will be the basis for other classes to populate areas on in in certain panels.
    So for example I have a default size for a screen and some default buttons that should appear on it. These are all setup in a class called ScriptyUI. Within ScriptyUI I want to set up several rows where each row will be populated with the container of a different class. So for instance another class called NetworkAreaUI will create all the buttons and boxes needed for the NetworkUI class along with the actionListeners for each of the buttons. I therefore want to add this into one of the rows of the ScriptyUI class.
    Each time I try and call the networkAreaUI class from within the ScriptyUI class I get an error stating that a container is expected and not a window.
    Any Ideas?
    I have placed everything within the ScriptyUI class and it works, however this class soon becomes so large it is quite unmanageble.
    What I am also trying is something similar to these code snippets:
    I want to add this.............:
    public class NetworkAreaUI extends JFrame implements Runnable, ActionListener
        private JPanel networkPanel;
        private JTextField netPath;
        private JButton remove;
        private JButton add;
        private JLabel netDrives;
        private JComboBox driveList;
        private int driveCount = 0;
        private Thread adds;
        private Thread lists;
        private Thread removes;
        protected NetworkDrive myNetworkDrive;
    public NetworkAreaUI()
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            networkPanel = new JPanel();
            networkPanel.setLayout(new GridLayout(3,4));
            netDrives = new JLabel("Type Network Drive Location");
            networkPanel.add(netDrives);
            remove = new JButton("Remove");
            networkPanel.add(remove);
            netPath = new JTextField("\\\\Server\\Share\\Name",20);
            networkPanel.add(netPath);
            add = new JButton("add");
            networkPanel.add(add);
            driveList = new JComboBox();
            networkPanel.add(driveList);
            networkPanel.setVisible(false);
            cp.add(networkPanel);
            //Adds action listeners
            //Adds MenuSelection to the menu's
            remove.addActionListener(this);
            add.addActionListener(this);
            driveList.addActionListener(this);(then there is code for the action listeners )........into this.....
    public class ScriptyUI extends JFrame// implements ActionListener, Runnable
        private final int FRAME_WIDTH = 600;
        private final int FRAME_HEIGHT = 540;
        private JPanel rows;
        private JPanel row1;
        private JPanel row2;
        private JPanel row3;
        private JPanel row4;
        private JPanel button;
        private JPanel outputArea;
        private JTextArea message;
        private JPanel selection;
        private JButton vbs;
        private JButton bat;
       /* private JPanel networkPanel;
        private JTextField netPath;
        private JButton remove;
        private JButton add;
        private JLabel netDrives;
        private JComboBox driveList;
        private int driveCount = 0;
        private JMenuBar menu;
        private JMenu fileMenu;
        private JMenu helpMenu;
        private JMenuItem restartMenu;
        private JMenuItem quitMenu;
        private JMenuItem show;
        protected NetworkDrive myNetworkDrive;
        protected NetworkAreaUI myNetGui;
        private JButton back;
        private JButton next;
        private JTextArea output;
        private JScrollPane jsp;
        private JButton save;
        private JFileChooser fc;
        private String fileType;
        // private Thread thread;
    /*   private Thread adds;
        private Thread lists;
        private Thread removes;
        private Thread nextOne;
        private Thread saveIt;*/
      //  private Thread;
        public ScriptyUI(String title)
            super(title);
            myNetworkDrive = new NetworkDrive();
            myNetworkDrive.reset();
         //   myNetGui = new NetworkAreaUI();
            setUpGui();
    public void setUpGui()
            setSize(FRAME_WIDTH,FRAME_HEIGHT);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            //Setup Menu Bar
            menu = new JMenuBar();
            setJMenuBar(menu);
            fileMenu = new JMenu("File");
            helpMenu = new JMenu("Help");
            restartMenu = new JMenuItem("Start Over");
            quitMenu = new JMenuItem("Quit game");
            show = new JMenuItem("Show Drives");
            //Construct Menu Bar
            menu.add(fileMenu);
            menu.add(helpMenu);
            fileMenu.add(restartMenu);
            fileMenu.add(quitMenu);
            fileMenu.add(show);
            rows = new JPanel();
            rows.setLayout(new GridLayout(6,1));
            //Create Message area and populate with Text.
            row1 = new JPanel();
            message = new JTextArea("Select which format you " +
                    "would like the Script to be in. Visual Basic" +
                    "Script or Batch Script", 3, 30);
            row1.add(message);
            rows.add(row1);
            //setup the selection screen
            row2 = new JPanel();
            selection = new JPanel();
            selection.setLayout(new BorderLayout());
            //sets the buttons on the selection screen
            vbs = new JButton("Visual Basic Scripts");
            selection.add(vbs, BorderLayout.NORTH);
            bat = new JButton("Batch Scripts");
            selection.add(bat, BorderLayout.SOUTH);
            row2.add(selection, BorderLayout.CENTER);
            rows.add(row2);
            row3 = new JPanel();
            myNetGui = new NetworkAreaUI();
            row3.add(myNetGui);
            rows.add(row3);
    cp.add(rows, BorderLayout.CENTER);Any help or guidance will be greatly appreciated,

    Encephalopathic wrote:
    good
    Thanks :)
    Are you sure that you want to use a Container and not a JPanel or JComponent? This is Swing after all.Hi i set up the method as below which seemed to work:
    public Container setup()
            networkPanel = new JPanel();
            networkPanel.setLayout(new GridLayout(5,2));
            netDrives = new JLabel("Type Network Drive Location:");
            networkPanel.add(netDrives);
            typeName = new JLabel("Type Drive Letter:");
            networkPanel.add(typeName);
            netPath = new JTextField("\\\\Server\\Share\\Name",20);
            networkPanel.add(netPath);
            nameDrive = new JTextField("X",1);
            networkPanel.add(nameDrive);
            add = new JButton("add");
            networkPanel.add(add);
            remove = new JButton("Remove");
            networkPanel.add(remove);
            driveList = new JComboBox();
            networkPanel.add(driveList);
            driveNames = new JComboBox();
            networkPanel.add(driveNames);
            //Adds action listeners
            //Adds MenuSelection to the menu's
            remove.addActionListener(this);
            add.addActionListener(this);
            driveList.addActionListener(this);
            //return the content panel
            return networkPanel;
    }it is set up in the header to return container
    public Container setup()
    .but i actually return networkPanel which is setup as a JPanel.
    So have now changed it to read:
    public JPanel setup()
    .I think that should be a little better? is it?
    Thanks for the heads up.
    Ian

  • Help with writing and retrieving data from a table field with type "LCHR"

    Hi Experts,
    I need help with writing and reading data from a database table field which has a type of "LCHR". I have given an example of the original code but don't know what to change it to in order to fix it and still read in the original data that's stored in the LCHR field.
    Basically we have two Function modules, one that saves list data to a database table and one that reads in this data. Both Function modules have an identicle table which has an array of fields from type INT4, CHAR, and type P. The INT4 field is the first one.
    Incidentally this worked in the 4.7 non-unicode system but is now dumping in the new ECC6 Unicode system.
    Thanks in advance,
    C
    SAVING THE LIST DATA TO DB
    DATA: L_WA(800).
    LOOP AT T_TAB into L_WA.
    ZDBTAB-DATALEN = STRLEN( L_WA ).
    MOVE: L_WA to ZDBTAB-RAWDATA.
    ZDBTAB-LINENUM = SY-TABIX.
    INSERT ZDBTAB.
    READING THE DATA FROM DB
    DATA: BEGIN OF T_DATA,
                 SEQNR type ZDBTAB-LINENUM,
                 DATA type ZDBTAB-RAWDATA,
               END OF T_TAB.
    Select the data.
    SELECT linenum rawdata from ZDBTAB into table T_DATA
         WHERE repid = w_repname
         AND rundate = w_rundate
         ORDER BY linenum.
    Populate calling Internal Table.
    LOOP AT T-DATA.
    APPEND T_DATA to T_TAB.
    ENDLOOP.

    Hi Anuj,
    The unicode flag is active.
    When I run our report and then to try and save the list data a dump is happening at the following point
    LOOP AT T_TAB into L_WA.
    As I say, T_TAB consists of different fields and field types whereas L_WA is CHAR 800. The dump mentions UC_OBJECTS_NOT_CONVERTIBLE
    When I try to load a saved list the dump is happening at the following point
    APPEND T_DATA-RAWDATA to T_TAB.
    T_DATA-RAWDATA is type LCHR and T_TAB consists of different fields and field types.
    In both examples the dumps mention UC_OBJECTS_NOT_CONVERTIBLE
    Regards
    C

  • [svn] 4793: Fix bug SDK-17734 Path with width and height set different than path data has incorrect bounds

    Revision: 4793
    Author: [email protected]
    Date: 2009-02-02 11:20:06 -0800 (Mon, 02 Feb 2009)
    Log Message:
    Fix bug SDK-17734 Path with width and height set different than path data has incorrect bounds
    Fix: When calculating the bounds position we should take into account the implicit scaling factor actualSize/naturalSize. Also did some refactoring, getting rid of the protected method calculateTopLeft.
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-17734
    Reviewer: Ryan
    tests: mustella gumbo/layout/GraphicElement
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-17734
    http://bugs.adobe.com/jira/browse/SDK-17734
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/Ellipse.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/Path.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/graphicsClasses/GraphicElement.a s

    Thank you so much for replying.
    Yes I have removed and reinstalled WMP.
    I had good results with the PD6 application installed on the default path onto the C: drive with the one exception that if the application was launched by accident and the user data path was not available, the PD6 application would blow away my custom user path registry settings. Now that I know what they are I have made a .reg file to repair my registry to my desired user data paths.
    Installing the application on the removable drive appeared to help prevent me from launching the application by accident and overwriting my registry with default user paths.
    So which is the less of the two evils?
    If the application directory is not available, windows media player still tries to launch the .msi for installing PD6.
    If I install the application to the C: drive but the user data to the removable drive, launching the PD6 application without the user data drive will still corrupt my registry settings for a user data path.
    Both these issues seem like a logical (if not easy) fix that should be done in the PD6 application and installation package. I mean really, cannot anyone tell me why windows media player is checking the PD6 application directory? Why in PD4 did we have an option control for setting the user data path from the PD4 application? Why is this option not in the PD6 application, just the installer?
    I am given a choice during installation to move the user data to another non default location. Why else would this be provided if not to accommodate my kind of request to store the user data into an alternate location other than “My Document”. Certainly Palm is not trying to force the users on how to protect and store their personal data?
    Post relates to: Centro (Verizon)

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • Problem with storing and retriving a different langauge font in mysql

    hi,
    i have problem with storing and retriving a different character set in
    mysql database ( for example storing kannada font text in database)
    it simply store what ever typed in JTextField in database in the
    formate ??????????? and it showing ???????? .
    please what can i do this problem.
    thanks
    daya

    MySQL does not know about what type of Font you use or store. that is applicatioon specific. All it knows is the character set that you are storing and the data type and data. THere are something you should know when working with database and Java:
    1. make sure you know what character set is used for the database table.
    2. make sure you know what character set is used by Java (default to UTF-8 ..
    sort off - there are few character that it cannot save). You can enforce the
    character set being sent to the database by the String's getBytes(String charsetName) method.
    3. make sure the application you use to view the table use the correct character set
    if it use a different character set, then any character that it does not recogized
    will be replaced with a quetion mark '?'....eventhough the data is correct.

  • How to use javasetters and getters in different classes

    how to use setters and getters in different class so that the setvalue in one class is effect in second class for getting

    If i got your question right,
    make sure your classes are in the same package
    make sure your getters are public/protected
    make sure your code calls the setter before calling the getter
    Kind regards

  • MOVED: [Athlon64] Need Help with X64 and Promise 20378

    This topic has been moved to Operating Systems.
    [Athlon64] Need Help with X64 and Promise 20378

    I'm moving this the the Administration Forum.  It seems more apporpiate there.

  • Time variables with if and else statements for class script

    Hello, for an in class assignment to create a script using random generated answers im trying to get the script set up for different answers depending on the time of day here is what i have so far, in bold is my second time that i would like to have if the
    time is 6pm, the one that works right now is the one that is anything greater then 12pm and the one that is everything before 12pm the 6pm will not work:
    #Clear the Windows command console screen
    Clear-Host
    #Define the variables used in this script to collect player inputs
    $question = ""   #This variables will store the player's question
    $status = "Play"  #This variable will be used to control game termination
    $answer = 0  #This variable stores a randomly genrated number
    $time = (Get-Date).Hour  #This variable stores the current hour of the day
    #Display the game's opening screen
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host "               W E L C O M E   T O   T H E   W I N D O W S"
    Write-Host
    Write-Host
    Write-Host
    Write-Host "            P O W E R S H E L L   F O R T U N E   T E L L E R"
    Write-Host
    Write-Host
    Write-Host   
    Write-Host "                          By Zelandra"
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host " Press Enter to continue."
    #Pause script execution and wait for the player to press the Enter key
    Read-Host
    #Clear the Windows command console screen
    Clear-Host  
    #Provide the player with instructions
    Write-Host
    Write-Host " The fortune teller is a very busy and impatient mystic. Make"
    Write-Host 
    Write-Host " your questions brief and simple and only expect to receive"
    Write-Host
    Write-host " Yes / No styled answers."   
    Write-Host 
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host " Press Enter to continue."
    #Pause script execution and wait for the player to press the Enter key
    Read-Host
    #Continue game play until the player decides to stop
    while ($status -ne "Stop") {
      #Ask the player the first question
      while ($question -eq ""){
        Clear-Host  #Clear the Windows command console screen
        Write-Host
        $question = read-host " What is your question? "
      $question = ""  #Reset variable to a empty string
      #Retrieve a random number between 1 and 7
      $answer = Get-Random -minimum 1 -maximum 8
      #If it is the night the fortune teller will be a little more cranky 
      if ($time -gt 18) {
        Write-Host
        if ($answer -eq 1) { " Grrrr. The answer is NO, now let me get back to sleep!" }
        if ($answer -eq 2) { " Grrrr. The answer is !!!NEVER!!!" }
        if ($answer -eq 3) { " Grrrr. The answer is unclear, did you really think i would know?" }
        if ($answer -eq 4) { " Grrrr. The answer is sure whatever!" }
        if ($answer -eq 5) { " Grrrr. Even if i wanted to tell your fortune i wouldnt!" }
        if ($answer -eq 6) { " Grrrr. Look at the time, im busy SLEEPING!" }
        if ($answer -eq 7) { " Grrrr. Take whatever answer you want and leave me alone!" }
      #Select an answer based on the time and the random number
      #If it is the afternoon the fortune teller will be a little cranky
      if ($time -gt 12) {
        Write-Host
        if ($answer -eq 1) { " Grrrr. The answer is no!" }
        if ($answer -eq 2) { " Grrrr. The answer is never" }
        if ($answer -eq 3) { " Grrrr. The answer is unclear!" }
        if ($answer -eq 4) { " Grrrr. The answer is yes!" }
        if ($answer -eq 5) { " Grrrr. The answer is absolutely not!" }
        if ($answer -eq 6) { " Grrrr. The answer is unforseeable!" }
        if ($answer -eq 7) { " Grrrr. Im sorry could you repeat that?" }
      #If it is morning the fortune teller will be in a good mood
      else {
        Write-Host
        if ($answer -eq 1) { " Ah. The answer is yes!" }
        if ($answer -eq 2) { " Ah. The answer is Always" }
        if ($answer -eq 3) { " Ah. The answer is uncertain!" }
        if ($answer -eq 4) { " Ah. The answer is no!" }
        if ($answer -eq 5) { " Ah. The answer is there is a fair cha... OH LOOK A SQUIRREL!" }
        if ($answer -eq 6) { " Ah. I think you meant to ask something else!" }
        if ($answer -eq 7) { " Ah. Well it looks like your wish will be ready tonight!" }
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host
      Write-Host " Press Enter to continue."
      #Pause script execution and wait for the player to press the Enter key
      Read-Host
      #Clear the Windows command console screen
      Clear-host
      Write-Host
      #Prompt the player to continue or quit
      $reply = read-host " Press Enter to ask another question or type Q to quit."
      if ($reply -eq "q") { $status = "Stop" }
    #Clear the Windows command console screen
    Clear-Host
    #Provide the player with instructions
    Write-Host 
    Write-Host " Very well then. Please return again to get all your questions"
    Write-Host " answered." 
    Write-Host
    Write-Host 
    Write-Host
    Write-Host
    Write-Host
    Write-Host 
    Write-Host
    Write-Host
    Write-Host  
    Write-Host 
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host 
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host
    Write-Host " Press Enter to continue."
    #Pause script execution and wait for the player to press the Enter key
    Read-Host
    #Clear the Windows command console screen
    Clear-Host  
    Thanks again if anyone can provide help.

    Hi,
    Use -and in your afternoon if test.
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • Help with creating a method within a class

    I need help creating another method within the same class.
    Here is part of my progam, and could anyone help me convert the switch statement into a seperate
    method within the same class?
    import javax.swing.JOptionPane;
    public class Yahtzee
         public static void main (String[] args)
              String numStr, playerStr, str, tobenamed;
              int num, times = 13, roll, x, y, maxRoll = 3, z = 0, t;
              int firstDie, secondDie, thirdDie, fourthDie, fifthDie, maxDie = 5, reroll;
              int rerolling = 0, categoryChoice, score, nextDie1, nextDie2, nextDie3, nextDie4;
              Die die1, die2, die3, die4, die5;
              do
              numStr = JOptionPane.showInputDialog ("Enter the number of player: ");
              num = Integer.parseInt(numStr);
              while (num < 1 || num > 6); //end of do loop
              String [] player = new String[num];
              // boolean //finsih later to make category choice only once.
              for (x = 0; x < num; x++)
                   playerStr = JOptionPane.showInputDialog ("Name of Player" + (x + 1) + " :");
                   player[x] = playerStr;  
              } //end of for loop
              die1 = new Die();
               die2 = new Die();
               die3 = new Die();
               die4 = new Die();
               die5 = new Die();
              int scoring [][] = new int [num][13];//scoring aray
              int[] numDie = new int[maxDie];
              String[][] usedCategory = new String [num][times];
              for (x=0; x < 13; x++)
                   for (y = 0; y < num; y++)
                      usedCategory[y][x] = " ";
              for (int choices = 0; choices < times; choices++)
                   //player turns for loop.
                   for (x = 0; x < num; x++)
                        //rolls the die;
                          for (y = 0; y < maxDie; y++)
                               numDie[y] =  die1.roll();
                     numStr = JOptionPane.showInputDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
                                                                            + "\nDie1: " + numDie[0]
                                                                                + "\nDie2: " + numDie[1]
                                                                                + "\nDie3: " + numDie[2]
                                                                                + "\nDie4: " + numDie[3]
                                                                                + "\nDie5: " + numDie[4]
                                                                                + "\nWhich dice do you want to reroll");
                    reroll = numStr.length();
                    if (reroll == 0)
                        t = maxRoll;
                   else{                                                      
                    //reroll
                         for(t = 0; t < maxRoll; t++ )
                             for (y = 0; y < reroll; y++)
                                    rerolling = numStr.charAt(y);
                                 //create another mwthod later.
                                    switch (rerolling)
                                         case '1':
                                              numDie[0] =  die1.roll();
                                              break;
                                         case '2':
                                              numDie[1] =  die1.roll();
                                              break;
                                         case '3':
                                              numDie[2] =  die1.roll();
                                              break;
                                         case '4':
                                              numDie[3] =  die1.roll();
                                              break;
                                         case '5':
                                              numDie[4] =  die1.roll();
                                              break;
                                         default:
                                         t = maxRoll;//to be changed
                                    } //end of switch class
                              }//end of reroll for loop
                                   JOptionPane.showMessegeDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
                                                                                      + "\nDie1: " + numDie[0]
                                                                                          + "\nDie2: " + numDie[1]
                                                                                          + "\nDie3: " + numDie[2]
                                                                                          + "\nDie4: " + numDie[3]
                                                                                          + "\nDie5: " + numDie[4]
                                                                                          + "\nWhich dice do you want to reroll"
                                               switch (rerolling)
                                         case '1':
                                              numDie[0] =  die1.roll();
                                              break;
                                         case '2':
                                              numDie[1] =  die1.roll();
                                              break;
                                         case '3':
                                              numDie[2] =  die1.roll();
                                              break;
                                         case '4':
                                              numDie[3] =  die1.roll();
                                              break;
                                         case '5':
                                              numDie[4] =  die1.roll();
                                              break;
                                         default:
                                         t = maxRoll; //not really anything yet, or is it?
                                    } //end of rerolling switch class
                                       //categorychoice = Integer.parseInt(category);
                              }//end of t for loop            
                   }//end of player for loop.

    samuraiexe wrote:
    well, i should have said it is a yahtzee program, and i ask the user what they want to reroll and whatever number they press, the switch will activate the case and the array that it will reroll.
    HOw would i pass it as an argument?You put it in the argument list. Modifying your original code a bit:
    public static void switchReroll (int[] dice, int position) {
         switch (position) {
         case '1':
                 dice[0] =  die1.roll()
                 break;
         case '2':
                 dice[1] =  die1.roll();
                 break;
         case '3':
                 dice[2] =  die1.roll();
                     break;
         case '4':
                 dice[3] =  die1.roll();
                 break;
         case '5':
                  dice[4] =  die1.roll();
                 break;
         default:
                 t = maxRoll;//to be changed
        } //end of switch
    }which you could then call as this:
    switchReroll(numDie, reroll);Note that your code still isn't done; the above won't compile. This is just an example of how you could pass the stuff as an argument (and note how the values have different names in the main method than in the switchReroll method -- this works, but also note that it's the same array of ints in both).
    By the way -- you really don't need a switch statement for this. You can do the same thing with a couple lines of code, which would lessen the advantage for a separate method. But I'd suggest continuing down this path, and then you could change the implementation of the method later.

  • Help with BufferedImage and JPanel

    I have a program that should display some curves, but thats not the problem, the real problem is when i copy the image contained in the JPanel to the buffered image then i draw something there and draw it back to the JPanel. My panel initialy its white but after the operation it gets gray
    Please if some one could help with this
    here is my code divided in three classes
    //class VentanaPrincipal
    package gui;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    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.image.BufferedImage;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.border.LineBorder;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo is being used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class VentanaPrincipal extends javax.swing.JFrame {
              //Set Look & Feel
              try {
                   javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch(Exception e) {
                   e.printStackTrace();
         private JMenuItem helpMenuItem;
         private JMenu jMenu5;
         private JMenuItem deleteMenuItem;
         private JSeparator jSeparator1;
         private JMenuItem pasteMenuItem;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel3;
         private JLabel jLabel2;
         private JLabel jLabel1;
         private JButton jSPLineButton;
         private JButton jHermiteButton;
         private JButton jBezierButton;
         private JPanel jPanel2;
         private JPanel jPanel1;
         private JMenuItem jResetMenuItem1;
         private JMenuItem copyMenuItem;
         private JMenuItem cutMenuItem;
         private JMenu jMenu4;
         private JMenuItem exitMenuItem;
         private JSeparator jSeparator2;
         private JMenu jMenu3;
         private JMenuBar jMenuBar1;
          * Variables no autogeneradas
         private int botonSeleccionado;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              VentanaPrincipal inst = new VentanaPrincipal();
              inst.setVisible(true);
         public VentanaPrincipal() {
              super();
              initGUI();
         private void initGUI() {
              try {
                        this.setTitle("Info3 TP 2");
                             jPanel1 = new pizarra();
                             getContentPane().add(jPanel1, BorderLayout.WEST);
                             jPanel1.setPreferredSize(new java.awt.Dimension(373, 340));
                             jPanel1.setMinimumSize(new java.awt.Dimension(10, 342));
                             jPanel1.setBackground(new java.awt.Color(0,0,255));
                             jPanel1.setBorder(BorderFactory.createCompoundBorder(
                                  new LineBorder(new java.awt.Color(0, 0, 0), 1, true),
                                  null));
                             BufferedImage bufimg = (BufferedImage)jPanel1.createImage(jPanel1.getWidth(), jPanel1.getHeight());
                             ((pizarra) jPanel1).setBufferedImage(bufimg);
                             jPanel2 = new JPanel();
                             getContentPane().add(jPanel2, BorderLayout.CENTER);
                             GridBagLayout jPanel2Layout = new GridBagLayout();
                             jPanel2Layout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
                             jPanel2Layout.rowHeights = new int[] {69, 74, 76, 71};
                             jPanel2Layout.columnWeights = new double[] {0.0, 0.0, 0.1};
                             jPanel2Layout.columnWidths = new int[] {83, 75, 7};
                             jPanel2.setLayout(jPanel2Layout);
                                  jBezierButton = new JButton();
                                  jPanel2.add(jBezierButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jBezierButton.setText("Bezier");
                                  jBezierButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jBezierButton.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent evt) {
                                            bezierActionPerformed();
                                  jHermiteButton = new JButton();
                                  jPanel2.add(jHermiteButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jHermiteButton.setText("Hermite");
                                  jHermiteButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jSPLineButton = new JButton();
                                  jPanel2.add(jSPLineButton, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jSPLineButton.setText("SP Line");
                                  jSPLineButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jLabel1 = new JLabel();
                                  jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                                  jLabel1.setText("Posicion Mouse");
                                  jLabel2 = new JLabel();
                                  jPanel2.add(jLabel2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel2.setText("X:");
                                  jLabel3 = new JLabel();
                                  jPanel2.add(jLabel3, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel3.setText("Y:");
                                  jLabel4 = new JLabel();
                                  jPanel2.add(jLabel4, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel4.setText("-");
                                  jLabel5 = new JLabel();
                                  jPanel2.add(jLabel5, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel5.setText("-");
                   this.setSize(600, 400);
                        jMenuBar1 = new JMenuBar();
                        setJMenuBar(jMenuBar1);
                             jMenu3 = new JMenu();
                             jMenuBar1.add(jMenu3);
                             jMenu3.setText("Archivo");
                                  jSeparator2 = new JSeparator();
                                  jMenu3.add(jSeparator2);
                                  exitMenuItem = new JMenuItem();
                                  jMenu3.add(exitMenuItem);
                                  exitMenuItem.setText("Exit");
                                  jResetMenuItem1 = new JMenuItem();
                                  jMenu3.add(jResetMenuItem1);
                                  jResetMenuItem1.setText("Reset");
                             jMenu4 = new JMenu();
                             jMenuBar1.add(jMenu4);
                             jMenu4.setText("Edit");
                                  cutMenuItem = new JMenuItem();
                                  jMenu4.add(cutMenuItem);
                                  cutMenuItem.setText("Cut");
                                  copyMenuItem = new JMenuItem();
                                  jMenu4.add(copyMenuItem);
                                  copyMenuItem.setText("Copy");
                                  pasteMenuItem = new JMenuItem();
                                  jMenu4.add(pasteMenuItem);
                                  pasteMenuItem.setText("Paste");
                                  jSeparator1 = new JSeparator();
                                  jMenu4.add(jSeparator1);
                                  deleteMenuItem = new JMenuItem();
                                  jMenu4.add(deleteMenuItem);
                                  deleteMenuItem.setText("Delete");
                             jMenu5 = new JMenu();
                             jMenuBar1.add(jMenu5);
                             jMenu5.setText("Help");
                                  helpMenuItem = new JMenuItem();
                                  jMenu5.add(helpMenuItem);
                                  helpMenuItem.setText("Help");
              } catch (Exception e) {
                   e.printStackTrace();
         private void bezierActionPerformed(){
              botonSeleccionado = 1;
              ((pizarra) jPanel1).setTipoFigura(botonSeleccionado);
              ((pizarra) jPanel1).pintarGrafico();
    //class graphUtils
    package func;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.image.BufferedImage;
    public class graphUtils {
         public static void dibujarPixel(BufferedImage img, int x, int y, int color){
              img.setRGB(x, y, color);
         public static void dibujarLinea(BufferedImage img, int x0, int y0, int x1, int y1, int color){
            int dx = x1 - x0;
            int dy = y1 - y0;
            if (Math.abs(dx) > Math.abs(dy)) {          // Pendiente m < 1
                float m = (float) dy / (float) dx;     
                float b = y0 - m*x0;
                if(dx < 0) dx = -1; else dx = 1;
                while (x0 != x1) {
                    x0 += dx;
                    dibujarPixel(img, x0, Math.round(m*x0 + b), color);
            } else
            if (dy != 0) {                              // Pendiente m >= 1
                float m = (float) dx / (float) dy;
                float b = x0 - m*y0;
                if(dy < 0) dy = -1; else dy = 1;
                while (y0 != y1) {
                    y0 += dy;
                    dibujarPixel(img, Math.round(m*y0 + b), y0, color);
         public static void dibujarBezier(BufferedImage img, Point puntos, int color){
    //class pizarra
    package gui;
    import javax.swing.*;
    import sun.awt.VerticalBagLayout;
    import sun.security.krb5.internal.bh;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import func.graphUtils;
    * esta clase pizarra extiende la clase JPanel y se agregan las funciones de pintado
    * y rellenado que se muestra en pantalla dentro del panel que se crea con esta clase
    * @author victorg
    public class pizarra extends JPanel implements MouseListener{
         private int tipoFigura;
         BufferedImage bufferImagen;
         Image img;
         Graphics img_gc;
         private Color colorRelleno, colorLinea;
         private Point puntosBezier[] = new Point[3];
         public pizarra(){
              super();          
              addMouseListener(this);
              //this.setBackground(Color.BLUE);
              colorLinea = Color.BLUE;
         public void setTipoFigura(int seleccion){
              // se setea para ver si es bezier, hermite, SP line
              tipoFigura = seleccion;
         public void setTipoRelleno(int seleccion){
         public void setColorRelleno(Color relleno){
              colorRelleno = relleno;          
         public void setColorLinea(Color linea){
              colorLinea = linea;
         public void setBufferedImage(BufferedImage bufimg){
              bufferImagen = bufimg;
         public void pintarGrafico(){
              Graphics g = this.getGraphics();     
              g.setColor(colorLinea);
              //accion ejecutada cuando se selecciona para graficar un poligono
              if(tipoFigura == 1){// bezier
                   if(bufferImagen == null){
                        //mantiene guardada la imagen cuando la pantalla pasa a segundo plano
                        bufferImagen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                        this.setBackground(Color.WHITE);                                                  
                        bufferImagen = (BufferedImage)createImage(getWidth(), getHeight());
                        //bufferImagen = this.createImage(getWidth(), getHeight());
                   //g.drawImage(bufferImagen,0,0,this);
                   graphUtils.dibujarLinea(bufferImagen,10, 10, 50, 50, colorLinea.getRGB());
                   g.drawImage(bufferImagen,0,0,this);
         protected void paintComponent(Graphics g) { // llamado al repintar
              //setBackground(colorFondo);
              super.paintComponent(g);
    //          Graphics2D g2 = (Graphics2D)g;          
    //          g2.drawImage(bufferImagen, 0,0, this);          
    //          g2.dispose();     
         public void mouseClicked(MouseEvent arg0) {          
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
    }

    1) Swing related questions should be posted in the Swing forum.
    Custom painting should be done in the paintComponent(..) method. You created a "pintarGraphico" method to do the custom painting, but that method is only execute once. When Java determines that the panel needs to be repainted, the paintComponent() method is executed which simply does a super.paintComponent(), which in turn simply paints the background of the panel overwriting you custom painting.

  • Help with JLabels and JTextFields

    I'm experimenting with JLabels and JTextFields in a basic JFrame. What I am trying to accomplish (without success) is to align a JLabel above and centered on a JTextField. The tutorials are confusing me. Any help would be greatly appreciated. a Sample of code is ...
    JLabel  myTextLabel = new JLabel("Who's text Field?");
    JTextField myTextField = new JTextField("My Text Field");...after reading the tutorial I thought that I needed to assign L&F variables to the JLabel ... i.e.
    JLabel myTextLabel = new JLabel("Who's text field?:", JLabel.CENTER, JLabel.TOP); but this results in an error when compiling. (cannot find symbol), so I thought I need to assign the JLabel to the JTextField. i.e.
    myTextLabel.setLabelFor(myTextField);Then I get "identifier" expected. So now being completely confused I am here asking "How do I?" :)
    Thanks in advance!

    Most likely, you need to think a little more about using a layout manager to hlp you along the way. If memory serves, the default layout manager for a JPanel is FlowLayout and that will simply place the components you add to the panel one after another and allow each to adopt it's preferred size.
    One way to ensure that the two compoenets were sized equally, would be to use the GridLayout layout manager and create either one row with two columns, or two rows with one column on each. Then add the compoennets to each of the 'cells' so to speak and that should ensure that they are both the same size.
    As to making the text centered in each, both the JLabel and JtextField classes have amethod called setHorizontalAlignment(); it can be used to aligh the text as you require.
    Simply create an instance of the class;
    JLabel aLabel = new JLabel("Some Text");
    // Then set the alignment
    aLabel.setHorizontalAlignment(SwingConstants.CENTER);Or, do the whole operation i one step
    JLabel aLabel = new JLabel("Sone Text", SwingConstants.CENTER);and then add the componenet to the panel once you have set the layout manager.
    Remember that the label.textfield will have to be wide enought to make it obvious that the text is centered!

  • Help with treemap and other stuff

    hi guys..
    i m new to this forum..
    and this is my first post....so if i act a little naive .....please bare with me.
    and if this is not the correct place to post ..i m sorry for that.
    i have an assignment to submit....i m getting the whole picture ....but not sure how to go about implementing it.
    here it is...
    Write an Object Oriented solution to the problem in Java. The solution is to consist of:
    A TableIndex class
    A TableNavigator Interface
    A data row class ....class that i have to create.
    An application class to use and test your TableIndex class
    The following UML class diagrams show the public methods of the classes. Other methods may be specified. Specify data members, inner classes and interfaces as appropriate.
    TableIndex Class
    The TableIndex class is an index to a collection of objects. The class is to approximate an index to a data table in memory that consists of a number of rows. To control access to the index a current row is defined that specifies the row that can be accessed. To retrieve a row from the index it must be the current row. The get() method is the only method in TableIndex class that retrieves a row from the index. The current row can be changed explicitly using the methods: previous(), next(), first(), last(), gotoBookmark and find(K); and implicitly using insert(K, V), modify(K, V) and remove().
    The TableIndex class is to be implemented using the java API's TreeMap class and must use Generics. The data types K and V below are generic types for the Key and Value (row) respectively. An important aspect of the assignment is using the Java API documentation to understand the TreeMap class.
    guys ....can u plz help with the starting bit ..
    what should be the opening statement of the class...
    public class TableIndex<K , V> .....????
    and what should be the treemap declaration..??
    TreeMap<K , V> indexTable = new TreeMap<K , V>();...???
    i m confused....
    can u plz explain to me..

    hi mate.....didnt quite get you..
    can u plz be a bit more simple in explanation..!!!
    i will post the whole question ..so that anyone reading will understand better....
    Problem Description
    You are to develop an index class and associated classes.
    Requirements
    Write an Object Oriented solution to the problem in Java. The solution is to consist of:
    A TableIndex class
    A TableNavigator Interface
    A data row class
    An application class to use and test your TableIndex class
    The following UML class diagrams show the public methods of the classes. Other methods may be specified. Specify data members, inner classes and interfaces as appropriate.
    TableIndex Class
    The TableIndex class is an index to a collection of objects. The class is to approximate an index to a data table in memory that consists of a number of rows. To control access to the index a current row is defined that specifies the row that can be accessed. To retrieve a row from the index it must be the current row. The get() method is the only method in TableIndex class that retrieves a row from the index. The current row can be changed explicitly using the methods: previous(), next(), first(), last(), gotoBookmark and find(K); and implicitly using insert(K, V), modify(K, V) and remove().
    The TableIndex class is to be implemented using the java API's TreeMap class and must use Generics. The data types K and V below are generic types for the Key and Value (row) respectively. An important aspect of the assignment is using the Java API documentation to understand the TreeMap class.
    TableIndex
    +TableIndex()
    +TableIndex(name: String, comp: Comparator)
    +getName(): String
    +isEmpty(): Boolean
    +size(): Integer
    +hasPrevious(): Boolean
    +hasNext(): Boolean
    +previous()
    +next()
    +first()
    +last()
    +setBookmark(): Boolean
    +clearBookmark()
    +gotoBookmark(): Boolean
    +contains(key: K): Boolean
    +find(key: K): Boolean
    +get(): V
    +insert(key:K, value: V): Boolean
    +modify(value: V): Boolean
    +modify(key: K, value: V): Boolean
    +remove(): V
    +iterator(): Iterator
    +equals(obj2: Object): Boolean
    +toString(): String
    Additional Notes:
    The table index has an order defined by the compareTo method of the key's class or by the compare method specified in the class that implements the Comparator interface.
    getName(): the name of the index, blank by default.
    isEmpty(): returns true if there aren't any rows in the table index
    size(): returns the number of rows in the table index
    hasPrevious(): returns true if there is a row before the current row.
    hasNext(): returns true if there is a row after the current row in sequence.
    previous(): if there is a row before the current row, move to the row and make it the new current row.
    next() if there is a row after the current row, move to the row and make it the new current row.
    first(): if the table isn't empty, move to the first row and make it the new current row.
    last(): if the table isn't empty, move to the last row and make it the new current row.
    setBookmark(): sets a bookmark at the current row. If the bookmark is successfully set the method returns true. The bookmark is cleared if the TableIndex is empty or the row the bookmark was set on is deleted..
    clearBookmark(): sets the bookmark to null, indicating there isn't a bookmark.
    gotoBookmark(): if a bookmark has been set, go to the bookmarked row. If successful the book marked row becomes the current row and the method returns true.
    contains(K): return true if a row with the key specified exists.
    find(K): if a row is found with the specified key, the current row is set to the row found.
    get(): returns the current row. Null is returned if there isn't a current row.
    insert(K, V): inserts a row (value) with the key specified. The key must not be null and must be unique (not already in the TableIndex). The row (value) must not be null. If the row is successfully inserted true is returned, and the row becomes the current row..
    modify(V): change the current row's data to the row (value) specified. The key and the current row key are to remain the same. If successful true is returned.
    modify(K, V): change the current row's key and data to the key and row (value) specified. If successful the changed row becomes the new current row. If successful true is returned. Note: this is more difficult than modify(V).
    remove(): remove the current row. When a row is deleted the next row (if available) becomes the current row, otherwise if there isn't a next row the previous row becomes the current row, otherwise the table is empty therefore the current row is null.
    iterator(): returns an iterator to the rows (values) in the index. The rows are to be retrieved in order. The remove method does not need to be implemented (its method body can be empty)..
    the equals method uses the name, and the rows (values) in order when testing for equality.
    the toString method should return appropriately formatted data members and the rows (values/data) in the index.
    TableNavigator Interface
    «interface»
    TableNavigator
    +isEmpty(): Boolean
    +hasPrevious(): Boolean
    +hasNext(): Boolean
    +previous()
    +next()
    +first()
    +last()
    +contains(key: K): Boolean
    +find(key: K): Boolean
    Additional Notes:
    The TableIndex class implements the TableNavigator Interface.
    The purpose of the above methods is outlined in the TableIndex class.
    Your Data Row Class
    You are to include a class of your own to represent a row of data in the TableIndex. This is not to be a class that was covered in other programming subjects. It does not need to be complex but must include a range of data types. This class will be used to test your TableIndex class. The class should have an appropriate name and deal with something of interest to you.
    Your Application Class
    The application class is to make use of the TableIndex class and your data row class. It is to clearly show how the TableIndex class is used, and in doing so, test it. The class should have an appropriate name. The application class should create two indexes of different key data types. One of the indexes must make use of the Comparator interface to have a key that is in descending order.
    Output
    Output in the test classes/programs is to go to standard out or a text file. There should be no output from the TableIndex class or your data row class. A GUI interface is NOT required. There is no need to input data from the keyboard or file. Use the Unix script command or write output to a text file (etc) to provide example runs of your test programs.

  • Help with TYPE and LIKE statements

    HI guys,
    I know this is really novice stuff, but I am a little confused.
    Can anyone please explain the exact difference between TYPE and like with the help of a program, to understand it.
    What situation would demand the use of each of the LIKE statement, since I can do all these things using the TYPE ?

    Hi Akhil,
    I summarized the info in SDN posts and SAP Help, to make it easier for you to understand. I also included some code snippets. Hope these prove to be helpful to you.
    The following is from SAP Help:
    The Additions TYPE and LIKE
    The additions TYPE type and LIKE dobj are used in various ABAP statements. The additions can have various meanings, depending on the syntax and context.
    ·        Definition of local types in a program
    ·        Declaration of data objects
    ·        Dynamic creation of data objects
    ·        Specification of the type of formal parameters in subroutines
    ·        Specification of the type of formal parameters in methods
    ·        Specification of the type of field symbols
    A known data type can be any of the following:
    ·        A predefined ABAP type to which you refer using the TYPE addition
    ·        An existing local data type in the program to which you refer using the TYPE addition
    ·        The data type of a local data object in the program to which you refer using the LIKE addition
    ·        A data type in the ABAP Dictionary to which you refer using the TYPE addition. To ensure compatibility with earlier releases, it is still possible to use the LIKE addition to refer to database tables and flat structures in the ABAP Dictionary. However, you should use the TYPE addition in new programs.
    The LIKE addition takes its technical attributes from a visible data object. As a rule, you can use LIKE to refer to any object that has been declared using DATA or a similar statement, and is visible in the current context.  The data object only has to have been declared. It is irrelevant whether the data object already exists in memory when you make the LIKE reference.
    ·        In principle, the local data objects in the same program are visible. As with local data types, there is a difference between local data objects in procedures and global data objects. Data objects defined in a procedure obscure other objects with the same name that are declared in the global declarations of the program.
    ·        You can also refer to the data objects of other visible ABAP programs. These might be, for example, the visible attributes of global classes in class pools. If a global class cl_lobal has a public instance attribute or static attribute attr, you can refer to it as follows in any ABAP program:
    DATA dref TYPE REF TO cl_global.
    DATA:  f1 LIKE cl_global=>attr,
           f2 LIKE dref->attr.
    You can access the technical properties of an instance attribute using the class name and a reference variable without first having to create an object. The properties of the attributes of a class are not instance-specific and belong to the static properties of the class.
    Example
    TYPES: BEGIN OF struct,
             number_1 TYPE i,
             number_2 TYPE p DECIMALS 2,
           END OF struct.
    DATA:  wa_struct TYPE struct,
           number    LIKE wa_struct-number_2,
           date      LIKE sy-datum,
           time      TYPE t,
           text      TYPE string,
           company   TYPE s_carr_id.
    This example declares variables with reference to the internal type STRUCT in the program, a component of an existing data object wa_struct, the predefined data object SY-DATUM, the predefined ABAP type t and STRING, and the data element S_CARR_ID from the ABAP Dictionary.
    The following info is from various posts:
    --> Type: It is used when userdefined object link with SAP system data type.
    Local types mask global types that have the same names. When typing the interface parameters or field symbols, a reference is also possible to generic types ANY, ANY TABLE,INDEX TABLE, TABLE or STANDARD TABLE, SORTED TABLE and HASHED TABLE.
    --> Like: It is when data object link with the other data object.
    --> TYPE, you assign datatype directly to the data object while declaring.
    --> LIKE,you assign the datatype of another object to the declaring data object. The datatype is referenced indirectly.
    you can refer to all visible data objects at the ABAP program's positon in question. Only the declaration of the data object must be known. In this case it is totally irrelevant whether the data object already exists physically in
    memory during the LIKE reference. Local data objects mask global data objects that have the same name.
    --> Type is a keyword used to refer to a data type whereas Like is a keyword used to copy the existing properties of already existing data object.
    Types: var1(20) type c.
    data: var2 type var1. ( type is used bcoz var1 is defined with TYPES and it
    does not occupy any memory spce.
    data: var3 like var2. ( like is used here bcoz var2 is defined with DATA
    so it does occupy space in memory ).
    data: material like mara-matnr. ( like is used here bcoz mara-matnr is stored in memory)
    --> Type refers the existing data type
    --> Like refers the existing data object
    Please Reward Points if any of the above points are helpful to you.
    Regards,
    Kalyan Chakravarthy

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

Maybe you are looking for