Accessing a public array from extra class.

I am trying to access a public array that I declared in my main class from a separate class. I am a bit confused about why this is not working.
The method search in the extra class is called in the extra class in part one of the nextKeystream method. How can I get it to use the int array "key". That I declared in the MainSolitaireDriver?
Thanks
My main class:
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class MainSolitaireDriver
   int pcount = 0;
   public int[] key = new int[26];    
   public MainSolitaireDriver()
       getValues();
        public void getValues()
            try
                Scanner inFile = new  Scanner(new File("input.txt"));
                for (int counter = 0; counter < key.length; counter++ )
                    key[counter]= inFile.nextInt();
                    System.out.print(key[counter]+" ");
            catch(FileNotFoundException e )
            e.printStackTrace();
            System.err.print("Failure- File Not Found");
     public static void main (String[] args)
            /*String whereInTheWorldMyFileShouldBe = new File("input.txt").getAbsolutePath();
System.out.println(whereInTheWorldMyFileShouldBe); */
}My extra class:
public class Solitaire
     private Deck deck;
     *  Initialize the deck from the current key deck ordering.
     public Solitaire (int[] shuffle)
          deck = new Deck(shuffle);
        public void getArray(int[] Array)
        public int search(int [] span, int target)
            for (int indexcount = 0; indexcount < span.length; indexcount++)
                if (span[indexcount]==target)
                    return indexcount;
        public void getArray(int[] a)
     *  Returns the next keystream generated by the Solitaire  Algorithm
     public int nextKeystream()
          // Step one: Move Joker A one card down.
                int jokerAindex = search(MainSolitaireDriver(key), 27);
                System.out.print(jokerAindex);
          // Step two: Move Joker B two cards down.
          // Step three: Perform a triple cut.
          // Step four: Perform a count cut.
          // Step five: Find the output card.
          return 0;
     *  Returns the ciphertext corresponding to the specified
   *  plaintext, according to the current key deck ordering.
     public String encrypt(String plaintext)
          return "";
     *  Returns the plaintext corresponding to the specified
   *  ciphertext, according to the current key deck ordering.
     public String decrypt(String ciphertext)
          return "";
}

Main Class
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class MainSolitaireDriver
   int pcount = 0;
   public int[] key = new int[26];    
   public MainSolitaireDriver()
       getValues();
        public void getValues()
            try
                Scanner inFile = new  Scanner(new File("input.txt"));
                for (int counter = 0; counter < key.length; counter++ )
                    key[counter]= inFile.nextInt();
                    System.out.print(key[counter]+" ");
            catch(FileNotFoundException e )
            e.printStackTrace();
            System.err.print("Failure- File Not Found");
     public static void main (String[] args)
            /*String whereInTheWorldMyFileShouldBe = new File("input.txt").getAbsolutePath();
System.out.println(whereInTheWorldMyFileShouldBe); */
}Solitaire Class (not main)
public class Solitaire
     private Deck deck;
     *  Initialize the deck from the current key deck ordering.
     public Solitaire (int[] shuffle)
          deck = new Deck(shuffle);
        public void getArray(int[] Array)
        public int search(int [] span, int target)
            for (int indexcount = 0; indexcount < span.length; indexcount++)
                if (span[indexcount]==target)
                    return indexcount;
        public void getArray(int[] a)
     *  Returns the next keystream generated by the Solitaire  Algorithm
     public int nextKeystream()
          // Step one: Move Joker A one card down.
                int jokerAindex = search(MainSolitaireDriver.key, 27);
                System.out.print(jokerAindex);
          // Step two: Move Joker B two cards down.
          // Step three: Perform a triple cut.
          // Step four: Perform a count cut.
          // Step five: Find the output card.
          return 0;
     *  Returns the ciphertext corresponding to the specified
   *  plaintext, according to the current key deck ordering.
     public String encrypt(String plaintext)
          return "";
     *  Returns the plaintext corresponding to the specified
   *  ciphertext, according to the current key deck ordering.
     public String decrypt(String ciphertext)
          return "";
}

