Class.getResource JNLP issue

I'm seeing an error when deploying an application via JNLP:
schema_reference.4: Failed to read schema document 'jar:com/mycompany/my_schema.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>On a Linux machine, running 1.5.0_15-b04, it works fine. On a Windows machine, running 1.5.0_16-b02, it fails.
The code is attempting to load an XSD as follows (and is failing on the second line):
  URL schemaURL = MyClass.class.getResource("my_schema.xsd");
  SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL);On the Linux machine, where it works, the URL returned from the "getResource" call looks like:
jar:file:/path/to/containing.jar!/com/mycompany/my_schema.xsd
On the Windows machine, where it fails, the URL returned from the "getResource" call looks like:
jar:com/mycompany/my_schema.xsd
The same JARs are being run via JNLP on both machines.
I found that getting an InputStream instead of an URL (via MyClass.class.getResourceAsStream("my_schema.xsd")) and passing that into the newSchema call with a new StreamSource works if the schema is completely self-contained. However, one schema I work with is extremely large and is broken into many different files via "<xs:include schemaLocation=""/>". This schema does not appear to load correctly via getResourceAsStream.
I suspect this may be a classloader issue inside JNLP. When I run the application using the same JARs via javaw on the Windows machine, everything works.
What am I doing wrong and how do I go about working around/fixing this issue?
Thanks,
--David                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Here is some code that works around the issue:
    public static URL getResource(Class clazz, String name) {
        // Get the URL for the resource using the standard behavior
        URL result = clazz.getResource(name);
        // Check to see that the URL is not null and that it's a JAR URL.
        if (result != null && "jar".equalsIgnoreCase(result.getProtocol())) {
            // Get the URL to the "clazz" itself.  In a JNLP environment, the "getProtectionDomain" call should succeed only with properly signed JARs.
            URL classSourceLocationURL = clazz.getProtectionDomain().getCodeSource().getLocation();
            // Create a String which embeds the classSourceLocationURL in a JAR URL referencing the desired resource.
            String urlString = MessageFormat.format("jar:{0}!/{1}/{2}", classSourceLocationURL.toExternalForm(), packageNameOfClass(clazz).replaceAll("\\.", "/"), name);
            // Check to see that new URL differs.  There's no reason to instantiate a new URL if the external forms are identical (as happens on pre-1.5.0_16 builds of the JDK).
            if (urlString.equals(result.toExternalForm()) == false) {
                // The URLs are different, try instantiating the new URL.
                try {
                    result = new URL(urlString);
                } catch (MalformedURLException malformedURLException) {
                    throw new RuntimeException(malformedURLException);
        return result;
    public static String packageNameOfClass(Class clazz) {
        String result = "";
        String className = clazz.getName();
        int lastPeriod = className.lastIndexOf(".");
        if (lastPeriod > -1) {
            result = className.substring(0, lastPeriod);
        return result;
    }There are two additional work-arounds:
1. Use Class.getResourceAsStream(String). However this doesn't work in the case of XSDs that use <xs:include> to include other XSDs via relative pathing.
2. A real hack: Class.getResource("MyResource.txt").openConnection().getURL().

Similar Messages

  • Problem with Class.getResource()

    I am trying to load a jar file dynamicaly like,
    ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
    URLClassLoader m_ClassLoader = new URLClassLoader(new URL[] {new URL(sV1JarPath)}, prevClassLoader);
    But after doing this if I try to load a resource from the "prevClassLoader " like,
    MyClass.class.getResource("path"); where MyClass is loaded by prevClassLoader, it is not working. It fails to load the resource.
    Can anyone help me correct this issue?
    Thanks
    Unni

    try "/path".I am giving it like
    MyClass.class.getResource("images/" + name); where there is an images packages in side the package where MyClass resides.
    But here the problem is as MyClass is in the prevClassLoader and it is not able to find it when we call Class.getResource()

  • Jnlp issue

    Unable to open jar all through jnlp file .
    My jnlp look like
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+"
      codebase="file:///D:/Build/"
    >
    <information>
      <title>MyApp</title>
      <vendor>Java Developer Connection</vendor> 
    </information>
    <offline-allowed/>
    <security>
      <j2ee-application-client-permissions/>
    </security>
    <resources>
      <j2se version="1.2+" />
      <jar href="MyApp.jar"/>
    </resources>
    <application-desc main-class="Myclass"/>
    </jnlp>MyApp.jar this jar need other jar as well to run which are present at same location .
    App starts loading loading but nothing happens .. what can be the issue ?
    Please suggest some solution

    AmitChalwade123456 wrote:
    But my app uses 50 jar file
    do i need to add jar separatelyYes.
    and do i need to sign each jar ??Yes. Beware if you're using third-party jars, some of them may already be signed. In that case, you have to build a jnlp file for each different signature and add a reference of the file to the main jnlp file. For the jars you're signing yourself, you may referenced them in the main jnlp file. They must all have the same signature than the main jar.
    Here's an example using Javamail ( the jar is already signed by the manufacturer ) :
    In the main jnlp :
             <jar href="MyApp.jar" main="true"/>
                <extension name="Java Mail" href="mail.jnlp"/>
                <jar href="Other.jar"/>
    The mail.jnlp content :
    <?xml version = '1.0' encoding = 'utf-8'?>
        <jnlp spec="1.0+" codebase="file:///D:/Build/" href="mail.jnlp">
         <information>
                <title>JavaMail</title>
             <vendor>Sun Microsystems, Inc.</vendor>
         </information>
         <security>
                <all-permissions/>
         </security>
            <resources>
                <jar href="mail.jar"/>
            </resources>
            <component-desc/>
        </jnlp>

  • How to use class.getResource() to create an ImageIcon

    Hi,
    I am well acquainted with creating and using ImageIcon icons using the ImageIcon constructor
    and putting the image file in a folder called Images which is at the same level as the
    bin and src folders.
    I discovered a demo program, LayeredPaneDemo, that uses class.getResource() to create
    an icon and found that in my eclipse version, the icon's image file was not found when
    I used the original getResource() call but the icon was created when I used the ImageIcon
    constructor.
    I posted on JavaRanch and eventually realized that the image file needed to be with the
    .class files, so I moved the Images folder under bin and getResource() works fine and I'm
    happy.
    However, I have three questions for you.
    One poster on JavaRanch told me that it's better to use getResource() rather than the
    ImageIcon constructor for distributing an app (I'm not distributing anything but want
    to do it all correctly).
    Do you agree with that or can I safe keep using the ImageIcon constructor?
    Another poster told me he doesn't think it's safe to leave the image file in bin because
    it might be lost during the build in eclipse and that there is a way to have eclipse copy
    the files to bin during the build which should mean that I can leave the images folder at
    the level of bin and src.
    Do you agree with that?
    If yes, how do I get eclipse to copy the file during the build?
    P.S.
    Before I posted on JavaRanch, I put the Images folder at every level of the project's
    directory as shown in eclipse (which is why I missed the bin folder until JavaRanch
    whacked me upside the head) and getResource() still didn't work.

    The contents of the Java Source folder are compiled if they're source files, copied otherwise (assuming no filter's been put in place to prevent copying), so your images belong under a source folder.

  • Why got Nullpointer use getJarPath.class.getResource(".").getPath() ?

    hi,
    I have a question about the following program:
    public class getJarPath {
    public getJarPath() {
    public static void main(String[] arg) {
    System.out.println("java.net.URl->" + getJarPath.class.getResource(
    "getJarPath.class"));
    System.out.println("getPath->" + getJarPath.class.getResource(
    "getJarPath.class").getPath());
    System.out.println("getFile->" + getJarPath.class.getResource(
    "getJarPath.class").getFile());
    System.out.println("getPath with . ->"+getJarPath.class.getResource(".").getPath()); // NullPointer occured
    1. compile getJarPath.java
    D:\>D:\j2sdk1.4.2_04\bin\javac getJarPath.java
    2. run this test program with "java getJarPath"
    D:\>D:\j2sdk1.4.2_04\bin\java getJarPath
    java.net.URl->file:/D:/getJarPath.class
    getPath->/D:/getJarPath.class
    getFile->/D:/getJarPath.class
    getPath with . ->/C:/Program%20Files/exceed.nt/
    3. D:\>D:\j2sdk1.4.2_04\bin\jar cvf getJarPath.jar getJarPath.class
    4. D:\>D:\j2sdk1.4.2_04\bin\java -cp d:\getJarPath.jar getJarPath
    java.net.URl->jar:file:/D:/getJarPath.jar!/getJarPath.class
    getPath->file:/D:/getJarPath.jar!/getJarPath.class
    getFile->file:/D:/getJarPath.jar!/getJarPath.class
    Exception in thread "main" java.lang.NullPointerException
    at getJarPath.main(getJarPath.java:15)
    question:
    in step 2. why the path "." is "/C:/Program%20Files/exceed.nt/" ?
    in step 4. why NullPointerException occured?
    thank a lot
    BR

    Your output seems to indicate that all lines executed successfully, yet you say there's a NullPointerException. Which is it?

  • Different result with class.getResource/ getClassLoader ...

    There is something about resource loading I don't understand. According to the api the method getResource() calls the ClassLoader for loading the given resource. But the following example shows a difference:
    package testPackage;
    public class Test
        public static void main(String[] args)
            Test t = new Test();
            System.out.println(Test.class.getResource("testPackage/test.class")); 
    System.out.println(Test.class.getClassLoader().getResource("testPackage/test.class"));
            System.out.println(t.getClass().getResource("testPackage/test.class"));
    System.out.println(t.getClass().getClassLoader().getResource("testPackage/test.class"));
    }The resulting output is:
    null
    file:/C:/.../bin/testPackage/test.class
    null
    file:/C:/.../bin/testPackage/test.classHow can this difference be explained?

    There is something about resource loading I don't
    understand. According to the api the method
    getResource() calls the ClassLoader for loading the
    given resource. As noted, the API also explains the algorithm used to get an absolute resource name from the initial resource name, before delegating to the classloader.
    Basically, a package name prefix is added if the name is not absolute (i.e doesn't start with a leading slash).

  • Class.getResource(String)....how to use it?

    I know i nedd to use this to access some wav files in a jar, but i can't figure out how. Could some kind person give me a demo.
    my wav file is called "boring.wav" it's in the same directory as the class file. How do implement the code to access this file from the jar archive?
    thanx
    Peter

    Use
    ClassLoader classLoader =
    ClassLoader.getSystemClassLoader();
    URL propsURL = classLoader.getResource(fileName);
    inStream = propsURL.openStream();
    Then read the contents from the stream
    ClassLoader looks for resources in the classpathLooks good. I just wanted to make a quick note. The System Class Loader is the bootstrap classloader that loads up the class containing main. Some deployment systems (Java Web Start) imediately start up thier own class loader to do the rest of the work. So the system class loader becomes useless. In these cases you would use this.getClass().getClassLoader() instead. It's a small point, but Jars were asked about. ;)

  • Register plugin in OIM11g-class not found issue

    Hi All,
    I have a plugin created and imported the metadata.
    I have also made the plugin.zip with the necessary structure.
    now whenever i restart my oim to see if my plugin has been initialized its gives
    <Aug 8, 2011 9:03:06 AM CEST> <Error> <oracle.iam.platform.pluginframework> <IAM-1050006> <An error occurred while loading the plugin class. Class com.test.oim.adapter.entity.testwas not found.>
    any guesses what cd be the issue
    I have double ckeced witth my pakage structure,n didnt found any typo mistake as such

    Did you resolve this issue? Is it something related to compilation issue?

  • Template member function of a class template specialisation issue

    The following bit of code from gmock (http://code.google.com/p/googlemock/) caused CC 5.9 ( and Studio Express) to emit:
    "./include/gmock/gmock-printers.h", line 418: Error: static testing::internal::TuplePrefixPrinter<testing::internal::N>::PrintPrefixTo<testing::internal::TuplePrefixPrinter<testing::internal::N>::Tuple>(const testing::internal::TuplePrefixPrinter<testing::internal::N>::Tuple&, std::ostream *) already had a body defined.
    Code:
    template <size_t N>
    struct TuplePrefixPrinter {
    // Prints the first N fields of a tuple.
    template <typename Tuple>
    static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
    TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
    *os << ", ";
    UniversalPrinter<typename ::std::tr1::tuple_element<N - 1, Tuple>::type>
    ::Print(::std::tr1::get<N - 1>(t), os);
    // Tersely prints the first N fields of a tuple to a string vector,
    // one element for each field.
    template <typename Tuple>
    static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
    TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
    ::std::stringstream ss;
    UniversalTersePrint(::std::tr1::get<N - 1>(t), &ss);
    strings->push_back(ss.str());
    template <>
    template <typename Tuple>
    void TuplePrefixPrinter<1>::PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
    UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>::
    Print(::std::tr1::get<0>(t), os);
    Removing the inline definition of TuplePrefixPrinter from the class and adding it after the specialisation fixed the issue.
    Ian.

    Hi, Ian. Please file a bug report at bugs.sun.com so we can track the problem.
    - Steve

  • Class & int/String issues

    Upon compiling, I am receiving the following errors:
    TeamRosterApp.java:153: cannot find symbol
    symbol : class ButtonPanel
    location: class TeamRosterPanel
    ButtonPanel buttonPanel;
    ^
    TeamRosterApp.java:166: cannot find symbol
    symbol : class ButtonPanel
    location: class TeamRosterPanel
    buttonPanel = new ButtonPanel();
    ^
    2 errors
    I've included the code below, but I having difficulty understanding why it cannot find the ButtonPanel class when that class is specified in the code (Line 364).
    Thanks in advance for your help!
    //Modified by Doe, John 20OCT2007
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.JTextComponent;
    import java.util.ArrayList;
    import java.text.*;
    import java.lang.*;
    import java.util.*;
    public class TeamRosterApp
         public static void main(String[] args)
              TeamIO.getTeam();
                    JFrame frame = new TeamRosterFrame();
                    frame.setVisible(true);
    class Player
         String lname;
         String fname;
         int number;
         public Player()
              lname = "";
              fname = "";
              number = 0;
         public Player(String lname, String fname, int number)
              this.lname = lname;
              this.fname = fname;
              this.number = number;
         public void setLastName(String lname)
              this.lname = lname;
         public String getLastName()
              return lname;
         public void setFirstName(String fname)
              this.fname = fname;
         public String getFirstName()
              return fname;
         public void setNumber(int number)
              this.number = number;
         public int getNumber()
              return number;
    class TeamIO
         private static final ArrayList<Player> team = new ArrayList<Player>();
         public static ArrayList<Player> getTeam()
              team.add(new Player("Doe", "John", 69));
              team.add(new Player("Berg", "Laura", 44));
              team.add(new Player("Bustos", "Crystl", 6));
              team.add(new Player("Clark", "Jamie", 24));
              team.add(new Player("Fernandez", "Lisa", 16));
              team.add(new Player("Finch", "Jennie", 27));
              team.add(new Player("Flowers", "Tairia", 11));
              team.add(new Player("Freed", "Amanda", 7));
              team.add(new Player("Giordano", "Nicole", 4));
              team.add(new Player("Harrigan", "Lori", 21));
              team.add(new Player("Jung", "Lovieanne", 3));
              team.add(new Player("Kretchman", "Kelly", 12));
              team.add(new Player("Lappin", "Lauren", 37));
              team.add(new Player("Mendoza", "Jessica", 2));
              team.add(new Player("O'Brien-Amico", "Lisa", 20));
              team.add(new Player("Nuveman", "Stacy", 33));
              team.add(new Player("Osterman", "Catherine", 8));
              team.add(new Player("Topping", "Jennie", 31));
              team.add(new Player("Watley", "Natasha", 29));
              System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              for(int i = 0; i < team.size(); i++)
                   Player p = (Player)team.get(i);
                   System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
                   System.out.println("****************************************");
              return new ArrayList<Player>(team);
         public static ArrayList<Player> saveTeam()
              System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              for(int i = 0; i < team.size(); i++)
              Player p = (Player)team.get(i);
              System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
              System.out.println("****************************************");
              return new ArrayList<Player>(team);
    class TeamRosterFrame extends JFrame
        public TeamRosterFrame()
            String me = "Campbell, Corey";
              String date;
              Date now = new Date();
              DateFormat longDate = DateFormat.getDateInstance(DateFormat.LONG);
              date = longDate.format(now);
              setTitle("Team Roster "+me+" "+date);
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(new TeamRosterPanel());
            this.pack();
            centerWindow(this);
        private void centerWindow(Window w)
            Toolkit tk = Toolkit.getDefaultToolkit();
            Dimension d = tk.getScreenSize();
            setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    class TeamRosterPanel extends JPanel
         ArrayList<Player>team;
         Player newPlayer = null;
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         public TeamRosterPanel()
              // fill the team ArrayList
              team = TeamIO.getTeam();
              // add the panels
              setLayout(new GridBagLayout());
              selectorPanel = new teamSelectorPanel();
              add(selectorPanel, getConstraints(0,0,1,1, GridBagConstraints.WEST));
              playerPanel = new PlayerDisplayPanel();
              add(playerPanel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
              buttonPanel = new ButtonPanel();
              add(buttonPanel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
              // set the initial player to be displayed
              playerPanel.showPlayer(team.get(0));
              selectorPanel.selectPlayer(team.get(0));
         // a method for setting grid bag constraints
         private GridBagConstraints getConstraints(int gridx, int gridy,
              int gridwidth, int gridheight, int anchor)
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(5, 5, 5, 5);
              c.ipadx = 0;
              c.ipady = 0;
              c.gridx = gridx;
              c.gridy = gridy;
              c.gridwidth = gridwidth;
              c.gridheight = gridheight;
              c.anchor = anchor;
              return c;
         class teamSelectorPanel extends JPanel implements ActionListener
              public JComboBox    playerComboBox;
              private JLabel      playerLabel;
              boolean filling = false;            // used to indicate the combo box is being filled
              public teamSelectorPanel()
                   // set panel layout
                   setLayout(new FlowLayout(FlowLayout.LEFT));
                   // Player label
                   playerLabel = new JLabel("Select Player:");
                   add(playerLabel);
                   // Player combo box
                   playerComboBox = new JComboBox();
                   fillComboBox(team);
                   playerComboBox.addActionListener(this);
                   add(playerComboBox);
              public void actionPerformed(ActionEvent e)
                   if (!filling)
                        Player p = (Player)playerComboBox.getSelectedItem();
                        playerPanel.showPlayer(p);
              public void fillComboBox(ArrayList<Player> team)
              filling = true;
              playerComboBox.removeAllItems();
              for (Player p : team)
              playerComboBox.addItem(p);
              filling = false;
              public void selectPlayer(Player p)
                   playerComboBox.setSelectedItem(p);
              public Player getCurrentPlayer()
                   return (Player) playerComboBox.getSelectedItem();
         class PlayerDisplayPanel extends JPanel
              public JTextField   lastNameTextField,
                   firstNameTextField,
                   numberTextField;
              private JLabel      lastNameLabel,
                   firstNameLabel,
                   numberLabel;
              public PlayerDisplayPanel()
                   // set panel layout
                   setLayout(new GridBagLayout());
                   // last name label
                   lastNameLabel = new JLabel("Last name:");
                   add(lastNameLabel, getConstraints(0,0,1,1, GridBagConstraints.EAST));
                   // last name text field
                   lastNameTextField = new JTextField(10);
                   lastNameTextField.setEditable(false);
                   lastNameTextField.setFocusable(false);
                   lastNameTextField.addFocusListener(new AutoSelect());
                   add(lastNameTextField, getConstraints(1,0,1,1, GridBagConstraints.WEST));
                   // first name label
                   firstNameLabel = new JLabel("First name:");
                   add(firstNameLabel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
                   // first name text field
                   firstNameTextField = new JTextField(30);
                   firstNameTextField.setEditable(false);
                   firstNameTextField.setFocusable(false);
                   firstNameTextField.addFocusListener(new AutoSelect());
                   add(firstNameTextField, getConstraints(1,1,1,1, GridBagConstraints.WEST));
                   // number label
                   numberLabel = new JLabel("Number:");
                   add(numberLabel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
                   // number text field
                   numberTextField = new JTextField(10);
                   numberTextField.setEditable(false);
                   numberTextField.setFocusable(false);
                   numberTextField.addFocusListener(new AutoSelect());
                   numberTextField.addKeyListener(new IntFilter());
                   add(numberTextField, getConstraints(1,2,1,1, GridBagConstraints.WEST));
              public void showPlayer(Player p)
                   lastNameTextField.setText(p.getLastName());
                   firstNameTextField.setText(p.getFirstName());
                   numberTextField.setText(String.valueOf(p.getNumber()));
              public void clearFields()
                   lastNameTextField.setText("");
                   firstNameTextField.setText("");
                   numberTextField.setText("");
              // return a new Player object with the data in the text fields
              public Player getPlayer()
                   Player p = new Player();
                   p.setLastName(lastNameTextField.getText());
                   p.setFirstName(firstNameTextField.getText());
                   int n = Integer.parseInt(numberTextField.getText());
                   p.setNumber(n);
                   return p;
              public void setAddEditMode(boolean e)
                   lastNameTextField.setEditable(e);
                   lastNameTextField.setFocusable(e);
                   lastNameTextField.requestFocusInWindow();
                   firstNameTextField.setEditable(e);
                   firstNameTextField.setFocusable(e);
                   numberTextField.setEditable(e);
                   numberTextField.setFocusable(e);
              class AutoSelect implements FocusListener
                   public void focusGained(FocusEvent e)
                        if(e.getComponent() instanceof JTextField)
                             JTextField t = (JTextField) e.getComponent();
                             t.selectAll();
                   public void focusLost(FocusEvent e){}
              class IntFilter implements KeyListener
                   public void keyTyped(KeyEvent e)
                        char c = e.getKeyChar();
                        if ( c !='0' && c !='1' && c !='2' && c !='3' && c !='4' && c !='5'
                             && c !='6' && c !='7' && c !='8' && c !='9')
                             e.consume();
                   public void keyPressed(KeyEvent e){}
                   public void keyReleased(KeyEvent e){}
              class ButtonPanel extends JPanel
                   public JButton addButton,
                        editButton,
                        deleteButton,
                        acceptButton,
                        cancelButton,
                        exitButton;
                   public ButtonPanel()
                        // create maintenance button panel
                        JPanel maintPanel = new JPanel();
                        maintPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
                        // add button
                        addButton = new JButton("Add");
                        addButton.addActionListener(new AddListener());
                        maintPanel.add(addButton);
                        // edit button
                        editButton = new JButton("Edit");
                        editButton.addActionListener(new EditListener());
                        maintPanel.add(editButton);
                        // delete button
                        deleteButton = new JButton("Delete");
                        deleteButton.addActionListener(new DeleteListener());
                        maintPanel.add(deleteButton);
                        // accept button
                        acceptButton = new JButton("Accept");
                        acceptButton.setEnabled(false);
                        acceptButton.addActionListener(new AcceptListener());
                        maintPanel.add(acceptButton);
                        // cancel button
                        cancelButton = new JButton("Cancel");
                        cancelButton.setEnabled(false);
                        cancelButton.addActionListener(new CancelListener());
                        maintPanel.add(cancelButton);
                        // create exit button panel
                        JPanel exitPanel = new JPanel();
                        exitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
                        // exit button
                        exitButton = new JButton("Exit");
                        exitButton.addActionListener(new ExitListener());
                        exitPanel.add(exitButton);
                        // add panels to the ButtonPanel
                        setLayout(new BorderLayout());
                        add(maintPanel, BorderLayout.CENTER);
                        add(exitPanel, BorderLayout.SOUTH);
                   public void setAddEditMode(boolean e)
                        addButton.setEnabled(!e);
                        editButton.setEnabled(!e);
                        deleteButton.setEnabled(!e);
                        acceptButton.setEnabled(e);
                        cancelButton.setEnabled(e);
              class AddListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        newPlayer = new Player();
                        playerPanel.clearFields();
                        buttonPanel.setAddEditMode(true);
                        playerPanel.setAddEditMode(true);
              class EditListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        buttonPanel.setAddEditMode(true);
                        playerPanel.setAddEditMode(true);
              class DeleteListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        Player p = selectorPanel.getCurrentPlayer();
                        team.remove(p);
                        TeamIO.saveTeam();
                        selectorPanel.fillComboBox(team);
                        selectorPanel.selectPlayer(team.get(0));
                        playerPanel.showPlayer(team.get(0));
                        selectorPanel.playerComboBox.requestFocusInWindow();
              class AcceptListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        if (isValidData())
                             if (newPlayer != null)
                                  newPlayer = playerPanel.getPlayer();
                                  team.add(newPlayer);
                                  TeamIO.saveTeam();
                                  selectorPanel.fillComboBox(team);
                                  selectorPanel.selectPlayer(newPlayer);
                                  newPlayer = null;
                             else
                                  Player p = selectorPanel.getCurrentPlayer();
                                  Player newPlayer = playerPanel.getPlayer();
                                  p.setLastName(newPlayer.getLastName());
                                  p.setFirstName(newPlayer.getFirstName());
                                  p.setNumber(newPlayer.getNumber());
                                  TeamIO.saveTeam();
                                  selectorPanel.fillComboBox(team);
                                  selectorPanel.selectPlayer(p);
                                  playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
                             playerPanel.setAddEditMode(false);
                             buttonPanel.setAddEditMode(false);
                             selectorPanel.playerComboBox.requestFocusInWindow();
                   public boolean isValidData()
                        return SwingValidator.isPresent(playerPanel.lastNameTextField, "Last Name")
                             && SwingValidator.isPresent(playerPanel.firstNameTextField, "First Name")
                             && SwingValidator.isPresent(playerPanel.numberTextField, "Number")
                             && SwingValidator.isInteger(playerPanel.numberTextField, "Number");
              class CancelListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        if (newPlayer != null)
                             newPlayer = null;
                        playerPanel.setAddEditMode(false);
                        playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
                        buttonPanel.setAddEditMode(false);
                        selectorPanel.playerComboBox.requestFocusInWindow();
              class ExitListener implements ActionListener
                   public void actionPerformed(ActionEvent e)
                        System.exit(0);
    }Swing Validator Code:
    //Programmed by Doe, John 20OCT2007
    import javax.swing.*;
    import javax.swing.text.JTextComponent;
    public class SwingValidator
         public static boolean isPresent(JTextComponent c, String title)
              if(c.getText().length()==0)
                   showMessage(c, title + " is a required field.\n" + "Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
              return true;
         public static boolean isInteger(JTextComponent c, String title)
              try
                   int i = Integer.parseInt(c.getText());
                   return true;
              catch(NumberFormatException e)
                   showMessage(c,title+" must be an integer.\n"+"Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
         private static void showMessage(JTextComponent c, String message)
              JOptionPane.showMessageDialog(c, message, "Invalid Entry", JOptionPane.ERROR_MESSAGE);
    }Edited by: kc0poc on Oct 21, 2007 8:17 AM

    Ok. Got it, understand it now. Corrected all 58 errors after created the top level classes. It compiles, but I'm now encountering a NullPointerException:
    Exception in thread "main" java.lang.NullPointerException
    at teamSelectorPanel.fillComboBox(TeamRosterAppTest.java:233)
    at teamSelectorPanel.<init>(TeamRosterAppTest.java:214)
    at TeamRosterPanel.<init>(TeamRosterAppTest.java:164)
    at TeamRosterFrame.<init>(TeamRosterAppTest.java:135)
    at TeamRosterAppTest.main(TeamRosterAppTest.java:17)
    I think I am not initializing something correctly and it involved the "team" variable. Thoughts anyone?
    Thank you as always!
    Below is my code:
    //Modified by Campbell, Corey 20OCT2007
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.JTextComponent;
    import java.util.ArrayList;
    import java.text.*;
    import java.lang.*;
    import java.util.*;
    public class TeamRosterAppTest
         public static void main(String[] args)
              TeamIO.getTeam();
              JFrame frame = new TeamRosterFrame();
              frame.setVisible(true);
    class Player
         String lname;
         String fname;
         int number;
         public Player()
              lname = "";
              fname = "";
              number = 0;
         public Player(String lname, String fname, int number)
              this.lname = lname;
              this.fname = fname;
              this.number = number;
         public void setLastName(String lname)
              this.lname = lname;
         public String getLastName()
              return lname;
         public void setFirstName(String fname)
              this.fname = fname;
         public String getFirstName()
              return fname;
         public void setNumber(int number)
              this.number = number;
         public int getNumber()
              return number;
    class TeamIO
         private static final ArrayList<Player> team = new ArrayList<Player>();
         public static ArrayList<Player> getTeam()
              team.add(new Player("Campbell", "Corey", 69));
              team.add(new Player("Berg", "Laura", 44));
              team.add(new Player("Bustos", "Crystl", 6));
              team.add(new Player("Clark", "Jamie", 24));
              team.add(new Player("Fernandez", "Lisa", 16));
              team.add(new Player("Finch", "Jennie", 27));
              team.add(new Player("Flowers", "Tairia", 11));
              team.add(new Player("Freed", "Amanda", 7));
              team.add(new Player("Giordano", "Nicole", 4));
              team.add(new Player("Harrigan", "Lori", 21));
              team.add(new Player("Jung", "Lovieanne", 3));
              team.add(new Player("Kretchman", "Kelly", 12));
              team.add(new Player("Lappin", "Lauren", 37));
              team.add(new Player("Mendoza", "Jessica", 2));
              team.add(new Player("O'Brien-Amico", "Lisa", 20));
              team.add(new Player("Nuveman", "Stacy", 33));
              team.add(new Player("Osterman", "Catherine", 8));
              team.add(new Player("Topping", "Jennie", 31));
              team.add(new Player("Watley", "Natasha", 29));
              //System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              //for(int i = 0; i < team.size(); i++)
              //          Player p = (Player)team.get(i);
              //          System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
              //System.out.println("****************************************");
              return new ArrayList<Player>(team);
         public static ArrayList<Player> saveTeam()
              System.out.println("\nOpening team list" + "\n\n" + "****************************************");
              for(int i = 0; i < team.size(); i++)
                   Player p = (Player)team.get(i);
                   System.out.print(p.getNumber() + "\t" + p.getLastName() + "," + p.getFirstName() + "\n");
              System.out.println("****************************************");
              return new ArrayList<Player>(team);
    class TeamRosterFrame extends JFrame
         public TeamRosterFrame()
              String me = "Campbell, Corey";
              String date;
              Date now = new Date();
              DateFormat longDate = DateFormat.getDateInstance(DateFormat.LONG);
              date = longDate.format(now);
              setTitle("Team Roster "+me+" "+date);
              setResizable(false);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.add(new TeamRosterPanel());
              this.pack();
              centerWindow(this);
         private void centerWindow(Window w)
              Toolkit tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    class TeamRosterPanel extends JPanel
         ArrayList<Player>team;
         Player newPlayer = null;
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         public TeamRosterPanel()
              // fill the team ArrayList
              team = TeamIO.getTeam();
              // add the panels
              setLayout(new GridBagLayout());
              selectorPanel = new teamSelectorPanel();
              add(selectorPanel, getConstraints(0,0,1,1, GridBagConstraints.WEST));
              playerPanel = new PlayerDisplayPanel();
              add(playerPanel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
              buttonPanel = new ButtonPanel();
              add(buttonPanel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
              // set the initial player to be displayed
              playerPanel.showPlayer(team.get(0));
              selectorPanel.selectPlayer(team.get(0));
         // a method for setting grid bag constraints
         private GridBagConstraints getConstraints(int gridx, int gridy,
              int gridwidth, int gridheight, int anchor)
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(5, 5, 5, 5);
              c.ipadx = 0;
              c.ipady = 0;
              c.gridx = gridx;
              c.gridy = gridy;
              c.gridwidth = gridwidth;
              c.gridheight = gridheight;
              c.anchor = anchor;
              return c;
    class teamSelectorPanel extends JPanel implements ActionListener
         public JComboBox playerComboBox;
         private JLabel playerLabel;
         boolean filling = false;            // used to indicate the combo box is being filled
         ArrayList<Player>team;
         PlayerDisplayPanel playerPanel;
         public teamSelectorPanel()
              // set panel layout
              setLayout(new FlowLayout(FlowLayout.LEFT));
              // Player label
              playerLabel = new JLabel("Select Player:");
              add(playerLabel);
              // Player combo box
              playerComboBox = new JComboBox();
              fillComboBox(team);
              playerComboBox.addActionListener(this);
              add(playerComboBox);
         public void actionPerformed(ActionEvent e)
              if (!filling)
                   Player p = (Player)playerComboBox.getSelectedItem();
                   playerPanel.showPlayer(p);
         public void fillComboBox(ArrayList<Player> team)
              filling = true;
              playerComboBox.removeAllItems();
              for (Player p : team)
              playerComboBox.addItem(p);
              filling = false;
         public void selectPlayer(Player p)
              playerComboBox.setSelectedItem(p);
         public Player getCurrentPlayer()
              return (Player) playerComboBox.getSelectedItem();
    class PlayerDisplayPanel extends JPanel
         public JTextField lastNameTextField,
              firstNameTextField,
              numberTextField;
         private JLabel lastNameLabel,
              firstNameLabel,
              numberLabel;
         public PlayerDisplayPanel()
              // set panel layout
              setLayout(new GridBagLayout());
              // last name label
              lastNameLabel = new JLabel("Last name:");
              add(lastNameLabel, getConstraints(0,0,1,1, GridBagConstraints.EAST));
              // last name text field
              lastNameTextField = new JTextField(10);
              lastNameTextField.setEditable(false);
              lastNameTextField.setFocusable(false);
              lastNameTextField.addFocusListener(new AutoSelect());
              add(lastNameTextField, getConstraints(1,0,1,1, GridBagConstraints.WEST));
              // first name label
              firstNameLabel = new JLabel("First name:");
              add(firstNameLabel, getConstraints(0,1,1,1, GridBagConstraints.EAST));
              // first name text field
              firstNameTextField = new JTextField(30);
              firstNameTextField.setEditable(false);
              firstNameTextField.setFocusable(false);
              firstNameTextField.addFocusListener(new AutoSelect());
              add(firstNameTextField, getConstraints(1,1,1,1, GridBagConstraints.WEST));
              // number label
              numberLabel = new JLabel("Number:");
              add(numberLabel, getConstraints(0,2,1,1, GridBagConstraints.EAST));
              // number text field
              numberTextField = new JTextField(10);
              numberTextField.setEditable(false);
              numberTextField.setFocusable(false);
              numberTextField.addFocusListener(new AutoSelect());
              numberTextField.addKeyListener(new IntFilter());
              add(numberTextField, getConstraints(1,2,1,1, GridBagConstraints.WEST));
         public void showPlayer(Player p)
              lastNameTextField.setText(p.getLastName());
              firstNameTextField.setText(p.getFirstName());
              numberTextField.setText(String.valueOf(p.getNumber()));
         public void clearFields()
              lastNameTextField.setText("");
              firstNameTextField.setText("");
              numberTextField.setText("");
         // return a new Player object with the data in the text fields
         public Player getPlayer()
              Player p = new Player();
              p.setLastName(lastNameTextField.getText());
              p.setFirstName(firstNameTextField.getText());
              int n = Integer.parseInt(numberTextField.getText());
              p.setNumber(n);
              return p;
         public void setAddEditMode(boolean e)
              lastNameTextField.setEditable(e);
              lastNameTextField.setFocusable(e);
              lastNameTextField.requestFocusInWindow();
              firstNameTextField.setEditable(e);
              firstNameTextField.setFocusable(e);
              numberTextField.setEditable(e);
              numberTextField.setFocusable(e);
         // a method for setting grid bag constraints
         private GridBagConstraints getConstraints(int gridx, int gridy,
              int gridwidth, int gridheight, int anchor)
              GridBagConstraints c = new GridBagConstraints();
              c.insets = new Insets(5, 5, 5, 5);
              c.ipadx = 0;
              c.ipady = 0;
              c.gridx = gridx;
              c.gridy = gridy;
              c.gridwidth = gridwidth;
              c.gridheight = gridheight;
              c.anchor = anchor;
              return c;
    class AutoSelect implements FocusListener
         public void focusGained(FocusEvent e)
              if(e.getComponent() instanceof JTextField)
                   JTextField t = (JTextField) e.getComponent();
                   t.selectAll();
         public void focusLost(FocusEvent e){}
    class IntFilter implements KeyListener
         public void keyTyped(KeyEvent e)
              char c = e.getKeyChar();
              if ( c !='0' && c !='1' && c !='2' && c !='3' && c !='4' && c !='5'
                   && c !='6' && c !='7' && c !='8' && c !='9')
                   e.consume();
         public void keyPressed(KeyEvent e){}
         public void keyReleased(KeyEvent e){}
    class ButtonPanel extends JPanel
         public JButton addButton,
              editButton,
              deleteButton,
              acceptButton,
              cancelButton,
              exitButton;
         public ButtonPanel()
              // create maintenance button panel
              JPanel maintPanel = new JPanel();
              maintPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              // add button
              addButton = new JButton("Add");
              addButton.addActionListener(new AddListener());
              maintPanel.add(addButton);
              // edit button
              editButton = new JButton("Edit");
              editButton.addActionListener(new EditListener());
              maintPanel.add(editButton);
              // delete button
              deleteButton = new JButton("Delete");
              deleteButton.addActionListener(new DeleteListener());
              maintPanel.add(deleteButton);
              // accept button
              acceptButton = new JButton("Accept");
              acceptButton.setEnabled(false);
              acceptButton.addActionListener(new AcceptListener());
              maintPanel.add(acceptButton);
              // cancel button
              cancelButton = new JButton("Cancel");
              cancelButton.setEnabled(false);
              cancelButton.addActionListener(new CancelListener());
              maintPanel.add(cancelButton);
              // create exit button panel
              JPanel exitPanel = new JPanel();
              exitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
              // exit button
              exitButton = new JButton("Exit");
              exitButton.addActionListener(new ExitListener());
              exitPanel.add(exitButton);
              // add panels to the ButtonPanel
              setLayout(new BorderLayout());
              add(maintPanel, BorderLayout.CENTER);
              add(exitPanel, BorderLayout.SOUTH);
         public void setAddEditMode(boolean e)
              addButton.setEnabled(!e);
              editButton.setEnabled(!e);
              deleteButton.setEnabled(!e);
              acceptButton.setEnabled(e);
              cancelButton.setEnabled(e);
    class AddListener implements ActionListener
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         Player newPlayer;
         public void actionPerformed(ActionEvent e)
              newPlayer = new Player();
              playerPanel.clearFields();
              buttonPanel.setAddEditMode(true);
              playerPanel.setAddEditMode(true);
    class EditListener implements ActionListener
         ButtonPanel buttonPanel;
         PlayerDisplayPanel playerPanel;
         public void actionPerformed(ActionEvent e)
              buttonPanel.setAddEditMode(true);
              playerPanel.setAddEditMode(true);
    class DeleteListener implements ActionListener
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ArrayList<Player>team;
         public void actionPerformed(ActionEvent e)
              Player p = selectorPanel.getCurrentPlayer();
              team.remove(p);
              TeamIO.saveTeam();
              selectorPanel.fillComboBox(team);
              selectorPanel.selectPlayer(team.get(0));
              playerPanel.showPlayer(team.get(0));
              selectorPanel.playerComboBox.requestFocusInWindow();
    class AcceptListener implements ActionListener
         teamSelectorPanel selectorPanel;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         ArrayList<Player>team;
         Player newPlayer;
         public void actionPerformed(ActionEvent e)
              if (isValidData())
                   if (newPlayer != null)
                        newPlayer = playerPanel.getPlayer();
                        team.add(newPlayer);
                        TeamIO.saveTeam();
                        selectorPanel.fillComboBox(team);
                        selectorPanel.selectPlayer(newPlayer);
                        newPlayer = null;
                   else
                        Player p = selectorPanel.getCurrentPlayer();
                        Player newPlayer = playerPanel.getPlayer();
                        p.setLastName(newPlayer.getLastName());
                        p.setFirstName(newPlayer.getFirstName());
                        p.setNumber(newPlayer.getNumber());
                        TeamIO.saveTeam();
                        selectorPanel.fillComboBox(team);
                        selectorPanel.selectPlayer(p);
                        playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
                   playerPanel.setAddEditMode(false);
                   buttonPanel.setAddEditMode(false);
                   selectorPanel.playerComboBox.requestFocusInWindow();
         public boolean isValidData()
              return SwingValidator.isPresent(playerPanel.lastNameTextField, "Last Name")
                   && SwingValidator.isPresent(playerPanel.firstNameTextField, "First Name")
                   && SwingValidator.isPresent(playerPanel.numberTextField, "Number")
                   && SwingValidator.isInteger(playerPanel.numberTextField, "Number");
    class CancelListener implements ActionListener
         Player newPlayer;
         PlayerDisplayPanel playerPanel;
         ButtonPanel buttonPanel;
         teamSelectorPanel selectorPanel;
         public void actionPerformed(ActionEvent e)
              if (newPlayer != null)
                   newPlayer = null;
              playerPanel.setAddEditMode(false);
              playerPanel.showPlayer(selectorPanel.getCurrentPlayer());
              buttonPanel.setAddEditMode(false);
              selectorPanel.playerComboBox.requestFocusInWindow();
    class ExitListener implements ActionListener
         public void actionPerformed(ActionEvent e)
              System.exit(0);
    class SwingValidator
         public static boolean isPresent(JTextComponent c, String title)
              if(c.getText().length()==0)
                   showMessage(c, title + " is a required field.\n" + "Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
              return true;
         public static boolean isInteger(JTextComponent c, String title)
              try
                   int i = Integer.parseInt(c.getText());
                   return true;
              catch(NumberFormatException e)
                   showMessage(c,title+" must be an integer.\n"+"Please re-enter.");
                   c.requestFocusInWindow();
                   return false;
         private static void showMessage(JTextComponent c, String message)
              JOptionPane.showMessageDialog(c, message, "Invalid Entry", JOptionPane.ERROR_MESSAGE);
    }

  • Moving a method from one class to another issues

    Hi, im new. Let me explain what i am trying to achieve. I am basically trying to move a method from one class to another in order to refactor the code. However every time i do, the program stops working and i am struggling. I have literally tried 30 times these last two days. Can some one help please? If shown once i should be ok, i pick up quickly.
    Help would seriously be appreciated.
    Class trying to move from, given that this is an extraction:
    class GACanvas extends Panel implements ActionListener, Runnable {
    private WorldMenuItems speedMenuItems, designMenuItemsPlantGrowth, designMenuItemsPlantCount;
         private WorldMenuItems designMenuItemsPlantEaten, designMenuItemsApproximatePopulation;
         private WorldMenuItems designMenuItemsEatersBorn,designMenuItemsMutationProbability;
         private WorldMenuItems designMenuItemsCrossoverProbability;
    MenuBar getMenuBar() {
              menuBar = new MenuBar();
              addControlItemsToMenuBar();
              addSpeedItemsToMenuBar();
              addWorldDesignItemsToMenuBar();
              return menuBar;
    This is the method i am trying to move (below)
    public void itemsInsideWorldDesignMenu() {
              designMenuItemsPlantGrowth = new WorldMenuItems("Plants Grow",
                        new String[] { "In Rows", "In Clumps", "At Random",
                                  "Along the Bottom", "Along the Edges" }, 1);
              designMenuItemsPlantCount = new WorldMenuItems("Number Of Plants",
                        new String[] { "50", "100", "150", "250", "500" }, 3);
              designMenuItemsPlantEaten = new WorldMenuItems("When a Plant is Eaten",
                        new String[] { "It grows back somewhere",
                                  "It grows back nearby", "It's Gone" }, 0);
              designMenuItemsApproximatePopulation = new WorldMenuItems(
                        "Approximate Population", new String[] { "10", "20", "25",
                                  "30", "40", "50", "75", "100" }, 2);
              designMenuItemsEatersBorn = new WorldMenuItems("Eaters are Born",
                        new String[] { "At the Center", "In a Corner",
                                  "At Random Location", "At Parent's Location" }, 2);
              designMenuItemsMutationProbability = new WorldMenuItems(
                        "Mutation Probability", new String[] { "Zero", "0.25%", "0.5%",
                                  "1%", "2%", "3%", "5%", "10%" }, 3);
              designMenuItemsCrossoverProbability = new WorldMenuItems(
                        "Crossover Probability", new String[] { "Zero", "10%", "25%",
                                  "50%", "75%", "100%" }, 4);
    Class Trying to move to:
    class WorldMenuItems extends Menu implements ItemListener {
       private CheckboxMenuItem[] items;
       private int selectedIndex = -1;
       WorldMenuItems(String menuName, String[] itemNames) {
          this(menuName, itemNames, -1);
       WorldMenuItems(String menuName, String[] itemNames, int selected) {
          super(menuName);
          items = new CheckboxMenuItem[itemNames.length];
          for (int i = 0; i < itemNames.length; i++) {
             items[i] = new CheckboxMenuItem(itemNames);
    add(items[i]);
    items[i].addItemListener(this);
    selectedIndex = selected;
    if (selectedIndex < 0 || selectedIndex >= items.length)
    selectedIndex = 1;
    items[selectedIndex].setState(true);
         public int getSelectedIndex() {
              return selectedIndex;
    public void itemStateChanged(ItemEvent evt) {  // This works on other systems
    CheckboxMenuItem newSelection = (CheckboxMenuItem)evt.getSource();
    for (int i = 0; i < items.length; i++) {
    if (newSelection == items[i]) {
    items[selectedIndex].setState(false);
    selectedIndex = i;
    newSelection.setState(true);
    return;

    Ok i've done this. I am getting an error on the line specified. Can someone help me out and tell me what i need to do?
    GACanvas
    //IM GETTING AN ERROR ON THIS LINE UNDER NAME, SAYING IT IS NOT VISIBLE
    WorldMenuItems worldmenuitems = new WorldMenuItems(name, null);
    public MenuBar getMenuBar() {
              menuBar = new MenuBar();
              addControlItemsToMenuBar();
              addSpeedItemsToMenuBar();
              worldmenuitems.addWorldDesignItemsToMenuBar();
              return menuBar;
    class WorldMenuItems extends Menu implements ItemListener {
         private WorldMenuItems speedMenuItems, designMenuItemsPlantGrowth, designMenuItemsPlantCount;
         private WorldMenuItems designMenuItemsPlantEaten, designMenuItemsApproximatePopulation;
         private WorldMenuItems designMenuItemsEatersBorn,designMenuItemsMutationProbability;
         private WorldMenuItems designMenuItemsCrossoverProbability;
         GACanvas gacanvas = new GACanvas(null);
       private CheckboxMenuItem[] items;
       private int selectedIndex = -1;
       WorldMenuItems(String menuName, String[] itemNames) {
          this(menuName, itemNames, -1);
       WorldMenuItems(String menuName, String[] itemNames, int selected) {
          super(menuName);
          items = new CheckboxMenuItem[itemNames.length];
          for (int i = 0; i < itemNames.length; i++) {
             items[i] = new CheckboxMenuItem(itemNames);
    add(items[i]);
    items[i].addItemListener(this);
    selectedIndex = selected;
    if (selectedIndex < 0 || selectedIndex >= items.length)
    selectedIndex = 1;
    items[selectedIndex].setState(true);
         public int getSelectedIndex() {
              return selectedIndex;
    public void itemStateChanged(ItemEvent evt) {  // This works on other systems
    CheckboxMenuItem newSelection = (CheckboxMenuItem)evt.getSource();
    for (int i = 0; i < items.length; i++) {
    if (newSelection == items[i]) {
    items[selectedIndex].setState(false);
    selectedIndex = i;
    newSelection.setState(true);
    return;
    public void itemsInsideWorldDesignMenu() {
         designMenuItemsPlantGrowth = new WorldMenuItems("Plants Grow",
                   new String[] { "In Rows", "In Clumps", "At Random",
                             "Along the Bottom", "Along the Edges" }, 1);
         designMenuItemsPlantCount = new WorldMenuItems("Number Of Plants",
                   new String[] { "50", "100", "150", "250", "500" }, 3);
         designMenuItemsPlantEaten = new WorldMenuItems("When a Plant is Eaten",
                   new String[] { "It grows back somewhere",
                             "It grows back nearby", "It's Gone" }, 0);
         designMenuItemsApproximatePopulation = new WorldMenuItems(
                   "Approximate Population", new String[] { "10", "20", "25",
                             "30", "40", "50", "75", "100" }, 2);
         designMenuItemsEatersBorn = new WorldMenuItems("Eaters are Born",
                   new String[] { "At the Center", "In a Corner",
                             "At Random Location", "At Parent's Location" }, 2);
         designMenuItemsMutationProbability = new WorldMenuItems(
                   "Mutation Probability", new String[] { "Zero", "0.25%", "0.5%",
                             "1%", "2%", "3%", "5%", "10%" }, 3);
         designMenuItemsCrossoverProbability = new WorldMenuItems(
                   "Crossover Probability", new String[] { "Zero", "10%", "25%",
                             "50%", "75%", "100%" }, 4);
    public void addWorldDesignItemsToMenuBar() {
         gacanvas = new GACanvas(null);
         itemsInsideWorldDesignMenu();
         Menu designMenuItems = new Menu("WorldDesign");
         designMenuItems.add(designMenuItemsPlantGrowth);
         designMenuItems.add(designMenuItemsPlantCount);
         designMenuItems.add(designMenuItemsPlantEaten);
         designMenuItems.add(designMenuItemsApproximatePopulation);
         designMenuItems.add(designMenuItemsEatersBorn);
         designMenuItems.add(designMenuItemsMutationProbability);
         designMenuItems.add(designMenuItemsCrossoverProbability);
         gacanvas.menuBar.add(designMenuItems);

  • JNDI lookup couldn't find any objects in MBean class and -userThreads issue

    Hi,
    We had used some MBean classes in a jboss j2ee project. Now we need to migrate it to oc4j. We also need to use Thread class and jndi looking up in these MBean classes.
    I encountered two problems when I migrate these MBeans.
    1. The first problem is:
    If I create a InitialContext object just like the following:
    InitialContext result = new InitialContext();
    Then I lookup an ejb,I can't find anything from this InitialContext.
    However,If I create a InitialContext object just like below:
    Properties props = new Properties();
    props.put( Context.PROVIDER_URL, "***" );
    props.put( Context.INITIAL_CONTEXT_FACTORY, "***");
    //props.put( Context.URL_PKG_PREFIXES, "***" );
    props.put( Context.SECURITY_PRINCIPAL, "***");
    props.put( Context.SECURITY_CREDENTIALS, "***" );
    InitialContext result = new InitialContext(props);
    I can find that ejb. Why?
    Is it possible to get InitialContext just like InitialContext result = new InitialContext()?
    2. The second problem is:
    I had used a thread class to do the above mentioned jndi looking up in one MBean method. This method is not be invoked by oc4j EM. It is invoked by another class. There is an exception throws just like below:
    javax.naming.NamingException: Not in an application scope - start OC4J with the -userThreads switch if using user-created threads
    I had add -userThreads argument in the startup command just like below:
    java -Xdebug -Xnoagent -Djava.compiler=NONE -Doc4j.jmx.security.proxy.off=true -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4000 -Dnl=en_US %JAVA_OPTS% %JAVA_SYSPROP% -jar %ORACLE_HOME%/j2ee/home/oc4j.jar
    -userThreads
    Does anyone know why there is an jndi problem in MBean class?
    Thanks,
    Eternal

    Hi,
    We had used some MBean classes in a jboss j2ee project. Now we need to migrate it to oc4j. We also need to use Thread class and jndi looking up in these MBean classes.
    I encountered two problems when I migrate these MBeans.
    1. The first problem is:
    If I create a InitialContext object just like the following:
    InitialContext result = new InitialContext();
    Then I lookup an ejb,I can't find anything from this InitialContext.
    However,If I create a InitialContext object just like below:
    Properties props = new Properties();
    props.put( Context.PROVIDER_URL, "***" );
    props.put( Context.INITIAL_CONTEXT_FACTORY, "***");
    //props.put( Context.URL_PKG_PREFIXES, "***" );
    props.put( Context.SECURITY_PRINCIPAL, "***");
    props.put( Context.SECURITY_CREDENTIALS, "***" );
    InitialContext result = new InitialContext(props);
    I can find that ejb. Why?
    Is it possible to get InitialContext just like InitialContext result = new InitialContext()?
    2. The second problem is:
    I had used a thread class to do the above mentioned jndi looking up in one MBean method. This method is not be invoked by oc4j EM. It is invoked by another class. There is an exception throws just like below:
    javax.naming.NamingException: Not in an application scope - start OC4J with the -userThreads switch if using user-created threads
    I had add -userThreads argument in the startup command just like below:
    java -Xdebug -Xnoagent -Djava.compiler=NONE -Doc4j.jmx.security.proxy.off=true -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4000 -Dnl=en_US %JAVA_OPTS% %JAVA_SYSPROP% -jar %ORACLE_HOME%/j2ee/home/oc4j.jar
    -userThreads
    Does anyone know why there is an jndi problem in MBean class?
    Thanks,
    Eternal

  • Class has be instantiated in document class but having issue..HELP

    Guys,
    I am making my way with AS3 in little steps and have hit a
    road block. This is what I have:
    I have a document class called "Document Class"
    I have a custom class called "Game"
    I have instantiated an object of "Game" class and I am able
    to trace a class method which return a simple "HELLO".
    within my Game class, I have a variable(type Array) called
    "questions" as instance variable.
    I would like to add questions to "questions" array by using
    "Mutator" method, or count the current elements with the questions
    array and return the total number of questions. I am unable to add
    or access elements to the questions array.
    Any help would highly be appreciated, please.

    First thing: you need to set the functions you're calling to
    public, so that you have access to them outside of your class.
    Second: you are initializing 'questions' to null. I made some
    changes and it seems to work for me:
    //////////////Game
    Class///////////////////////////////////////////////
    public function Game()
    //this.questions = null;
    this.correctAnswers = null;
    this.userAnswers = null;
    // SETQUESTION FUNCTION CAN ADD QUESTIONS TO THE QUESTION
    ARRAY;
    public function myArr():void
    trace(questions.length);
    public function AddQuestions(val:String)
    this.questions.push(val);
    trace(val);
    }

  • Classes and Methods Issues

    I can't seem to figure out how to get a method to print without returning to main. I am importing time from the method just above this one but cannot make it a constant because I change the time later on in the program. Nor can I change the main program. This is the code snippet of the method...
         public void convert(int time)
              /*convert*/     
              if (time < 12)
                   System.out.println(time + " months have gone by.");
              else if (time > 12)
                        int years = time / 12;
                        int months = time % 12;
                        System.out.print(years + " year(s) and " + months + " month(s) have passed.");
    This is the call to that snippet in main...
         /*calling the method convert() in class homes*/
         homes.convert(time);
    This is the error that I get...
    Exception in thread "main" java.lang.NoSuchMethodError: homes.convert(I)I
    at HomeTime.main(HomeTime.java:28)

    This code shouldn't be compiling if you are getting the error you are.
    My guess is that you have not compiled all of your classes, or you have a mixture of old and new classes in the same classpath.
    Also, make sure that your methods are declared inside the class - not inside methods inside the class. I've seen some folks who are new to Java make the mistake of trying to declare a method inside the main() method.
    If the code is actually compiling without any errors, please post what you've got (read the help file on how to post code to the forum first!) and I'll give it a shot.
    - Kevin

  • Package/Class name resolution issue

    Hey guys!
    I have an application called Infused. I also have a package called Managers with a class called DataManager which extends HTTPService.
    In a function in DataManager I need to call a public function that exists in Infused.
    Now, if the application is called Infused, then it's default class must be called Infused too, right?
    But when I called Infused.loginResult(evt) I get the error: Access of possibly undefined method loginResult through a reference with static type Class.
    I assumed the applications class would be in the global namespace and accessible. Am I wrong? And if so how can I call the function?
    Also, in the applications main class I have a number of functions called xxxResult which I need to call depending on a string that is passed in to the class request function. So the request function may receive 'login', and so the function to call in Infused would be 'loginResult'.
    How can I call the function based on this string? I know I could do Class[functionName]() if the function where in the same class, but will the answe to my first question lead to the obvious solution for the second?
    I am a PHP5 OOP developer learning Flex, so please forgive my dumbassness
    Thanks for any help.
    Paul.

    But when I called Infused.loginResult(evt) I get the error: Access of
    possibly undefined method loginResult through a reference with static
    type Class.
    You can't call instance methods like that. You'd need to make the method static, or alternately, call Infused(Application.application).loginResult(evt). After you make either change, you should be able to use the ['functionName']() approach.
    Keep in mind, though, that you're coupling your DataManager to your application with this approach. This might be fine for a small app, but take a look at Mate (or some of the other MVC frameworks) to see how to reduce or avoid this sort of coupling.

Maybe you are looking for

  • "message could not be delivered"

    MAILER-DAEMON are replying that message can not be delivered when sendin to my mac addresses!? this started last night. I'm sorry to have to inform you that your message could not be delivered to one or more recipients. It's attached below. For furth

  • Vendor Master External Number range

    Hi, There is a single number range object for vendor account groups you have suppose five different account groups suppose for LIEF i am using internal number range starting with 10..up to 10 digit for Vedor i am using external say A to ZZZZ up to 10

  • Another 7110 CIF problem!

    I'm exporting the same file system as a CIF and NFS share. I have created a file on the CIF share, I can read, write, modify fine. I get permission denied with trying to modify the same file on the NFS mount. I can see the file, but when I try and do

  • Quicktime errors with .mov's captured in premiere. HELP!

    I captured video through Adobe Premiere CS3 to a FAT32 external. It stopped twice during capture before I changed it to capture to the computers internal HD. I went back to retrieve the files that had stopped during capture. and the .mov files cannot

  • Macbook freezes when I play 720p movies

    I bought my macbook back in early 2008 and now it runs on OS X Tiger. Recently, I find that whenever I use realplayer to play 720p movies....my macbook would free at some random spot and I'd have no other ways of closing the program other than physic