How can i pass variables between classes?

Hi.
i have three classes and i need use a variable from 'Battleship' and use it in 'BattleWindow', these summaries of the classes, if anyone could give me a solution without editing it too much it would be greatly appreciated
public class Ship{
public Ship(){
int missilesLeft;
int shots = 10;
for (int i=0;i<8;i++) {
     missilesLeft = shots - 1;
//Panel
public class PanelWindow{
     public static void main (String [] args) { 
     System.out.println(missilesLeft.Ship);
Andrew

i still can get it to work.. but i think that you got me quite close;
this is where i need to get missilesLeft from
//BattleShip
public void mouseClicked(MouseEvent e){
     tries--;
     for (int i = 0; i < 8; i++){
      for (int j = 0; j < 8; j++){
       if (e.getSource().equals(buttons[i][j]) && ship[i][j] == true){
        buttons[i][j].setBackground(new Color(80,80,80));
        hit++;
        System.out.println(hit+" "+total);
       else if (e.getSource().equals(buttons[i][j]) && ship[i][j] == false){
        buttons[i][j].setBackground(new Color(0,0,255));
     //Win
      if (isWin()){
       int hits = 64 - tries;
       int misses = hits- hit;
       int score = ((tries+hit)/misses)*64;
       missilesLeft = tries - 30;
       mis = missilesLeft;
       JOptionPane.showMessageDialog(this, "You WIN!\n \nMissiles used: "+hits+"\nMissiles left: "+missilesLeft+"\nHits: "+hit+"\nMisses: "+misses+"\nScore: "+score );
     //Game Over
     if (isGameOver()){
       JOptionPane.showMessageDialog(this, "  GAME OVER!!\n*******************\nYou have run out of missiles!\nTRY AGAIN");
//BattleWindow
private void build(){
          main = new JPanel(new BorderLayout());
          title = new JPanel(new FlowLayout(FlowLayout.CENTER));
          right= new JPanel(new FlowLayout(FlowLayout.CENTER));
          left = new JPanel(new FlowLayout(FlowLayout.CENTER));
          bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
          displayField = new JTextField("000", 8);
          displayField.setEditable( false );
          b = new Battleship();
          JLabel t = new JLabel("Battleship Potemkin");
          Font myFont =  new Font("Arial",Font.BOLD,32);
          t.setFont(myFont);
          title.add(t);
          help = new JButton("Help");
        exit = new JButton("Quit");     
        help.setFont(new Font("Arial", Font.BOLD, 17));
        exit.setFont(new Font("Arial", Font.BOLD, 17));
        displayField.setFont(new Font("Arial", Font.BOLD, 22));
          main.add(title,BorderLayout.NORTH);
          main.add(left,BorderLayout.WEST);
          main.add(right,BorderLayout.EAST);
          main.add(bottom,BorderLayout.SOUTH);
          main.add(b,BorderLayout.CENTER);
         this.add(main);
          help.addMouseListener(this);
          exit.addMouseListener(this);
          bottom.add(displayField);
          bottom.add(help);
          bottom.add(exit);
          setSize(500,600);
          setResizable(false);
          String aString = Integer.toString(bob);
          displayField.setText(displayField.getText() + bob);
          //displayField.setText("bob");
          }the variable bob in must have the same value as missilesLeft
thank you

Similar Messages

  • How can I pass variables from one project to another using Javascript?

    Hi all, I am trying to do this: let learners take one course and finish a quiz. Then based on their quiz scores, they will be sent to other differenct courses.
    However, I wish keep track on their previous quiz scores as well as many other variables.
    I found this nice widge of upload/download variables by CPguru (http://www.cpguru.com/2011/05/18/save-and-load-data-widget-for-adobe-captivate-4-and-adobe -captivate-5/). However, this widget works by storing variables from one project in local computer and then upload it to another project.
    My targeted learners may not always use the same computer though, so using this widget seems not work.
    All these courses resided in a local-made LMS which I don't have access to their code. Therefore, passing variables to PHP html files seems not work.
    Based on my limited programing knowledge, I assume that using Javascript to pass variables may be the only possible way.
    Can someone instruct me how to do this?
    Thank you very much.

    If you create two MIDlet in a midlet suite, it will display as you mentioned means you can't change the display style.

  • How can I pass variable to eventdriven startElement() function?

    I am new to java and SAX. Could anybody tell me how to pass variable to eventdriven startElement function? I tried the following code but didn't work.
    public class ReadXmlSax extends DefaultHandler
    String elementName;
    String requestName;
    Vector v = new Vector();
    public Enumeration getAttribute(String sFileName, String sTagName, String sAttrName)
         Enumeration e;
         elementName=sTagName;
    requestName=sAttrName;
    File f = new File(sFileName);
    // Use an instance of ourselves as the SAX event handler
    DefaultHandler handler = new ReadXmlSax();
    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
    // Parse the input
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(f, handler);
    } catch (Throwable t) {
    t.printStackTrace();
    e = v.elements();
    return(e);
    //===========================================================
    // SAX DocumentHandler methods
    //===========================================================
    public void startDocument()
    throws SAXException
    public void endDocument()
    throws SAXException
    public void startElement(String namespaceURI,
    String sName, // simple name
    String qName, // qualified name
    Attributes attrs)
    throws SAXException
              //System.out.println(elementName);
              if (qName.equals(elementName))
                   String serverName = attrs.getValue("",requestName);
                   v.addElement(serverName);
    }

    I attached the main call the ReadXmlSax class. I added the
    "system.out.println(elementName);" in the function getAttribute and startElement as well. I got printing out "name" for elementName from function getAttribute but got others printing out "null" for elementName from function startElement. Any suggestions? thanks
    import java.io.*;
    import java.util.*;
    import ReadXmlSax;
    public class ReadElement
         public static void main(String argv[])
              ReadXmlSax r = new ReadXmlSax();
              Enumeration e = r.getAttribute("dre.xml","server","name");
              try{
                   while (e.hasMoreElements()) {
                   System.out.println((String)e.nextElement());}
              }catch(Throwable t){
                   t.printStackTrace();
    <strong>test</strong>

  • Need Help ! how can I Pass Variable from JApplet to PHP?

    I think I post to the wrong forum and I don't know how to change.
    Sorry for messing thing.
    I try to send variable for applet to php but the result is no data was recorded in my database.
    I think the data did not transfer to php.
    I am familiar with php but new to java.
    Actually, I don't know how to send the variable for applet.
    For example, in PHP will receive $_POST['score'] so in applet, I need to send the variable name "score".
    In the book that I use for self-study, mention about servlet but I think PHP is much easier to me.
    So I need to know how set this request data to my applet.
    In internet, I still not get what is clear for me to understand.
    Or I may search with worng keyword or way.....
    Can someone please help me?
    public class test extends JApplet { public test(){ JButton myButton = new JButton("sendData");         myButton.setFont(new Font("Sansserif", Font.PLAIN, 14));         myButton.setSize(15, 10);                 myButton.addActionListener(new button());         add(myButton); } private class button implements ActionListener {         public void actionPerformed(ActionEvent e) {         PostMsg(10,"hello");         } } public void PostMsg(int score, String name){ try {             String data = "name=" + name + "score=" + score;                    byte[] parameterAsBytes = data.getBytes();      // Send data     URL url = new URL("http://localhost/addtest.php");     URLConnection con = url.openConnection();     ((HttpURLConnection) con).setRequestMethod("POST");          con.setDoOutput(true);          con.setDoInput(true);          con.setUseCaches(false);          OutputStream wr = con.getOutputStream();              wr.write(parameterAsBytes);     wr.flush();     // Get the response     BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream())); wr.close();     rd.close(); } catch (Exception e) { System.out.println("ERROR"+e.getMessage()); } } }
    <html> <title>Untitled Document</title> </head> <body> include("../connectionJAVA/connect.php"); $name = $_POST['name']; $score =$_POST['score']; //insert data $sql = "insert into java values(null,'$name','$score')"; mysql_query($sql) or die("error=$sql"); </body> </html>

    rinJava wrote:
    I think I post to the wrong forum and I don't know how to change.Yep wrong forum. This is probably a html/applet/web service sort of question.

  • How can I pass value between two pages or fragments?

    Hi,
    I am learning ADF nowadays. Now I come across the following problem.
    There are two pages or fragments in a bounded task flow, e.g. PageA&PageB. There is an inputtext on PageA.When I press an button on PageA with an action jumpping to PageB I want pass the value of this inputtext to annother inputtext, which is shown on PageB. Moreover, the inputtext on PageB comes from a ViewObject. How can I achieve this goal? Any ideas or suggestions?
    Best wishes!
    Eleven.Xu
    Mar 27th.2009
    Edited by: Eleven.Xu on 2009-3-26 下午7:03

    RequestContext requestContext = RequestContext.getCurrentInstance();
    requestContext.getPageFlowScope().put("var_name", value);
    String value = (String)requestContext.getPageFlowScope().get("var_name");
    if you open a new window, the value will be null.

  • How can I pass variable's from one frame to other

    //This is the first frame where the value in the TextField
    //tf1 and tf2 are to be passed to 2nd Frame
    import java.awt.*;
    import java.awt.event.*;
    public class del extends Frame implements ItemListener,ActionListener
    public Panel p,p1,p2;
    public Button b,n;
    public Label l1,l2;
    public TextField tf1,tf2;
    public del()
    setLayout(new FlowLayout(FlowLayout.LEFT));
    Panel p=new Panel();
    n=new Button("Submit");
    p.add(n);
    add(p);
    l1=new Label(" Enter the Temperature : ");
    tf1=new TextField(5);
    p.add(l1);
    p.add(tf1);
    add("South",p);
    l2=new Label(" Enter the Compund ");
    tf2=new TextField("N-OCTANE",15);
    p1=new Panel();
    p1.add(l2);
    p1.add(tf2);
    add("South",p1);
    setSize(600,700);
    setVisible(true);
    public void itemStateChanged(ItemEvent ie)
    repaint();
    public void actionPerformed(ActionEvent a)
    if(a.getSource()==n)
    this.setVisible(false);
    new Finalput1();
    repaint();
    public static void main(String[]args)
    del d=new del();
    //2nd Frame which will appear on clicking submit button
    import java.awt.*;
    class del1 extends Frame
    public static double T;//value in 1st text field has to be stored in variable T
    String compd=" ";//value in 2nd textField has to be stored in this string
    TextField tf;
    public del1()
    setLayout(new FlowLayout());
    setSize(800,700);
    setVisible(true);
    public void paint(Graphics g)
    g.drawString(" INPUT DATA : - ",30,120);
    g.setColor(Color.black);
    g.drawString(" Component Name ="+compd,20,160);
    g.drawString(" Temperature of the Mixture ="+T,30,250);
    public static void main(String[]args)
    new del1();
    Pls help me.
    I will be happy if anyone help's me!

    Both your classes seem to be independent applications. (they are public, and they have their public static void main)
    Is this your intention? If so, your question is how to pass data from one application to another. That can be done in many ways, and it is a complicated issue. (if one application wants to pass data to another, you first have to find the other one, and if it isnt running you might want to start... - lots of things to think about.)
    If what you want to do is simply to pass data from one Frame to another, the matter is quite more simple.
    Here is a sample:
    import java.awt.event.*;
    import java.awt.*;
    public class F1 extends Frame implements ActionListener
    private F2 theOtherFrame;
    public F1()
    Button b;
    b=new Button("Action");
    b.addActionListener(this);
    add(b);
    setSize(100,100);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if (theOtherFrame == null)
         theOtherFrame = new F2();
         theOtherFrame.setSize(100, 100);
    theOtherFrame.setSomeData("Her you have som data");
    theOtherFrame.setVisible(true);
    public static void main(String[] args)
    new F1();
    class F2 extends Frame
    private String strData;
    private Label lab;
    public void setSomeData(String str)
    lab.setText(str);
    repaint();
    public F2()
    lab = new Label();
    add(lab);

  • How can I Pass Variable from JApplet to PHP?

    I try to send variable for applet to php but the result is no data was recorded in my database.
    I think the data did not transfer to php.
    I am familiar with php but new to java.
    Can someone help me?
    public class test extends JApplet {
         public test(){
               JButton myButton = new JButton("sendData");
                 myButton.setFont(new Font("Sansserif", Font.PLAIN, 14));
                 myButton.setSize(15, 10);
                 myButton.addActionListener(new button());
                 add(myButton);
         private class button implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                 PostMsg(10,"hello");
         public void PostMsg(int score, String name){
               try {
                      String data = "name=" + name + "score=" + score;          
                      byte[] parameterAsBytes = data.getBytes();   
                    // Send data
                       URL url = new URL("http://localhost/addtest.php");
                       URLConnection con = url.openConnection();
                       ((HttpURLConnection) con).setRequestMethod("POST");  
                      con.setDoOutput(true);  
                      con.setDoInput(true);  
                      con.setUseCaches(false);  
                      OutputStream wr = con.getOutputStream();     
                      wr.write(parameterAsBytes);
                       wr.flush();
                       // Get the response
                       BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
    wr.close();
                       rd.close();
                   } catch (Exception e) {
                        System.out.println("ERROR"+e.getMessage());
    <html>
    <title>Untitled Document</title>
    </head>
    <body>
    include("../connectionJAVA/connect.php");
    $name = $_POST['name'];
    $score =$_POST['score'];
    //insert data
    $sql = "insert into java
    values(null,'$name','$score')";
    mysql_query($sql) or die("error=$sql");
    </body>
    </html>

    Maybe you should set the proper header according to your form encoding, should be:
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");And I think this encoding requires a newline after each parameter, "\n" may suffice, may need even carriage return: "\r\n" (or "\n\r" I never remeber for sure).
    Anyway why don't you use a simple GET instead, since you're sending just one parameter?
    Bye.

  • How can i pass variables from component MXML to main MXML

    I have been struggling to pass some variables from my custom PanelTest.mxml to Main.mxml
    In my Main.mxml, i tried:
    import PanelTest;
    private var newVar:String;
    private var _panel:PanelTest;
    _panel.thisVar = newVar;
    I then bind the newVar to a Label textfield and nothing happens.
    Thanks

    One possibility would be to use a Login PEI to set a unique UserInfo Name/Value for the user. I think in 5.0 each guest session is unique, so would have unique UserInfo. Then you could pass this value to your portlet (by specifying it in the web service) and use it as a key into a Application-scoped hashmap where you store your info. In other words, your Application variables option, but you have a way of uniquely naming your variables via PEI-set UserInfo.

  • Pass variables between form

    Hi,
    I'm using oracle forms 6i.
    How can i pass variables between forms?
    Consider the scenarion of a login form.
    After a user logged in successfully, a new form appears , where his name should be displayed
    like 'Welcome <user>'
    So name should be passed form login form to the home page.
    Is it possible with Oracle?
    Divya

    Arif,
    -- Your CodeTo format a number of lines, write  at the ending and to begin the code area write .
    -- Line of Code
    And if you want only 1 line to be formatted then use >.
    Regards,
    Manu.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How can I pass a variable(s) between two swfs?

    Hello all,
    I was wondering if it is possible to pass variables between
    two standalone swfs that are not being hosted on a webserver.
    I am creating a flash projector to go on a CD Rom and want to
    load another swf into the _root level and in the process, want to
    pass a variable or two to the "new" swf that is being loaded. Any
    help or insights that you can offer would be greatly appreciated!
    Thanks for your help.
    Tim

    if by _root level you mean you're loading something into
    _level0 you can't won't be able to use the localconnection. the
    sharedobject is your only option.

  • How to pass variables between loaders

    Hi,
    I am trying to load an image, with descriptive text and a back button on the click of a thumbnail of the image. I am using a MovieClipLoader instance to do this.
    Here are my problems:
    1. I tried loading the image, with the text(which is within an external swf), using the same loader, but since I am placing them dynamically, depending on the dimensions of the image, I need to pass variables between the two. The image loader is taking longer than the text (obviously) but I need the dimensions of the image before I can place the text. How do I do that??
    2. I tried using two loaders, with separate listeners, and the problem once again is that the text loads before the image, and is hence placed with default values instead of the values derived from the image. The code is within onLoadInit(). Is it possible for me to get the dimensions of the image from onLoadStart()???
    3. There is a back button within the text.swf. I want the image and the text.swf to be unloaded when this button is clicked. How can I achieve that? Can I call loader.unloadClip(target), from within this? Will it recognize the variable?
    4. Is there a much easier way to do this, which I am sadly unaware of?
    Any help will be appreciated.

    Tried the onloadstart() function, but it gives target._width and _height as 0. So that is ruled out...any other suggestions?

  • How to use a variable between interfaces or class?

    Hello All;
    Far by now I can say that the forum is very helpful for me. Thanks for all the people who have the time and generosity to help our problems. Thank you.
    Unfortunately I have a problem <Again :( >
    I want to use a variable in two different *.java files.
    Is it possible?
    The Variable i want to use is; int CiftSayisi
    The variable is declared in the CamCalib.Java under a button's Action Listener.
    Here is the code;
    public void actionPerformed(ActionEvent arg0) {
                        ImagePair.main(null);
                        String[] ImPath = list.getItems();                                           //Storing Items in an Array
                        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();                     //Dimensions of the Screen Storing in an object
                        int ScreenHeight = dim.height;                                           //Definition ScreenHeight
                        int ScreenWidth = dim.width;                                          //Definition ScreenWidth
                        // System.out.println(ScreenHeight);                                                    //Testing of the Dimensions
                        // System.out.println(ScreenWidth);                                                     //Testing of the Dimensions
                        int CiftSayisi = ImPath.length -1 ;
                        if (CiftSayisi == 0){
                             System.out.println("Added Images do not Construct a Pair");
                        else {
    }Now i want to use it in another java file which is ImagePair.Java in the loading part of the interface;
                 setType(Type.UTILITY);
              setTitle("Image Pair Selection");
              setResizable(false);
              setAlwaysOnTop(true);
              setBounds(100, 100, 450, 68);
              contentPane = new JPanel();
              contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
              setContentPane(contentPane);
              contentPane.setLayout(null);
              textField = new JTextField();
              textField.setBounds(61, 11, 22, 20);
              textField.setEditable(false);
              textField.setEnabled(false);
              contentPane.add(textField);
              textField.setColumns(2);I have a text field in here that i need to fill with the value of CiftSayisi
    Any help please?
    ömer kaya
    METU-GGIT
    Edited by: Ömer K. on Apr 10, 2012 12:43 AM

    I didn't bother reading the code, since you didn't format it.
    But to answer your question (if I understand it correctly), yes, it is possible to pass variables between different object instances (not from an interface specifically, since interfaces don't have members). The simplest way to pass the variable as an argument to a method or constructor. If these aren't available, you could create a static global variable, though in a multithreaded app you'd have to synchronize access.

  • How can i pass a variable instead of a table name in the Select statement.

    Dear all
    how can i pass a variable instead of a table name in a select statement ?
    Example :-
    Begin
    P_get_procedure_tname (aap_name,otable_name);--It will take an application name and will return a table name
    Select col1 into ocol1
    from  ---- here i want to pass the variable OTABLE_NAME
    End;How can i pass this ?

    Hi,
    You can use dynamic sql.
    EXECUTE IMMEDIATE 'SELECT COL1 INTO ' || OCOL1 || ' FROM " || OTABLE_NAME;
    {code}
    cheers
    VT                                                                                                                                                                                                                                                                                                   

  • How can I pass environment variables to the child process?

    How can I pass environment variables to the child process? This is what I tried and it didn't work.
         static public void main (String[] args) throws Exception {
              ProcessBuilder b = new ProcessBuilder("java", "-cp", ".", "Child");
              Map<String, String> map = b.environment();
              map.put("custom.property", "my value");
                 b.redirectErrorStream(true);
              Process p = b.start();
              BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream()));
              String line = null;
              while (null != (line = reader.readLine())) {
                   System.out.println(line);
         public static void main(String[] args) {
              System.out.println("The value of custom.property is : " + System.getProperty("custom.property"));
         }and the result is:
    The value of custom.property is : null

    Complete test:
         static public void main (String[] args) throws Exception {
              ProcessBuilder b = new ProcessBuilder("java", "-Dcustom.property=my property value", "-cp", ".", "Child");
              Map<String, String> map = b.environment();
              map.put("custom.property", "my environment value");
                 b.redirectErrorStream(true);
              Process p = b.start();
              BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream()));
              String line = null;
              while (null != (line = reader.readLine())) {
                   System.out.println(line);
         public static void main(String[] args) {
              System.out.println("Property value of custom.property is : " + System.getProperty("custom.property"));
              System.out.println("Environment value of custom.property is : " + System.getenv("custom.property"));          
         }

  • How can I pass a Presentation Variable (Date) into a prompt

    Hello
    How can I pass a Presentation Variable (date) into a prompt? I seem to be able to do this successfully for a non-date value but have had no luck with a Date variable.
    Here's a simplistic version of what I'm trying to do:
    1. I have a Presentation Variable called startDate which is a Date that defaults to this SQL - SELECT "Reporting Dates"."Measure Date" FROM Trading WHERE "Reporting Dates"."Date Name" = 'Current'.
    2. I now want to pass this variable into a prompt with SQL like this: SELECT "Position Date"."Position Date" FROM Trading where "Position Date"."Position Date" = date'@{startDate}{2009-04-24}'
    I get this error: Datetime value @{startDate}{2009-04-24} from @{startDate}{2009-04-24} does not match the specified format.
    Now I can use the exact same syntax in a filter. For example, a simple Answers request where I pick Position Date with a filter saying "Position Date"."Position Date" = date'@{startDate}{2009-04-24}' works fine.
    What am I doing wrong?
    Thanks!

    Can you provide more information please?
    1. What is the format of the first date prompt, is it YYYY-MM-DD or?
    2. Which data type is Position Date."Position Date" in the physical layer, date or date time?
    3. What is the column formula in the first prompt?
    4. The first prompt is set to drop-down or?
    5. If you are using this SQL Results in the second prompt:
    SELECT "Position Date"."Position Date" FROM Trading where "Position Date"."Position Date" = date '@{startDate}{2009-04-24}'
    then @{startDate} must be in YYYY-MM-DD format to work properly, otherwise (for example):
    datetime value 01/01/2000 from 01/01/2000 does not match the specified format.
    This doesn't work for example:
    SELECT Times.time_id FROM "Normal model" where Times.time_id =date '01/01/2000'
    Regards
    Goran
    http://108obiee.blogspot.com

Maybe you are looking for