Similar Messages

  • OOABAP-How to access the protected methos from a class

    How to access the protected methos from a class..There is a built in class..For tht class i have created a object..
    Built in class name : CL_GUI_TEXTEDIT
    method : LIMIT_TEXT.
    How to access this..help me with code

    hi,
    If inheritance is used properly, it provides a significantly better structure, as common components only
    need to be stored once centrally (in the superclass) and are then automatically available to subclasses.
    Subclasses also profit immediately from changes (although the changes can also render them invalid!).
    Inheritance provides very strong links between the superclass and the subclass. The subclass must
    possess detailed knowledge of the implementation of the superclass, particularly for redefinition, but also in
    order to use inherited components.
    Even if, technically, the superclass does not know its subclasses, the
    subclass often makes additional requirements of the superclass, for example, because a subclass needs
    certain protected components or because implementation details in the superclass need to be changed in
    the subclass in order to redefine methods.
    The basic reason is that the developer of a (super)class cannot
    normally predict all the requirements that subclasses will later need to make of the superclass.
    Inheritance provides an extension of the visibility concept: there are protected components. The visibility of
    these components lies between that of the public components (visible to all users, all subclasses, and the class itself), and private (visible only to the class itself). Protected components are visible to and can be used by all subclasses and the class itself.
    Subclasses cannot access the private components  particularly attributes) of the superclass. Private
    components are genuinely private. This is particularly important if a (super)class needs to make local
    enhancements to handle errors: it can use private components to do this without knowing or invalidating
    subclasses.
    Create your class inse24 and inherit this CL_GUI_TEXTEDIT
    class in yours. You can then access the protected methods.
    Hope this is helpful, <REMOVED BY MODERATOR>
    Edited by: Runal Singh on Feb 8, 2008 1:08 PM
    Edited by: Alvaro Tejada Galindo on Feb 19, 2008 2:19 PM

  • Access the object array from client.

    I'm trying to access the object array from client.
    it's throwing the following error,
    RemoteException Ocuredjava.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.MarshalException: CORBA BAD_PARAM 0x4f4d0006 Maybe; nested exception is:
         java.io.NotSerializableException: oracle.jdbc.driver.OracleResultSetImpl is not serializable
    how to resolve it?
    thanx in advance,
    Ilam.

    Don't send a ResultSet back as the result of an RMI call. Extract the data from the ResultSet on the server and send that back instead.

  • Accessing public variables from other classes

    Probably a simple questions, but how can I access a variable from another class. My exact situation is as follows.
    A class called WorldCalender has a variable which is defined: public int hour; (the value is given to it elsewhere).
    I want to access this variable and increase it by one in a subroutine in the class Hour. In this class I have put: WorldCalender.hour++; but it doesn't seem to work. How should I do it?

    don't expose the hour variable at all.
    have a method eg addToHourBy( int hrs )
    Probably a simple questions, but how can I access a
    variable from another class. My exact situation is as
    follows.
    A class called WorldCalender has a variable which is
    defined: public int hour; (the value is given to it
    elsewhere).
    I want to access this variable and increase it by one
    in a subroutine in the class Hour. In this class I
    have put: WorldCalender.hour++; but it doesn't seem to
    work. How should I do it?

  • Accessing the same object from multiple classes.

    For the life of me I can't workout how I can access things from classes that haven't created them.
    I don't want to have to use "new" multiple times in seperate classes as that would erase manipulated values.
    I want to be able to access and manipulate an array of objects from multiple classes without resetting the array object values. How do I create a new object then be able to use it from all classes rather than re-creating it?
    Also I need my GUI to recognize the changes my buttons are making to data and reload itself so they show up.
    All help is good help!
    regards,
    Luke Grainger

    As long as you have a headquarters it shouldn't be to painfull. You simply keep a refrence to your ShipDataBase and Arsenal and all your irrellevant stuff in Headquarters. So the start of your Headquarters class would look something like:
    public class Headquarters{
      public Arsenal arsenal;
      public ShipDatabase db;
    //constructor
      public Headquarters(){
        arsenal = new Arsenal(this, ....);
        db = new ShipDatabase(...);
    //The Arsenal class:
    public class Arsenal{
      public Headquarter hq;
      public Arsenal(Headquarter hq, ....){
        this.hq = hq;
        .Then in your ShipDatabase you should, as good programing goes, keep the arraylist as a private class variable, and then make simple public methods to access it. Methods like getShipList(), addToShipList(Ship ship)....
    So when you want to add a ship from arsenal you write:
    hq.db.addToShipList(ship);
    .Or you could of course use a more direct refrence:
    ShipDatabase db = hq.db;
    or even
    ShipList = hq.db.getShipList();
    but this requires that the shiplist in the DB is kept public....
    Hope it was comprehensive enough, and that I answered what you where wondering.
    Sjur
    PS: Initialise the array is what you do right here:
    //constructor
    shipList = new Ship[6];
    shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " "etc
    shipList[5] = new Ship("Sentry", 15, 10, "Scout");PPS: To make code snippets etc. more readable please read this article:
    http://forum.java.sun.com/faq.jsp#messageformat

  • Using Variables/Arrays from one class in another

    Hello all,
    First, to explain what I am attempting to create, is a program that will accept input of employee names and hours worked into an array. The first class will accept a command line argument when invoked. If the argument is correct, it will call another class that will gather information from the user via an input box. After all names and hours have been input for employees, this class will calculate the salary based upon the first letter of each employee name and print the total hours, salary, etc. for each employee.
    What I need to do now is to split the second class into two: one that will gather the data and another that will calculate and print the data. Yes, this is an assignment. However, I am trying to learn and I have gotten this far, but I am stuck on how to get a class to be able to use an array/variables from another class.
    I realize the below code isn't exactly cleaned up...yet.
    Code for AverageSalaryGather class:
    import javax.swing.JOptionPane; // uses class JOptionPane
    import java.lang.reflect.Array;     
    import java.math.*;
    public class AverageSalaryGather {
         public static void gatherData() {     
              char[] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'};
              String[][] empInfoArray = new String[100][4];
              String[] empNameArray = new String[100];
              String finalOutput = "Name - Rate - Hours - Total Pay\n";
              String averageHoursOutput = "Average Hours Worked:\n";
              String averageSalaryOutput = "Average Hourly Salary:\n";
              String averageGroupSalaryOutput = "Average Group Salary:\n";
                        String[] rateArray = new String[26];
                        char empNameChar = 'a';
              int empRate = 0;
              int payRate = 0;
                        for (int i = 0; i < 26; i++) {
                   payRate = i + 5;
                   rateArray[i] = Integer.toString(payRate);
                        int countJoo = 0;
              while (true) {
                   String namePrompt = "Please enter the employee name: ";
                   String empName = JOptionPane.showInputDialog(namePrompt);
                                  if (empName == null | empName.equals("")) {
                        break;
                   else {
                        empInfoArray[countJoo][0] = empName;
                        for (int i = 0; i < alphaArray.length; i++) {
                             empNameChar = empName.toLowerCase().charAt(0);
                                                      if (alphaArray[i] == empNameChar) {
                                  empInfoArray[countJoo][1] = rateArray;
                                  break;
                        countJoo++;
              // DecimalFormat dollarFormat = new DecimalFormat("$#0.00");
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[i][0] == null)) {
                        String hourPrompt = "Please enter hours for " + empInfoArray[i][0] + ": ";
                        String empHours = JOptionPane.showInputDialog(hourPrompt);
                        int test = 0;
                        empInfoArray[i][2] = empHours;
                        // convert type String to double
                        //double tmpPayRate = Double.parseDouble(empInfoArray[i][1]);
                        //double tmpHours = Double.parseDouble(empInfoArray[i][2]);
                        //double tmpTotalPay = tmpPayRate * tmpHours;
                        // create via a string in empInfoArray
                             BigDecimal bdRate = new BigDecimal(empInfoArray[i][1]);
                             BigDecimal bdHours = new BigDecimal(empInfoArray[i][2]);
                             BigDecimal bdTotal = bdRate.multiply(bdHours);
                             bdTotal = bdTotal.setScale(2, RoundingMode.HALF_UP);
                             String strTotal = bdTotal.toString();
                             empInfoArray[i][3] = strTotal;
                        //String strTotalPay = Double.toString(tmpTotalPay);
                        //empInfoArray[i][3] = dollarFormat.format(tmpTotalPay);
                        else {
                             break;
              AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
              averageSalaryCalcAndprint.calcAndPrint();
    Code for AverageSalaryCalcAndPrint class (upon compiling, there are more than a few complie errors, and that is due to me cutting/pasting the code from the other class into the new class and the compiler does not know how to access the array/variables from the gatherData class):
    import javax.swing.JOptionPane; // uses class JOptionPane
    import java.lang.reflect.Array;
    import java.math.*;
    public class AverageSalaryCalcAndPrint
         public static void calcAndPrint() {     
              AverageSalaryGather averageSalaryGather = new AverageSalaryGather();
              double totalHours = 0;
              double averageHours = 0;
              double averageSalary = 0;
              double totalSalary = 0;
              double averageGroupSalary = 0;
              double totalGroupSalary = 0;
              int countOfArray = 0;
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[0] == null)) {
                        totalSalary = totalSalary + Double.parseDouble(empInfoArray[i][1]);
                        totalHours = totalHours + Double.parseDouble(empInfoArray[i][2]);
                        totalGroupSalary = totalGroupSalary + Double.parseDouble(empInfoArray[i][3]);
                        countOfArray = i;
              averageHours = totalHours / (countOfArray + 1);
              averageSalary = totalSalary / (countOfArray + 1);
              averageGroupSalary = totalGroupSalary / (countOfArray + 1);
              String strAverageHourlySalary = Double.toString(averageSalary);
              String strAverageHours = Double.toString(averageHours);
              String strAverageGroupSalary = Double.toString(averageGroupSalary);
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[i][0] == null)) {
                        finalOutput = finalOutput + empInfoArray[i][0] + " - " + "$" + empInfoArray[i][1] + "/hr" + " - " + empInfoArray[i][2] + " - " + "$" + empInfoArray[i][3] + "\n";
              averageHoursOutput = averageHoursOutput + strAverageHours + "\n";
              averageSalaryOutput = averageSalaryOutput + strAverageHourlySalary + "\n";
              averageGroupSalaryOutput = averageGroupSalaryOutput + strAverageGroupSalary + "\n";
              JOptionPane.showMessageDialog(null, finalOutput + averageHoursOutput + averageSalaryOutput + averageGroupSalaryOutput, "Totals", JOptionPane.PLAIN_MESSAGE );

    Call the other class's methods. (In general, you
    shouldn't even try to access fields from the other
    class.) Also you should be looking at an
    instance of the other class, and not the class
    itself, generally.Would I not call the other classes method's by someting similar as below?:
    AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
              averageSalaryCalcAndprint.calcAndPrint(); Well... don't break down classes based on broad steps
    of the program. Break them down by the information
    being managed. I'm not expressing this well...Could you give an example of this? I'm not sure I'm following well.
    Anyway, you want one or more objects that represent
    the data, and operations on that data. Those
    operations include calculations on the data. Other
    classes might represent the user interface, and
    different output types (say, a file versus the
    console).Yes, the requirements is to have a separate class to gather the data, and then another class to calculate and print the data. Is this what you mean in the above?

  • Calling an array from another class

    Ok I have this little program that I created to display values stored in an array. Well, I want my array to automatically be populated with the same values that are in another array that resides in a different class. Here is my code for the class that I want the values to be displayed:
    import javax.swing.*;
    import java.awt.*;
    public class GUIRead extends JFrame
         double[] interest = new double[3];
         MemicCSVReader[] interestObjectArray = new MemicCSVReader[3];
         interestObjectArray[0] = new MemicCSVReader();
         interestObjectArray[1] = new MemicCSVReader();
         interestObjectArray[2] = new MemicCSVReader():
         for(int x = 0; x < 3; x++)
         JPanel display = new JPanel();
         JTextField interestText = new JTextField(10);
         JPanel display2 = new JPanel();
         JTextField interestText2 = new JTextField(10);
         JPanel display3 = new JPanel();
         JTextField interestText3 = new JTextField(10);
         public GUIRead()
              super("Test");
              setSize(160,200);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              GridLayout config = new GridLayout(3,1);
              FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
              Container pane = getContentPane();
              pane.setLayout(config2);
              display.setLayout(config2);
              display.add(interestText);
              interestText.setText(interest[0]);
              interestText.setEditable(false);
              pane.add(display);
              display2.setLayout(config2);
              display2.add(interestText2);
              interestText2.setText(interest[1]);
              interestText2.setEditable(false);
              pane.add(display2);
              display3.setLayout(config2);
              display3.add(interestText3);
              interestText3.setText(interest[2]);
              interestText3.setEditable(false);
              pane.add(display3);
              setContentPane(pane);
         public static void main(String[] args)
              GUIRead run = new GUIRead();
    Here is my code that I want the double[] interest array to pull it's data from:
    public class MemicCSVReader
         double interestArray[];
         MemicCSVReader()
              String[] interestString = {"5.5","5.35","5.75"};
              for(int x = 0; x < 3; x++)
                   interestArray[x] = Double.parseDouble(interestString[x]);
    }

    Ok, thanks for your help. Now I have another problem. I can't get the values to display. Here is my code:
    This is the program that runs the application:
    import javax.swing.*;
    import java.awt.*;
    public class GUIRead extends JFrame
         MemicCSVReader readCSV = new MemicCSVReader();
         double[] interestDouble = readCSV.getInterestArray();
         String[] interest;
         JPanel display = new JPanel();
         JTextField interestText = new JTextField(10);
         JPanel display2 = new JPanel();
         JTextField interestText2 = new JTextField(10);
         JPanel display3 = new JPanel();
         JTextField interestText3 = new JTextField(10);
         public GUIRead()
              super("Test");
              setSize(160,200);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              GridLayout config = new GridLayout(3,1);
              FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
              Container pane = getContentPane();
              pane.setLayout(config2);
              display.setLayout(config2);
              display.add(interestText);
              interestText.setEditable(false);
              pane.add(display);
              display2.setLayout(config2);
              display2.add(interestText2);
              interestText2.setEditable(false);
              pane.add(display2);
              display3.setLayout(config2);
              display3.add(interestText3);
              interestText3.setEditable(false);
              pane.add(display3);
              setContentPane(pane);
         public void actionPerformed()
              for(int x = 0; x < 3; x++)
                   interest[x] = Double.toString(interestDouble[x]);
              interestText.setText(interest[0]);
              interestText2.setText(interest[1]);
              interestText3.setText(interest[2]);
         public static void main(String[] args)
              GUIRead run = new GUIRead();
    This is the file that it pulls the array from:
    public class MemicCSVReader
         private double[] InterestArray = new double[3];
         MemicCSVReader()
              double[] InterestArray = {5.5,5.35,5.75};
         public double[] getInterestArray()
              return InterestArray;
    }

  • Error accessing constnt public attribute of a class in an overwrite method.

    Hi Gurus,
    I am facing an error while accessing a constant public attribute while using it in the overwrite-exit of a methods.
    The constant which is declared as public in the attribute section of the class is not available in the overwrite-exit of the method.
    Please suggest me how to access the public attributes in the overwtire exits of the methods.
    Thanks.

    Hi Ramneek,
    Let me explain you the entire scenario:
    Actually we are trying to ehance the SAP standard class : CL_FITV_POWL_FEEDER_TRIPS in ECC 6.0 EHP 5 .
    We tried to create and overwrite-exit of the method "IF_POWL_FEEDER~GET_ACTIONS".
    Overwrite-exit of a method is just like a method which will be called instead of the standard method : IF_POWL_FEEDER~GET_ACTIONS.
    But the problem which we are facing here is that the Attributes which are defined in the class CL_FITV_POWL_FEEDER_TRIPS,  are getting accessed from the overwrite-exit method.
    Becuase of this we are not able to implement our custom logic.

  • Accessing method of parent from instanced class

    Heyo!
    I don't know if this makes sense. But I can't figure out another way to do it. Hell, I can't even figure this out. :P
    So. I've got this class:
            JPanel cp = new JPanel();
         JPanel menuScreen = new egMenuScreen();
         JPanel newGame = new egNewGameScreen();
         public EscapeGravityUI() {
              // Create toolkit and get screen size
              Toolkit toolkit = getToolkit();
              Dimension size = toolkit.getScreenSize();
              // Set size, title and close operation on main game window
              setSize(1024, 768);
              setTitle("Escape Gravity");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              // Remove border
              setUndecorated(true);
              // Instructions for centering game window
              setLocation(size.width/2 - getWidth()/2,
                   size.height/2 - getHeight()/2);
              // Create JPanel and add to JFrame
              cp = menuScreen;
              getContentPane().add(cp);
              // Set KeyListener so we can close window in fullscreen
              this.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                             System.exit(0);
                             //TODO add nice code for confirming exit
         public void changeScreen(String np) {
              getContentPane().remove(cp);
              if(np == "egngs") {
                   JPanel p = new egNewGameScreen();
              getContentPane().add(p);
              repaint();
         }This class is supposed to be a "holder" for diffrent screens in my game. Every screen represented by a JPanel.
    in egMenuScreen that looks like this:
    public class egMenuScreen extends JPanel {
         public egMenuScreen() {
              // Setup the menu screen
              setBackground(Color.white);
              setSize(1024, 768);
              setLayout(null);
              setFocusable(false);
              // Create menu buttons
              JButton newGame = new JButton("New Game");
              newGame.setBounds(getWidth()/2-60, 60, 120, 30);
              newGame.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        super.changeScreen("egngs");
              JButton loadSaved = new JButton("Load Saved");
              loadSaved.setBounds(getWidth()/2-60, 100, 120, 30);
              loadSaved.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        System.out.println("Load Saved");
              JButton options = new JButton("Options");
              options.setBounds(getWidth()/2-60, 140, 120, 30);
              options.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        System.out.println("Options");
              JButton quit = new JButton("Quit");
              quit.setBounds(getWidth()/2-60, 180, 120, 30);
              quit.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        System.out.println("Quit");
                        System.exit(0);
              // Add buttons to JPanel
              this.add(newGame);
              this.add(loadSaved);
              this.add(options);
              this.add(quit);
    }What I want to do is to change that egMenuScreen to another JPanel class that holds the other screen. I figured I needed to do that from the JFrame (EscapeGravityUI). So the method changeScreen() is supposed to handle that. However I don't know how to run that method from within that instanced JPanel class... does that even make sense?
    I'd really appriciate any help!
    Peace

    Styrisen wrote:
    I looked at CardLayout but that looks like it needs to always have the buttons visible. Huh??
    I may be wrong, Very
    but I want to change the entire screen and as I saw it that wasn't possible with card layout!You're not reading the same stuff that I'm reading.
    Here's a simple seizure-inducing program program that uses CardLayout to change a JPanel that fills the entire JFrame. Each card is simply a JPanel of random color with a label at the top and a red circle of increasing size. The cards are swapped by way of a Swing Timer:
    import java.awt.BasicStroke;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Ellipse2D;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class CardLayoutFun4 extends JPanel
        private static final int DELAY = 100;
        private static final int CARD_COUNT = 180;
        private CardLayout cardlayout = new CardLayout();
        private Timer timer = new Timer(DELAY, new ActionListener()
            public void actionPerformed(ActionEvent e)
                cardlayout.next(CardLayoutFun4.this);
        public CardLayoutFun4()
            setLayout(cardlayout);
            setPreferredSize(new Dimension(1024, 768));
            addCards();
            timer.start();
        private void addCards()
            Random random = new Random();
            for (int i = 0; i < CARD_COUNT; i++)
                final int index = i;
                JPanel cardPanel = new JPanel()
                    private final double diameter = 600 * (index + 1) / CARD_COUNT;
                    protected void paintComponent(Graphics g)
                        super.paintComponent(g);
                        Graphics2D g2 = (Graphics2D) g;
                        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
                        Stroke oldStroke = g2.getStroke();
                        g2.setStroke(new BasicStroke(5));
                        g2.setPaint(Color.red);
                        g2.draw(new Ellipse2D.Double(20, 80, diameter, diameter));
                        g2.setStroke(oldStroke);
                cardPanel.setBackground(new Color(
                        random.nextInt(128),
                        random.nextInt(128),
                        random.nextInt(128)));
                cardPanel.add(new JLabel(String.valueOf(i)));
                add(cardPanel, String.valueOf(i));
        private static void createAndShowUI()
            JFrame frame = new JFrame("CardLayoutFun4");
            frame.getContentPane().add(new CardLayoutFun4());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Jan 19, 2008 8:06 PM

  • Accessing a public method from javascript in an applet!!!

    Hi!!
    I'm have an applet (named say applet.class) in an html page that has a public method like this....
    public void doShowFrame()
              Frame frame = new frame();
         frame.setVisible (true);
    What I want to do is to call that method with javascript, I've tried to do it like this...
    function show(){
    applet.doShowFrame();
    But when i press the button that launch the java scipt the browser says
    'applet' is unidentified...
    What's wrong, what can I do??

    http://www.google.com/search?q=applet+javascript+communication&sourceid=opera&num=0&ie=utf-8&oe=utf-8
    how hard was that? seriously.

  • Accessing a public variable between classes

    Hi there,
    I've got two classes running...one is a document class (EgoGame.as) and another is a class linked to several similar movie clips (Ball.as).
    I'm trying to access a public variable from Ball.as which has been declared in the doucment class EgoGame.as.
    When I run the test the outputs states the following...
    1120: Access of undefined property _ballPlaced.
    Here's my code.  What I'm trying to do is remove the event listeners from the Ball.as when the _ballPlaced variable is true, so that the user can't drag and drop the balls after they've been placed in a zone....any pointers greatly appreciated!
    Document Class
    EgoGame.as
    package
        import flash.display.MovieClip;
        import flash.display.DisplayObject;
        import flash.events.MouseEvent;
        import Ball;
        public class EgoGame extends MovieClip
            public var __zoneFull:Array = new Array(false, false, false);
            public var __ballPlaced:Array = new Array(false, false, false);
            public function EgoGame()
                ball0_mc.addEventListener(MouseEvent.MOUSE_DOWN, zoneEmpty);
                ball1_mc.addEventListener(MouseEvent.MOUSE_DOWN, zoneEmpty);
                ball2_mc.addEventListener(MouseEvent.MOUSE_DOWN, zoneEmpty);
                ball0_mc.addEventListener(MouseEvent.MOUSE_UP, zoneFill);
                ball2_mc.addEventListener(MouseEvent.MOUSE_UP, zoneFill);
                ball1_mc.addEventListener(MouseEvent.MOUSE_UP, zoneFill);
                ball0_mc.addEventListener(MouseEvent.MOUSE_UP, playMovie);
                ball1_mc.addEventListener(MouseEvent.MOUSE_UP, playMovie);
                ball2_mc.addEventListener(MouseEvent.MOUSE_UP, playMovie);
            private function zoneEmpty(event:MouseEvent):void
                if(event.target.hitTestObject(zone0_mc) && _zoneFull[0] == true)
                    _zoneFull[0] = false;
                    _ballPlaced[event.target.name.substring(4,5)] = false;
                else if(event.target.hitTestObject(zone1_mc) && _zoneFull[1] == true)
                    _zoneFull[1] = false;
                    _ballPlaced[event.target.name.substring(4,5)] = false;
                else if(event.target.hitTestObject(zone2_mc) && _zoneFull[2] == true)
                    _zoneFull[2] = false;
                    _ballPlaced[event.target.name.substring(4,5)] = false;
                else
                    event.target.x = event.target._startX;
                    event.target.y = event.target._startY;
                    _ballPlaced[event.target.name.substring(4,5)] = false;
            private function zoneFill(event:MouseEvent):void
                if(event.target.hitTestObject(zone0_mc) && _zoneFull[0] == false)
                    event.target.x = zone0_mc.x;
                    event.target.y = zone0_mc.y;
                    _zoneFull[0] = true;
                    _ballPlaced[event.target.name.substring(4,5)] = true;
                else if(event.target.hitTestObject(zone1_mc) && _zoneFull[1] == false)
                    event.target.x = zone1_mc.x;
                    event.target.y = zone1_mc.y;
                    _zoneFull[1] = true;
                    _ballPlaced[event.target.name.substring(4,5)] = true;
                else if(event.target.hitTestObject(zone2_mc) && _zoneFull[2] == false)
                    event.target.x = zone2_mc.x;
                    event.target.y = zone2_mc.y;
                    _zoneFull[2] = true;
                    _ballPlaced[event.target.name.substring(4,5)] = true;
                else
                    event.target.x = event.target._startX;
                    event.target.y = event.target._startY;
                    _ballPlaced[event.target.name.substring(4,5)] =false;
            private function playMovie(event:MouseEvent):void
                if (_ballPlaced[0] == true)
                    ball0_mc.gotoAndPlay(2);
                else
                    ball0_mc.gotoAndStop(1);
                if (_ballPlaced[1] == true)
                    ball1_mc.gotoAndPlay(2);
                else
                    ball1_mc.gotoAndStop(1);
                if (_ballPlaced[2] == true)
                    ball2_mc.gotoAndPlay(2);
                else
                    ball2_mc.gotoAndStop(1);
    Ball.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import flash.display.DisplayObject;
        import EgoGame;
        public class Ball extends MovieClip
            // public var _hitTarget:MovieClip;
            public var _startX:Number;
            public var _startY:Number;
            public function Ball()
                _startX = this.x;
                _startY = this.y;
                this.buttonMode = true;
                this.addEventListener(MouseEvent.MOUSE_DOWN, dragIt);
                this.addEventListener(MouseEvent.MOUSE_UP, dropIt);
            private function dragIt(event:MouseEvent):void
                this.startDrag();
            public function dropIt(event:MouseEvent):void
                this.stopDrag();
            public function lockBall(event:MouseEvent):void
                if(_ballPlaced[this.name.substring(4,5)] == true)
                    this.removeEventListener(MouseEvent.MOUSE_DOWN, dragIt);
                    this.removeEventListener(MouseEvent.MOUSE_UP, dropIt);

    every place you have a ball reference you can access the lockBall() method.  so, if ball0_mc is a Ball class member, you can use:
    ball0_mc.lockBall();

  • Using an array in another class to set text of a button

    I am trying to use an array from one class in another to set the text of a button.
    This is the code in the class where i have made the array.
    public class EnterHomeTeam
         public int NumberOfPlayers = 11;
         public String[] PlayerName = new String [NumberOfPlayers];
    private void button1_Click (Object sender, System.EventArgs e)
              PlayerName [0] = this.HGoalKeeper.toString();
              PlayerName [1] = this.HDef1.toString();
              PlayerName [2] = this.HDef2.toString();
              PlayerName [3] = this.HDef3.toString();
              PlayerName [4] = this.HDef4.toString();
              PlayerName [5] = this.HMid1.toString();
              PlayerName [6] = this.HMid2.toString();
              PlayerName [7] = this.HMid3.toString();
              PlayerName [8] = this.HMid4.toString();
              PlayerName [9] = this.HAtt1.toString();
              PlayerName [10] = this.HAtt2.toString();     
              Players IM = new Players();
              this.Hide();
              IM.Show();
    }Then in the class where i want to use the variables (ie. PlayerName[0]) I have got
    public class Players
    EnterHomeTeam HT = new EnterHomeTeam();
    //and included in the button code
    this.button1.set_Text(HT.PlayerName[0]);I hope i have explained this well enough and hope someone can help me solve this problem! Im not a very competent programmer so i apologise if I havent explained this well enough!
    Adam

    .NET automatically generates quite a bit of code.... this is button1:
    private void InitializeComponent()
              this.button1 = new System.Windows.Forms.Button();
    // button1
              this.button1.set_BackColor(System.Drawing.Color.get_LightBlue());
              this.button1.set_Location(new System.Drawing.Point(88, 32));
              this.button1.set_Name("button1");
              this.button1.set_Size(new System.Drawing.Size(72, 56));
              this.button1.set_TabIndex(0);
              this.button1.set_Text(HT.PlayerName[0]);
              this.button1.add_Click( new System.EventHandler(this.button1_Click) );
    this.get_Controls().Add(this.button1);
         private void button1_Click (Object sender, System.EventArgs e)
              System.out.print(HT.PlayerName[0]);
              GKAction GK = new GKAction();
              this.Hide();
              GK.Show();
         }Hope that helps - im pretty sure that's all the button1 code

  • Accesing from other classes to protected void

    Hy! I'm a newbie to java programming. So i am making a program in J2ME, and the problem is :
    I have an abstract class, wich i must extend. That class defines a procedure
    abstract protected void destroyApp(boolean unconditional), so in my extended class this void is protected. But i want to access to this procedure from other class, and do it somehow static.
    I have made a main program class (the extended class), and i want to send from other class a destroy message to it (to call destroyApp procedure).
    Kazhha.

    Your question has nothing to do with Native Methods.
    In the future, for novice questions, use the New To Java Technology forum.
    I have an abstract class, which i must extend. That
    class defines a procedure
    abstract protected void destroyApp(boolean
    unconditional), so in my extended class this void is
    protected.You can make the method public in your class.
    But i want to access to this procedure
    from other class, and do it somehow static.IIRC you cannot make a method static if it is not static in the class you extend.
    I have made a main program class (the extended class),
    and i want to send from other class a destroy message
    to it (to call destroyApp procedure).Huh?

  • Help please! Using an array in another class

    Hello, I'm new to JAVA and I'm trying to pass an array from one class to another, but I can't get it right. I've been able to get individual values on at a time.
    If any one can help me out and give me a quick sample of how to do it,
    I've done this below.
    Is it as simple as an individual value - but just calling it an array - instead of say a string - or is it more complex. Please Help
    class BoxVol extends Box {
    public static void main (String args[]) {
    Box ob1 = new Box();
    int[] vol;
    ob1.getLength();
    vol = ob1.getLength();
    System.out.println("Volume is : " + vol);
    } class Box {
    // what are the properties or fields
         private int innerData [];
    //public String length2 = "text";
    // what are the actions or methods
    public void setLength(String p)
         innerData = new int [5];
         for (int i=0; i < innerData.length; i++)  {
              innerData = i;
    public int[] getLength()
         return innerData;

    Guss46 wrote:
    hmmm I see, I shouldve seen that last night when I was working on this....but I was very tired....
    I don't have a compiler in front of me now,
    would this solve my problem
    1st :
    ob1.getLength();
    //Should be....
    vol = ob1.getLength();
    No you are missing my point. You original code was calling the getLength method twice. On the first line it did nothing with the returned value and on the second you assigned the returned value to vol. But the setLength method is where you actually create the array and assign values to it. So unless you call that method first then you will not have an array at all.
    >
    2nd:
    System.out.println("Volume is : " + vol);
    should be
    System.out.println("Volume is : " + vol.length);
    Yes you could do that but all that will tell you is the length of the array and not what values are in it.
    .or vol[i] to go through it if I make a loop around it??Yep, sounds like a much better idea to me.

  • Access session scope variables from a filter

    I have a filter I am using to check if 2 people are loged in with the same user name.
    When my web app loads I store the user name in a class that has session scope.
    Is there a way for me to access this class from the Filter class?
    How do I access the session instance from this class?
    How do I pass parameters to the Filter class?
    Thank you,
    Al

    http://forum.java.sun.com/thread.jspa?threadID=5122925&tstart=0

Maybe you are looking for

  • Data Services Not Working in Flash 9.0.115

    Hi all, I have an existing flex 2 application using dataservices extensively. I upgraded flash on my computer to flash 9.0.115 and dataservices no longer work. I read about the new security feature for the crossdomain.xml, so I checked the log files

  • Form Participant Step.

    Hi All, Back again with my qns to experts. My qn is related to Form Participant workflow. I wanted to work with Form Participant as I think it gives me a flexiblity to work with java script as against with dialog participant step. What I did: 1. I cr

  • RECORD HISTORY DISPLAYS EXCEPTION ON SUPPLIER PAGES :- R12.1.3

    Hello everyone, We have done personalization on the supplier pages to display the record history icon at site level . The record History icon is displayed but when I click on that the following error is diplayed: You have encountered an unexpected er

  • Security update and Adobe CS2 Suite

    there is alot being said about this but i thought i would throw this out there, as it may be helpful. i installed security update on intel macbook pro from software update. machine is nonresponsive, can move mouse but that is all. so i did an erase a

  • Need help with Color Matrix Filter.

    need help. still can't find the answer. thanks in advance!