Hashmap from user input

I am writing a battleship program and I have created an array of xycoordinates in my board class, in my player class i created a method to accept user input for an xy coordinate to place the ship. In my game class (where the main method is in) I want to be able to put this coordinate in the ship hashmap with the ship name.
I am not sure how to get the user input from my method in the player class to the hashmap in the game class.

I was originally calling this method when the player selected to play the game. I have created the method in my player class:
public String placeBships() {
          System.out.println("Enter xy coordinates for: Battleship");
          Scanner blocationxy = new Scanner(System.in);
          String bxycoordinate;
          bxycoordinate = blocationxy.next();
          System.out.println("You Chose " + bxycoordinate);
          return bxycoordinate;
how do make it return to the Game class?
I am not sure how to load it to my hashmap "ships". I tried ships.put(myplayer.placeBships());

Similar Messages

  • How to update jTable from user input?

    I create one jTable with 2 rows and 3 columns. the jtable colums contains deviceIP and Status. I am getting device IP from user input through jTextfield. so, when user enter IP and click add button, it must added in the jTable rows one by one.
    how can I add it by user enter the IP. Also, I want to update the status column value by "UP" or "DOWN" by just getting string value from other function.
    but, my problem is i need to update the correct IP status value to correct column (ie., I want to put IP 1(row 1) status to column 1 in status column list.
    I don't know about jTable .
    If any one have any examples please give me.

    use
    ((DefaultTableModel)jTable.getModel()).addRow(Object[]);
    Object[] is the array of row data values you want to insert;

  • How to check the value from user input in database or not?

    Hello;
    I want to check the value of user input from JtextFiled in my database or not.
    If it is in database, then i will pop up a window to tell us, otherwise, it will tell us it is not in database.
    My problem is my code do not work properly, sometimes, it tell me correct information, sometime it tell wrong information.
    Could anyone help,please.Thanks
    The following code is for check whether the value in database or not, and pop up a window to tell us.
    while( rs.next()) {
                    System.out.println("i am testing");
                    bInt=new Integer(rs.getInt("id"));
                    if(aInt.equals(bInt)){ // If i find the value in data base, set flag to 1.
                  flag=1;  //I set a flag to check whether the id in database or not
                        break;
             System.out.println("falg" + flag);
                if(flag==1){ //?????????????????????
              String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
              String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
              String remove3 = "DELETE FROM Customer WHERE id=" +a;
              s.executeUpdate(remove1);
              s.executeUpdate(remove2);
              s.executeUpdate(remove3);
                    JOptionPane.showMessageDialog(null,"you have success delete the value");
              s.close();
             else//???????????????????????????????
                  JOptionPane.showMessageDialog(null,"I could not found the value"); -------------------------------------------------------------------
    My whole program
    import java.sql.*;
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class DeleteC extends JFrame
        public static int index=0;   
        public static ResultSet rs;
        public static Statement s;
        public static Connection c;
        public static  Object cols[][];
        private static JTable table;
        private static JScrollPane scroller;
        private static int flag=0;
        public DeleteC()
            //information of our connection
            //the url of the database: protocol:subprotocol:subname:computer_name:port:database_name
            String strUrl      = "jdbc:oracle:thin:@augur.scms.waikato.ac.nz:1521:teaching";
            //user name and password
            String strUser      = "xbl1";
            String strPass      = "19681978";
            //try to load the driver
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            catch (ClassNotFoundException e) {
                System.out.println( "Cannot load the Oracle driver. Include it in your classpath.");
                System.exit( -1);
            //a null reference to a Connection object
            c = null;
            try {
                //open a connection to the database
                c = DriverManager.getConnection( strUrl, strUser, strPass);
            catch (SQLException e) {
                System.out.println("Cannot connect to the database. Here is the error:");
                e.printStackTrace();
                System.exit( -1);
           //create a statement object to execute sql statements
        public void getData(String a){
            try {
             //create a statement object to execute sql statements
             s = c.createStatement();
                int index=0;
                Integer aInt= Integer.valueOf(a);
                Integer bInt;
                  //our example query
                String strQuery = "select id from customer";
                //execute the query
                ResultSet rs = s.executeQuery( strQuery);
                //while there are rows in the result set
                while( rs.next()) {
                    System.out.println("i am testing");
                    bInt=new Integer(rs.getInt("id"));
                    if(aInt.equals(bInt)){
                  //JOptionPane.showMessageDialog(null,"I found the value"); 
                  flag=1;
                        break;
             System.out.println("falg" + flag);
                if(flag==1){
              String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
              String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
              String remove3 = "DELETE FROM Customer WHERE id=" +a;
              s.executeUpdate(remove1);
              s.executeUpdate(remove2);
              s.executeUpdate(remove3);
                    JOptionPane.showMessageDialog(null,"you have success delete the value");
              s.close();
             else
                  JOptionPane.showMessageDialog(null,"I could not found the value");
            catch (SQLException e) {
                 JOptionPane.showMessageDialog(null,"You may enter wrong id");
    My main program for user input from JTextField.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.util.*;
    public class EnterID extends JFrame{
        public JTextField tF1;
        public EnterID enID;
        public String tF1Value;
        private JLabel label1, label2, label3;
        private static JButton button;
        private static ButtonHandler handler;
        private static String aString;
        private static Integer aInteger;
        private static Integer checkV=0;
        public static void main(String args[]){
           EnterID eId= new EnterID();
       public EnterID(){
          handler=new ButtonHandler();
          Container c= getContentPane();
          c.setLayout(new GridLayout(3,1));
          button= new JButton("ok");
          button.addActionListener(handler);
          label1 = new JLabel(" CustomerID, Please");
          label2 = new JLabel("Label2");
          label3 = new JLabel();
          label3.setLayout(new GridLayout(1,1));
          label3.add(button);
          label2.setLayout(new GridLayout(1,1));
          aString = "Enter Id Here";
          tF1 = new JTextField(aString);
          label2.add(tF1);
          c.add(label1);
          c.add(label2);         
          c.add(label3);            
          setSize(150,100);
          setVisible(true);     
       private class ButtonHandler implements ActionListener{
         public void actionPerformed(ActionEvent event){
             tF1Value=tF1.getText();
            //   CheckData cData = new CheckData();
             //  aInteger = Integer.valueOf(tF1Value);      
             if(tF1Value.equals(aString)){
              JOptionPane.showMessageDialog(null,"You didn't type value into box");
              setVisible(false); 
            else {
                DeleteC dC= new DeleteC();
                dC.getData(tF1Value);
                setVisible(false); 
    }

    You may have working code now, but the code you posted is horrible and I'm going to tell you a much much much better approach for the JDBC part. (You should probably isolate your database code from your user interface code as well, but I'm skipping over that structural problem...)
    Do this instead:
        public void getData(String a){
            PreparedStatement p;
            String strQuery = "select count(*) the_count from customer where id = ?";
            try {   
             //create a prepared statement object to execute sql statements, it's better, faster, safer
             p = c.prepareStatement(strQuery);
                // bind the parameter value to the "?"
                p.setInt(1, Integer.parseInt(a) );
                //execute the query
                ResultSet rs = p.executeQuery( );
                // if the query doesn't throw an exception, it will have exactly one row
                rs.next();
                System.out.println("i am testing");
                if (rs.getInt("the_count") > 0 ) {
                // it's there, do what you need to...
             else
                  JOptionPane.showMessageDialog(null,"I could not find the value");
            catch (SQLException e) {
                 // JOptionPane.showMessageDialog(null,"You may enter wrong id");
                 // if you get an exception, something is really wrong, and it's NOT user error
            // always, always, ALWAYS close JDBC resources in a finally block
            finally
                p.close();
        }First, this is simpler and easier to read.
    Second, this retrieves just the needed information, whether or not the id is in the database. Your way will get much much slower as more data goes into the database. My way, if there is an index on the id column, more data doesn;t slow it down very much.
    I've also left some important points in comments.
    No guarantees that there isn't a dumb typo in there; I didn't actually compile it, much less test it. It's at least close though...

  • How to calculate the total from users input in switch?

    I dont know how to hold the input from user. But here is part of my coding :
    System.out.println ("Type 1 for buying Ruler"+
    "\nType 2 for buying Pencil");
    stationaries = console.nextInt();
    switch (stationaries)
    case 1 : System.out.println("Ruler per unit : MYR1");
    System.out.println("How much does you want? : ")
    wantRuler = console.nextInt();
    sum = wantRuler * 1;
    break;
    case 2 : System.out.println("Pencil per unit : MYR2");
    System.out.println("How much does you want? : ")
    wantPencil = console.nextInt();
    sum = wantPencil * 2;
    break;
    How can I calculate the total for both of the stationaries if user wants 5 for ruler and 6 for pencil?

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.

  • Set Assigned to in case from user input form

    Hi there
    Can anyone tell me if you can set the case Assigned to property from a user input field.
    Like you can set a category <input type="text" value="Client App id tag" maxlength="255" id="CAT_Category" name="CAT_Category" class="cat_textbox_small" />
    Maybe cat_assignedTo ?
    Cheers Daniel

    Hi Octopuse,
    Please check if you defined the object type in the form
        <action type="add">
          <form AutoManaged="1" ... ObjectType="NAMESPACE_UserMaster" ... uid="NAMESPACE_FORM">
            <datasources>
    Please keep in mind that table names and user objects should always be prefixed with the partner Namespace.
    Regards,
    Vítor Vieira

  • Slow response from user input

    Hi.
    I have a very strange problem with some of my clients. Sometimes they experience a huge delay between key pressed on keyboard and actual character printed on monitor. So there is a simple text item involved and when the user starts typing the delay could be two or even three seconds between user input (each character) and actual forms displaying it.
    First I suspected network contention but I am not quite sure if there is any network traffic (client browser -> application server) involved while user is typing text into text item. Next I tried to monitor clients machine processes (like anti virus program) but no luck. I have also tried various JRE versions but again no luck.
    I am using 11.1.2.1 version of forms with Mozilla and JRE 1.6.35 on client side.
    Does anybody have/had similar experience? Any suggestion in helping resolving the issue appreciated.
    Also I am really curious what is happening (is there any network traffic involved) while user is typing text into text item where there is no trigger on that item except when_validate_item.
    Best regards.

    Also I am really curious what is happening (is there any network traffic involved) while user is typing text into text item where there is no trigger on that item except when_validate_item.Unless you have implemented a Java Bean on the item to monitor the keystrokes in the field, no events are trigger by the act of typing characters in a field. The act of typing characters in a field occurs completly on the client - no network traffic at this point. Only when a field event occurs (navigation away from the item) will an event occur that would cause network communication between the client and the appilcation server.
    Sometimes they experience a huge delay between key pressed on keyboard and actual character printed on monitor. I encountered something similar to this with a user once who complained about how slow the application ran on their computer. The slowness was intermitant and there was no apparent pattern. Like you, I looked at JRE and other things. Finally, told the user to call me when the slowness occured so I could come look at the computer while it was occuring. Turns out, the user had at least 30+ applications running at the same time. The workstation was running Windows XP with 2gb Ram. Looking at their system resources, there was no memory available and the pc was memory thrashing really bad. I had the user close all but the absolute necessary programs and our Forms application started responding quickly again. After a little user education - miraculously, the slowness problem went away. :)
    Craig...

  • Pull/Get Data/Value from User Input Window

    I'm trying to do something that should be be quite basic for a programer, but unfortunately unfortunately being a designer I'm having a heck of a time with this.  Having spent hours searching and trying different things I thought of posting the problem.  I have the feeling I'm not the first designer struggling with this.
    I'm trying to pull input data from a window and pass it on to a variable.  In the script I do a couple of purge(), and I'm not sure if that will clear the user input values during the script, but this is thinking ahead...
    I need values to do:
    layer.translate(X, Y) // If I'm not wrong this needs to be a - string
    bitsaveoptions.method = ChanelScreen; //from drop down menu
    bitsaveoptions.angle = KAngle //  If I'm not wrong this needs to be a - integer
    bitsaveoptions.frequency = ChanelFrequency; //  If I'm not wrong this needs to be a - integer
    bitsaveoptions.resolution = ChanelResolution; //  If I'm not wrong this needs to be a - integer
    bitsaveoptions.shape = BitmapHalfToneType.ROUND; //from drop down menu
    I know that there are different ways to retrieve the data from a window .selection .value and maybe others but I can't seem to pull the data out of from the user input
    Any advice would be greatly appreciated. 
    Thanks.
    PS I'm working with Photoshop CS5
    This is what I have so far.
    // =========== Ruler to Millimiters
    app.preferences.rulerUnits = Units.MM;
    var doc = app.activeDocument;
    var layer = doc.activeLayer;
    var dropdownlistArray = new Array();// The array of drop down lists.
    var chosen_action = null;
    var ScreenShapeArray= new Array(
    'Round',
    'Eliptical'
    var WinContent =
    "dialog{\
        orientation: 'column', \
        alignChildren: ['fill', 'top'],  \
        preferredSize:[300, 130], \
        text: 'Export Settings',  \
        margins:15, \
            Coordinates: Panel {\
            orientation: 'column', \
            text: 'Chanels Shifts', \
            margins:15, \
            alignChildren: 'right',\
                KChanelX: Group{\
                st: StaticText { text: 'X:' }, \
                te: EditText { text: '15', characters: 4, justify: 'right'} \
                st2: StaticText { text: 'mm' }, \
                KChanelY: Group{\
                st: StaticText { text: 'Y:' }, \
                te: EditText { text: '10', characters: 4, justify: 'right'} \
                st2: StaticText { text: 'mm' }, \
        bottomGroup: Group{\
            cancelButton: Button { text: 'Cancel', properties:{name:'cancel'}, size: [120,24], alignment:['right', 'center'] }, \
            applyButton: Button { text: 'Apply', properties:{name:'ok'}, size: [120,24], alignment:['right', 'center'] }, \
    // ======== Create window object
    var win = new Window(WinContent);
    // ======== Display Window
    win.show();
    var X =parseInt(win.Coordinates.KChanelX.te.selection);
    var Y =parseInt(win.Coordinates.KChanelY.te.selection);
    alert (X); // Here I get NaN
    alert (Y); // Here I get NaN
    if (typeof(X) === "undefined" || typeof(Y) === "undefined" ){
    layer.translate(X+"mm", "-"+Y+"mm");
    }else {
    alert ("here"); // Always end-up here regardles of canling or acepting the default values

    .text
    Is what I was looking for!
    Not being so programming savvy, and not knowing the proper terminolgy makes things way harder.
    You asked what the script is for:
    I'm creating an interface to save multiple file from a master file.
    1. Set the bitmap conversion presets (res, screen type, shape, lpi, angle), for the desired chanels to export, set the pages in the book that will be produced, number of signatures, as well as pages per signature.
    2. Create tiffs for every chanlel and move the chanel according to the presets tied to the signature the page belongs to in the book.
    3. Reassemble the chanels into one file for viewning and use the tifs for print.
    Total I will have:
    Myfile_C.tif //Cyan
    Myfile_M.tif //Magenta
    Myfile_Y.tif //Yellow
    Myfile_K.tif //Black
    Myfile_col.psd //CMY chanels reassembled
    Myfile_sep.psd //CMYK chanels reassembled
    Why am I doing all this? I'm working on a comic that will simulate a silver age comic book and I need the look of that time, with off registration plates. But I also need to see the final result of the shift and keep things constant for each plate as I'm working on the separate pages, so series of presets are a must for me.
    If the result of the interface is somewhat acceptable I'll post it.
    Thanks for the help I really apperciate it.

  • Create a timer to make a variable for pause length from user input

    I have an external task that varies in time based on the machine I am using, yet once that value is determined, it will remain the same while on that machine. I need to have an Applescript perform a task based on that time variable. This a repeating loop script that will need user input for the first iteration of the loop. How can I get this time variable to use in the script? I would like it to be something like this.
    --script clicks OK button in the app (this is already scripted)
    --timer started
    --script throws up a dialog instructing user to click OK when hardware specific task is completed (has a cancel option to cancel script as well)
    --when dialog box OK is clicked a time value is determined between the timer started and the dialog OK click
    --time value is now a variable to call for pause between loop cycles, requiring no more user input (except an overall script cancel if needed)
    is this possible?
    PowerBook G4 Titanium 500 Mhz   Mac OS X (10.4.2)  

    Yeah, it's possible. There are probably a couple ways to do it. Here's a quick one that uses a unique hardware ID. Properties persist between runs, reboots, etc. but not compiles.
    click here to open this script in your editor<pre style="font-family: 'Monaco', 'Courier New', Courier, monospace; overflow:auto; color: #222; background: #DDD; padding: 0.2em; font-size: 10px; width:400px">property delay_time : missing value
    property last_mac : missing value
    set test_mac to primary Ethernet address of (system info)
    if test_mac is last_mac and delay_time is not missing value then
    -- performclickhandler()
    delay delay_time
    else
    set start_time to (current date)
    -- performclickhandler()
    display dialog "Click OK to set the timer..."
    set delay_time to (current date) - start_time
    set last_mac to test_mac
    end if
    -- rest of your script
    </pre>

  • Dynamically generating and printing output from user input on pdf form

    Hi Everyone,
    I am consider the purchase of of Designer with the hopes of doing something really simple (and hopefully in a simple way)
    I would like to present the user with a form which they will fill out. On clicking a "submit button", I would like to generate a letter and have it print out based on the information provided in this form (note, the user doesn't ever really even need to see the letter).
    Would Designer be able to do something like this? I have been messing around with the trial version, so I am somewhat familiar with the scrip language. For instance, I am at the point where I would be able to get all the information, and generate the letter in HTML stored in a string object. But I wouldn't know what to do with this string to render and print it.
    Thanks!
    - Dave

    I have just downloaded the trial version of Acrobat 7. It appears that if you want to create a new form, it pretty much brings you to Designer... which is really fine by me.
    I appreciate everyone telling me that it is doable, I'm still left with the problem of what I should actually do to do it! =)
    - Dave

  • Form data from user input

    Hi all,
    I'm working on a site where visitors can rent djs, each dj
    has it's own page (bio photo etc) and a 'Book me' button that opens
    the booking-form. What I want is to automatically fill in the
    selected dj in this form. I think it should be done with php, but
    all suggestions are welcome.
    Thank you all
    Pascal

    alvinhong wrote:
    one question, have you actually tried that using netbeans ide or did you just think that will work?I haven't used Netbeans for more than 5 minutes. I just did a tryout and I have immediately removed it from my PC. I use Eclipse for Java EE.
    if you have tried, you will realize the servlet source code is NOT in the WEB_INFO dir, it's in a different dir and in a different package, which can't be changed, and can't be accessed by specify the path.
    nothing personal, but when you brainlessly accuse some one of "brainlessly ..." maybe you are brainlessly assume you know what the problem is, and brainlessly assume you know what you are doing. some modesty might suit you better. and do you actually know what i meant by drag and drop, maybe you are too brainlessly to ask first and too brainlessly to know.That's how I see drag'n'droppers who came here to ask those kind of very trival questions which are covered by every technical JSP/Servlet tutorial. Sorry about the choice of the word.

  • How to create database from scratch using user input

    what I am trying to do is to create database via my java code (using hibernate and my sql) and based on user input.
    The details like the name of table.... or the number of columns in it are all supposed to be determined from user input (only the first time).
    On subsequent run the program should remember the previously created database and hence work with it.
    Can somebody help me through this?
    Suppose I did create it using firing queries from my program then the next problem is how my program would start up next time......?????

    Anuvrat wrote:
    what I am trying to do is to create database via my java code (using hibernate and my sql) and based on user input.
    The details like the name of table.... or the number of columns in it are all supposed to be determined from user input (only the first time).
    On subsequent run the program should remember the previously created database and hence work with it.
    Can somebody help me through this?Presumably because you want to (fun) rather than because you need to (job or project.)
    If the second then don't do it.
    >
    Suppose I did create it using firing queries from my program then the next problem is how my program would start up next time......?????You would start by learning about DDL which is the common name for the languages, which vary by database, used to create the entities that represent the structure of a database. Until you figure out the syntax of that you can't do anything in java.

  • Check user input

    Have this small script (my first attempt in Scripting), which is loaded with Acrobat 9 at startup.
    app.addMenuItem({ cName: "Gem &KMS-skrivelse", cParent: "File", cExec: "SaveAs('registreringsmeddelelse', 'produkter/')", nPos: 3 });
    app.addMenuItem({ cName: "Gem &dokument i sag", cParent: "File", cExec: "SaveAs('', '')", nPos: 4 });
    function SaveAs(cName, cDirectory)
        //Get full year
        var date=new Date();
        cYear = date.getFullYear();
        //Get year, case number and file name from user input
        var cYear = app.response({ cQuestion: "Indtast sagsår:", cTitle: "Sagsår", cDefault: cYear });
        var cCase = app.response({ cQuestion: "Indtast sagsnr.:", cTitle: "Sagsnr."});
        var cFile = app.response({ cQuestion: "Indtast filnavn (uden .pdf):", cTitle: "Filnavn", cDefault: cName });
        if (cFile == null)
             return;
        //Concatenate path string
        var cPath = "/h/digi/s" + cYear + "/" + cYear + "-" + cCase + "/" + cDirectory + cFile + ".pdf";
        //Try to save the document, if success, inform the user where to
        try {
            this.saveAs({ cPath: cPath, bPromptToOverwrite: true });
            app.alert("Dokumentet blev gemt i " + cPath, 3);
        catch(e) {
            app.alert("Kunne ikke gemme dokument i " + cPath + ". Kontroller at mappen er oprettet, og at du har skriverettigheder til denne, samt at Acrobat/Reader er sat korrekt op.");
        //So long and thanks for all the fish
        return;
    Based on user input it saves documents to folders on a network share.
    It  works just fine, but if the user cancel the input dialog, null is  returned, and eventually will be part of the filename. So I use a if  statement to check if cFile is null, and if true just returns the  function. But this fails with this error message:
    GeneralError: Handlingen mislykkedes.
    Root.(null):17:Menu Gem &dokument i sag:Exec
    script terminated
    Why is this so?
    Best regards
    mp

    The script still continues after return;
    Try this
    app.addMenuItem({ cName: "Gem &KMS-skrivelse", cParent: "File", cExec: "SaveAs('registreringsmeddelelse', 'produkter/')", nPos: 3 });
    app.addMenuItem({ cName: "Gem &dokument i sag", cParent: "File", cExec: "SaveAs('', '')", nPos: 4 });
    function SaveAs(cName, cDirectory)
        //Get full year
        var date=new Date();
        cYear = date.getFullYear();
        //Get year, case number and file name from user input
        var cYear = app.response({ cQuestion: "Indtast sagsår:", cTitle: "Sagsår", cDefault: cYear });
        var cCase = app.response({ cQuestion: "Indtast sagsnr.:", cTitle: "Sagsnr."});
        var cFile = app.response({ cQuestion: "Indtast filnavn (uden .pdf):", cTitle: "Filnavn", cDefault: cName });
       if (cFile == null)
    else
        //Concatenate path string
        var cPath = "/h/digi/s" + cYear + "/" + cYear + "-" + cCase + "/" + cDirectory + cFile + ".pdf";
        //Try to save the document, if success, inform the user where to
        try {
            this.saveAs({ cPath: cPath, bPromptToOverwrite: true });
            app.alert("Dokumentet blev gemt i " + cPath, 3);
        catch(e) {
            app.alert("Kunne ikke gemme dokument i " + cPath + ". Kontroller at mappen er oprettet, og at du har skriverettigheder til denne, samt at Acrobat/Reader er sat korrekt op.");
        //So long and thanks for all the fish
        return;

  • How to deploy a VO Bind variable to get value from user session....

    Hello everbody...
    A JSF Page has a table based on VO with two parameters. One of this parameters I will pass by operation ExecuteWithParams.
    but the other parameter I need to pass a value from User session.
    Is that possible? How would I do that? I´m using jdev10.1.3
    Thankyou...

    When you created a binding for executeWithParams in your pageDef, the action binding should have had NamedData elements for each of the parameters. These would have been assigned values from a variableIterator up in the executables section. The parameter that gets its value from user input should be left alone. For the parameter that gets its value from the user session, change the EL expression that defines its NDValue attribute so that it references the session information that you want to use. This can be a sessionScope variable that you set earlier in the session, as Frank suggests, a property of a managed bean in session scope, or some other variable.

  • Help with JTree data by user input

    I am trying to read data into a JTree without it being hardcoded.
    An example of the data is:
    String data[] = {"a","b","c",";","b","g","h",";","c","t",";","g","u"};
    The above data is taken from user input and stored in an array and checked for errors.
    I want to somehow read take the above array's data and put it into following format in some kind of loop but I am not sure how.
    Object[] hierarchy = {"a", new Object[]{"b",new Object[]{"g","u"},"h"},new Object[]{"c","t"}};
    This Object is then passed to a function that interpets it and prints out the appropriate JTREE structure. For the values above it would be:
    a
    ..b
    ....g
    ......l
    ......u
    ....h
    ..c
    ....t
    Tha problem is how to take the string array and put that data correctly into the Object array. I have been racking my feeble mind for quite sometime and if any one out there can see it or has a better idea of how to get my data into the JTree please let me know.
    Thanks

    //OutlookClient.java
    //uses also Console class from Bruce Eckel 
    //<applet code=OutlookClient width=500 height=300>
    //</applet>
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    import javax.swing.UIManager;
    import javax.swing.SwingUtilities;
    import BruceEckel.*;
    import DynamicTree.*;
    import DynamicTreeNode.*;
    import java.lang.reflect.*;
    /* a class creating a dialog with the version, and other details about the program*/
    class AboutDialog extends JDialog {
         private JButton ok = null;
         private Container cp = null;
         private JTextField tname = null;
            public AboutDialog() {
                   //System.out.println("constructor");
                   ok = new JButton("OK");
                   cp = getContentPane();
                   cp.setLayout(new FlowLayout());
                   JLabel tlab = new JLabel("Outlook - client side");
                   cp.add(tlab);
                   //tname.setMinimumSize(new Dimension(50,10));
                   //tname.setSize(new Dimension(70,10));
                   tlab = new JLabel("Author: Jiri Machotka");
                   cp.add(tlab);
                   tlab = new JLabel("version 1.0 (September 2001)");
                   cp.add(tlab);
                   tlab = new JLabel("----------------------------------------------");
                   cp.add(tlab);
                   ok.addActionListener( new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        dispose();
                      }//actionPerformed
                   });//addActionListener
                   cp.add(ok);
                   setSize(200,150);
                   setTitle("About the program");  
                   setModal(true);
         }//constructor
      *      <P>This class more-or-less contains a graphic design object used for interaction with a user.</P>
      *     Apart from all ScrollPanes, Buttons, and MenuItems, it contains also 3 interesting members:
      *     <ol>
      *     <li> <I>protected final DefaultMutableTreeNode topNode</I>, which is initialized with
      * a potent, non-removable object of the class <I>Node</I>
      *     <li> <I>protected final DefaultTreeModel treeModel</I>, which is initialized with the <I>topNode</I>
      *     <li> and finally <I>protected final DynamicTree dyn_tree</I>, which uses the 2 objects above
      *     </ol>
      *     <P> The <I>OutlookClient</I> is an applet, but it can be also processed as an application (thanks to
      *     a library by BruceEckel).</P>
    public class OutlookClient extends JApplet {
    //------------- properties -----------------------------------------
       private Action
            newMail = new AbstractAction ("New Mail", new ImageIcon("images/NewMailIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("NewMail");
         reply     = new AbstractAction ("Reply", new ImageIcon("images/ReplyIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("Reply");
       private JButton
         /*b1 = new JButton("Add a Node"),
         b2 = new JButton("Remove the current Node"),*/ //not used now
         tb1 = new JButton (newMail),
         tb2 = new JButton (reply);
       private JTextField
         txt = new JTextField(10);
       private Container
         leftArea = new Container(),
         rightArea = new Container();
       private JScrollPane
            left = new JScrollPane (leftArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
            right = new JScrollPane (rightArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
       private JSplitPane
            sp = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, left, right);
       private JToolBar
         toolBar = new JToolBar();
       private JMenuBar
         menuBar = new JMenuBar();
       /*ActionListener al = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String name = ( (JButton)e.getSource()).getText();
            txt.setText(name);
       };*/     //not used now - used as an action listener for buttons b1, b2
       private JMenu
         mainOutlookMenu = new JMenu ("Outlook activities"),
         othersMenu      = new JMenu ("Others"),
         mailMenu     = new JMenu ("Mails"),
         chatMenu     = new JMenu ("Chat"),
         look_and_feelMenu = new JMenu ("Look&Feel");
       private JMenuItem
         closeAppItem     = new JMenuItem ("Exit",KeyEvent.VK_F3),
         newMailItem     = new JMenuItem (newMail),
         replyItem     = new JMenuItem (reply);
       private JRadioButtonMenuItem
         windowsLookAndFeelItem;
       protected final DefaultMutableTreeNode topNode = new DefaultMutableTreeNode(new Node ("Outlook", false, true));
       protected final DefaultTreeModel treeModel = new DefaultTreeModel(topNode);
       protected final DynamicTree dyn_tree = new DynamicTree(topNode, treeModel);
    //-------------inner classes----------------------------------------
    /** <P>The class <I>MyRenderer</I> sets the renderer of the tree - by doing that icons can be assigned to
       * the tree's nodes. </P>
       * <P> It sould be probably a standard member of a class <I>DynamicTreeWithIcons</I>.</P>
       * <P> However, it uses the knowledge that the class <B>Node</B>, which is the only object that can be
       * found in the dynamic tree in this application, has a method <I>getIcon()</I>, which returns a
       * reference to the icon object assigned to the node.</P>
       * <P><B>This is the only place, where the class Node, or its methods are called explicitely.</B></P>
       protected class MyRenderer extends DefaultTreeCellRenderer {
         /** The constructor of the class.
           * - sets folders icons (opened, closed folder)
         public MyRenderer() {
                 //setLeafIcon(new ImageIcon("images/middle.gif")); //for leaves' icon, all at once!
              setOpenIcon(new ImageIcon("images/folder_open.gif"));
              setClosedIcon(new ImageIcon("images/folder_close.gif"));
         /** This overridden method gets the user-specified icon for leaf nodes. */
         public Component getTreeCellRendererComponent(
                   JTree tree,
                   Object value,
                   boolean sel,
                   boolean expanded,
                   boolean leaf,
                   int row,
                   boolean hasFocus) {
              super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
              if (leaf) 
              //workaround: test if icon not eq. null
                     ImageIcon ic = getRightIcon(value);
                     if (ic == null) return this;
                     else
                          setIcon(ic);
              return this;
         }//overridden: getTreeCellRendererComponent
         private ImageIcon getRightIcon(Object value) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              try{
              Node node_object = (Node)(node.getUserObject());   
                 return (node_object.getIcon());
           catch (Exception e) { return null; }
         }// ImageIcon getRightIcon(Object value)
      }//class MyRenderer
    //-------------OutlookClient methods-----------------------------------------
       private void assignListeners(){
         dyn_tree.addTreeSelectionListener(new TreeSelectionListener() {
             public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)dyn_tree.getLastSelectedPathComponent();
              if (node == null) return;
              if (node.isLeaf()) { txt.setText(node.toString()); }
       }//assignListeners()
       private void createLayout(){
         leftArea.setLayout(new BoxLayout(leftArea,BoxLayout.Y_AXIS));
         rightArea.setLayout(new BoxLayout(rightArea,BoxLayout.Y_AXIS));
         //left.setMinimumSize(new Dimension(120,200));
         right.setMinimumSize(new Dimension(50,50));
         //rightArea.add(b1);
         //rightArea.add(b2);
         rightArea.add(txt);
         //leftArea.add(tree);  ... not nice (why?)
           left = new JScrollPane (dyn_tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);       
         left.setMinimumSize(new Dimension(180,200));
         sp.setLeftComponent(left);
       }//createLayout()
       private void createMenu(){
         ButtonGroup group = new ButtonGroup();
            JRadioButtonMenuItem rbMenuItem;
         closeAppItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, ActionEvent.ALT_MASK));
         closeAppItem.getAccessibleContext().setAccessibleDescription("Closes application");
         closeAppItem.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {System.exit(0);}
         othersMenu.setMnemonic(KeyEvent.VK_O);
         othersMenu.getAccessibleContext().setAccessibleDescription("System settings&Others");
            rbMenuItem = new JRadioButtonMenuItem("Java");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_J);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF(UIManager.getCrossPlatformLookAndFeelClassName( ) );}
            look_and_feelMenu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Windows");
            rbMenuItem.setMnemonic(KeyEvent.VK_W);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");}
            look_and_feelMenu.add(rbMenuItem);
         windowsLookAndFeelItem = rbMenuItem;
         look_and_feelMenu.setMnemonic(KeyEvent.VK_L);
         look_and_feelMenu.getAccessibleContext().setAccessibleDescription("Look&Feel");
         JMenuItem aboutItem = new JMenuItem ("About");
         aboutItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   AboutDialog ad = new AboutDialog();
                   ad.show();
         othersMenu.add(look_and_feelMenu);
         othersMenu.addSeparator();
         othersMenu.add(aboutItem);
         othersMenu.addSeparator();
         othersMenu.add(closeAppItem);
         mainOutlookMenu.setMnemonic(KeyEvent.VK_A);
         mainOutlookMenu.getAccessibleContext().setAccessibleDescription("Outlook activities");
         menuBar.add(mainOutlookMenu);
         menuBar.add(othersMenu);
         mailMenu.setMnemonic(KeyEvent.VK_M);
         mailMenu.getAccessibleContext().setAccessibleDescription("Mail activities");
         chatMenu.setMnemonic(KeyEvent.VK_C);
         chatMenu.getAccessibleContext().setAccessibleDescription("Chat");
         chatMenu.setEnabled(false);
         mainOutlookMenu.add(mailMenu);
         mainOutlookMenu.addSeparator();
         mainOutlookMenu.add(chatMenu);
         //mailMenu.add(newMail);
         //mailMenu.add(reply);     //class Action has problems to catch the accelerator keys
         newMailItem.setMnemonic(KeyEvent.VK_N);
         replyItem.setMnemonic(KeyEvent.VK_R);
         mailMenu.add(newMailItem);
         mailMenu.add(replyItem);
         newMailItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
         replyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
         //newMail.putValue(Action.NAME, "New mail");
         //newMail.putValue(Action.SHORT_DESCRIPTION, "New mail");
         //newMail.putValue(Action.LONG_DESCRIPTION, "New mail");
         //newMail.putValue(Action.MNEMONIC_KEY, "N");  //cast an exception. why?
         //newMail.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));     
         setJMenuBar(menuBar);
       }//createMenu()
       private void createToolBar(){
         //toolBar.add(newMail);
         //toolBar.add(reply);    //does not provide texts and mnemonics
         tb1.setMnemonic(KeyEvent.VK_N);
         tb2.setMnemonic(KeyEvent.VK_R);
         toolBar.add(tb1);
         toolBar.add(tb2);
       }//createToolBar()
       private void createNodes(DefaultMutableTreeNode topNode){
         //new for dynamic processing
         DefaultMutableTreeNode
              parentNode = null,
              leaveNode  = null;
         parentNode = dyn_tree.addObject(null,new Node ("MailFolders", false, true));
         dyn_tree.addObject(parentNode,new Node ("Inbox","images/InboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Outbox","images/OutboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Sent","images/SentIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Deleted","images/DeletedIcon.gif", false, false));
         //leaveNode.setEnabled(false);  //TODO: disable "Chat"node
         dyn_tree.addObject(null,new Node ("Chat", false, false));
       }//createcreateNodes(DefaultMutableTreeNode)
       private void setTreeSettings(){
         //one selection at one time
         dyn_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         //connect nodes with a thin line - Java style only
         dyn_tree.putClientProperty("JTree.lineStyle","Angled");
         //collapse the root's children first
         //tree.setShowsRootHandles(false);
         //icon adjustment
         MyRenderer MyRen = new MyRenderer();
         dyn_tree.setCellRenderer(MyRen);
         //modifiable tree - by double click - allows modifying of nodes' names
         // but unfortunately also restores original icons
         //tree.setEditable(true);
       }//setTreeSettings()
       private boolean setPLAF(String LookAndFeelName){
          try{
         UIManager.setLookAndFeel(LookAndFeelName);
         SwingUtilities.updateComponentTreeUI(this);
         return true;
          } catch (Exception e) {
         //e.printStackTrace(System.err);
         return false;
       }//setPLAF(String LookAndFeelName)
       private void trytosetLookAndFeel(){
          if (setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))
              windowsLookAndFeelItem.setSelected(true);
       }//trytosetLookAndFeel()
       /** The applet's <I>init()</I>.
         * Calls methods to construct all visible objects.
         * Apart from that it also assigns the renderer to the tree.
       public void init(){
         sp.setOneTouchExpandable(true);
            //sp.setDividerLocation(150); - system puts the value to optimize the left part
         sp.setPreferredSize(new Dimension(450,200));
         Container cp = getContentPane();
         cp.setLayout(new FlowLayout());
            createLayout();     
         createMenu();
         createToolBar();
         createNodes(topNode);
         setTreeSettings();
         //createPopupMenu();
         assignListeners();
         cp.add(toolBar);
         cp.add(sp);
         trytosetLookAndFeel();
       }//init()
       /** If called as an application.
         * The desired Windows Look&Feel is re-set again, when the applet is running. Otherwise, it in an application
         * it tends not to work correctly.
       public static void main(String[] args) {
         OutlookClient theApplet;
         BruceEckel.Console.run(theApplet=new OutlookClient(), 500, 300);
         theApplet.trytosetLookAndFeel();
       }//main(String[])
    }///:~Take a look namely at createNodes
    Hope it helps.

  • Sum user input

    hi guys, i want to know on how to sum the number from user input. For example,
    Enter your input: 345
    The output will be: 12
    how can i do that? please help me

    Here's a solution
    String input = .... //user input
    int some = 0;
    for(int i=0;i<input.length;i++){
    somme += new Integer(""+input.charAt(i)).intValue();

Maybe you are looking for

  • How to write a specific bytes of a string

    I'm using DataOutputStream object to write a specific string to a file. If I want to write that string to a file with preserving of 20 bytes (for example) as a header of the file. Even though the length of the string can be at any size, I just want i

  • I want to pair my iPhone 3GS (OS 3.1) with my iMac via Bluetooth

    I am a bit disappointed that Bluetooth doesn't seem to be very mature in the iPhone. But maybe I'm just clueless as to how to get it working, and, once it's working, it will be good. My problem is that I can't even discover my iPhone (I have scanned

  • SqlDeveloper copy database

    Hello guys, i am getting crazy. I have an new server with Oracle 11g (11.2.0.1.0) and one (that i have used for testing) with Oracle XE (11.2.0.2.0). Now i want to copy all the data from the testing server to the new server. I tried it with the Datab

  • Cisco Interaction Mangaer 9 java process issue

    Hi All I have installed CIM version 9 but when i start cisco service, javaw processes are not coming UP. from logs i've found the following. also i am attaching the logs for reference. "Failed to launch task :   Description : Failed to execute task t

  • SAP Kernel 6.40 on AIX 5.3

    I am installing SAP 6.40 on AIX 5.3. I was successful in installing SAP Central Instance, but when i am installing Database Instance (Second Step) at 13 phase i.e Prepare Oracle Network Configuration phase the following error is popping up. CJS-00096