Creating array of objects of class which extends Thread

getting NullPointerException
can i not create thread array this way?
class sample extends Thread
{ int i,id;
  public sample(int c)
   { id=c;
  public void run()
  { for(i=0;i<6;i++)
     System.out.println("Thread "+id+" "+i);
public class thread extends Frame implements ActionListener
{  Button b1;
   sample s[];
   thread()
   { for(int i=0;i<2;i++)
          s=new sample(i);
     setLayout(new FlowLayout());
     b1=new Button("OK");
     add(b1);
     b1.addActionListener(this);
     public void actionPerformed(ActionEvent e)
     {   b1.setEnabled(false);
          for(int i=0;i<2;i++)
          { s[i]=new sample(i);
          s[i].start();
     public static void main(String args[])
     { thread t1=new thread(); 
     t1.setVisible(true);
     t1.setSize(150,150);

You need:
sample [] s = new sample[2];However
1) You should get into the habit that class names start with capital letters, variable and field names with lower case.
2) It's not a good idea to extend Thread, make a class which implements the Runnable interface and hook a standard Thread object to that.

Similar Messages

  • Calls to methods in a class that extends Thread

    Hello,
    I have some code that I am initiating from within an ActionListener that is part of my programs GUI. The code is quite long winded, at least in terms of how long it takes to perform. The code runs nicely, however once it is running the GUI freezes completely until operations have completed. This is unacceptable as the code can take up to hours to complete. After posting a message on this forum in regard to the freezing of the GUI it was kindly suggested that I use multi-threading to avoid the unwelcome program behaviour.
    The code to my class is as follows:
    public class FullURLAddress
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    I have changed the above code to make use of multithreading by making this class extend Thread and implementing the run() method as follows:
    public class FullURLAddress extends Thread
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
      public void run()
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    /* What happens with these methods, will they need to have their
    own treads also? */
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    Are there any special things that I need to do in regard to the variables returned by the getCount() and xurlAddressDetails() methods. These methods are called by the code that started the run method from within my GUI. I don't understand which thread these methods are running in, obviously there is an AWT thread for my GUI and then a seperate thread for my FullURLAddress objects, but does this new thread also encompass the getCount() and xurlAddressDetails() methods?
    Please explain.
    This probably sounds a little wack, but I don't understand what thread is responisble for the methods in my FullURLAddress class aside of course from the run() method which is obvious. Any help will be awesome.
    Thanks
    Davo

    Threads are part of code that allows you to run multiple operations "simultaneously". "Simultaneously", because threads are not run actually simultaneously in any one-CPU machine. Since you most propably have only one CPU in your system, you can only execute one CPU instruction at time. Basically this means that your CPU can handle only one java-operation at time. It does not matter if you put some code in thread and start it, it will still take up all CPU time as long as the thread runs.
    So you would need a way to let other threads run also, for that purpose thread contains a yield feature that allows you to give time for other threads to run.
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Thread.html#yield()
    You need to use thread's yield() method in your thread code, in a place you want to give other threads time to run. Also bear in mind that if you yield your first thread run to allow second thread to run, you also need to add yield to the second thread also. If you don't, after yielding the first thread, the second thread will eat up all CPU time until it finishes, thus meaning the rest of your first thread will be run after second thread is done.
    One good place to execute yield() is usually at the end of a loop, for example 'for' or 'while' loop. This way you prevent for example while-deadlocks.
    Here is a java thread tutorial, worthy reading:
    http://java.sun.com/docs/books/tutorial/essential/threads/

  • Assigning ThreadGroup to a Class that Extends Thread

    How can i assign a thread group to a class running as a thread that extends thread without changing the class to implement Runnable?
    An Example of the application format:
    public class Application implements Runnable
    private ThreadGroup main = new ThreadGroup("Main");
    private Thread mainThread = null;
    public Application()
    public void start()
    if (mainThread == null)
    mainThread = new Thread(main,"main")
    mainThread.start();
    public void run()
    Thread current = Thread.currentThread();
    while(current != null)
    while(something to do)
    AThread a = new AThread();
    a.start();
    String aData = a.getData();
    BThread b = new BThread(data);
    b.start();
    String bData = b.getData();
    class AThead extends Thread
    public AThread()
    //What to do with AThread to assign it to a thread group?
    public void run()
    Basically the application works form a main constructor class running the application class as a thread. The application class will then launch AThread and BThread as subthreads. I would like to be able to count how many of each type of thread is running for the AThread and BThread. I tried using AThread and BThread implementing Runnable to create a thread under a group but it wouldn't work. The application class needs to get information from the AThread and BThread threads once the thread was done, but if the AThread and BThread was implementing Runnable, the Applicaiton Class can't get the data or run methods. Is there some way i can assign what thread group AThread and BThread will run as in thier class files and not the Application class?

    See: http://java.sun.com/j2se/1.4/docs/api/java/lang/Thread.html#Thread(java.lang.ThreadGroup, java.lang.String)
    I think this does what you want:
    public class Application implements Runnable
    private ThreadGroup main = new ThreadGroup("Main");
    private ThreadGroup aThreads = new ThreadGroup("AThreads"); // Added a thread group for all AThread objects
    private Thread mainThread = null;
    public Application()
    public void start()
      if (mainThread == null)
        mainThread = new Thread(main,"main")
        mainThread.start();
      public void run()
        Thread current = Thread.currentThread();
        while(current != null)
          while(something to do)
            AThread a = new AThread(aThreads);  // Create an AThread that will belong to aThreads ThreadGroup
            a.start();
            String aData = a.getData();
            BThread b = new BThread(data);
            b.start();
            String bData = b.getData();
    class AThead extends Thread
      public AThread(ThreadGroup group)
        super(group, "AThread"); // This will make a new Thread that belongs to ThreadGroup group, see link above
      public void run()
    }

  • How to create an instance of a class which is actually an array?

    the following code gives a runtime exception
    Object obj = (Object )attributeClass.newInstance();
    Exception:
    java.lang.InstantiationException: [Ltest.Name;[/b]
    Here test.Name is user defined class and i want to create an array instance of that class.
    I have tried the following also:
    [b]Object methodArgs[] = new Object[length];
    for(int j=0;j<length;++j){
    methodArgs[j] = singleMemberClass.cast(testArray[j]);
    Object temp = attributeClass.cast(methodArgs);
    In the above code singleMemberClass is test.Name, but the last line gives the following exception.
    java.lang.ClassCastException
    Message was edited by:
    lalit_mangal
    Message was edited by:
    lalit_mangal

    Try the following code
    import java.lang.reflect.Array;
    public class TestReflection {
         public static void main(String args[]) {
              Object array = Array.newInstance(A.class, 3);
              printType(array);
         private static void printType(Object object) {
              Class type = object.getClass();
              if (type.isArray()) {
                   System.out.println("Array of: " + elementType);
              System.out.println("Array size: " + Array.getLength(object));
    class A{
    }

  • Invoke a panel object in a class which extends JFrame

    I have a class LoginUI which extends JFrame and another class NewUserUI which extends JPanel. The LoginUI contains a button which when clicked should display the NewUserUI panel in a separate window. How should I invoke the NewUserUI object in the LoginUI class?

    One possibility would be the use of a JOptionPane containing the JPanel.
    Cheers
    DB

  • Create a new class which extends DataGrid

    Can someone give me a simple example on how to create a new
    class that extends DataGrid. Still having a little trouble
    understanding classes.
    Thanks for any help.
    Jeremy

    import mx.controls.DataGrid
    public class MyGrid extends DataGrid {
    It is pretty much as you would extend a class in Java

  • Creating array of objects of JLabel , JTextField type

    hello,
    I wanted to create an array of objects of JLabel class. I wrote and complied the following lines. it was successfully compiled but during execution it showed - 'start: applet not initialized' on the applet's window. What wrong have I done and how can I get rid of that?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[];
         public void init()
                   for( int i = 0; i < 10; i++ )
                   lb[i] = new JLabel( "Line" + i );
                   c.add( lb[i] );
    }

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[] = new JLabel[10];
         public void init()
                   for( int x = 0; x < 10; x++ )
                   lb [x]= new JLabel( "Line" + x );
                   c.add( lb );
    // showing applet not initiliazed
    // generating nullPointerException
    // please helpLast post, thats a promise!!! :-)Still wrong. See corrections in 'for' loop. :)

  • Creating stubs for a java class which implements ejbobject and ejbHome

    Hi,
    I am using the weblogic rmic utility to generate WLStub of a class which implements
    EJBHome and EJBObject. The stubs are being generated with the name...WLStub261b2l255i2g1h1324e2u702w6fn1t.class
    rather than with the name_WLStub as it should be and as the server wants it to
    be when I try to bind this object using JNDI.
    I appreciate your help.
    Thanks,
    Kamps

    Have you tried the -nomanglednames option as from:
    Usage: java weblogic.rmic [options] <classes>...
    where options include:
    -help Print this help message.
    -version Print version information.
    -d <dir> Target (top-level) directory for compilation.
    -nontransactional Suspends the transaction before making the
    RMI call and resumes after
    -verbosemethods Instruments proxies to print debug info to
    std err.
    -descriptor <example> Associates or creates a descriptor for each
    remote class.
    -nomanglednames Don't mangle the names of the stubs and
    skeletons.
    kamps wrote:
    >
    Hi,
    I am using the weblogic rmic utility to generate WLStub of a class which implements
    EJBHome and EJBObject. The stubs are being generated with the name...WLStub261b2l255i2g1h1324e2u702w6fn1t.class
    rather than with the name_WLStub as it should be and as the server wants it to
    be when I try to bind this object using JNDI.
    I appreciate your help.
    Thanks,
    Kamps

  • Retrieve method from class which extends JFrame

    hi, i need some help with my program.
    I have two class which both extends JFrame. The first class called security class and second class is available class.
    In the SECURITY class, i create a button to operate the AVAILABLE class and it generate a result in method Count(). I want to view the result in Frame SECURITY by calling method count() but i could manage to do it. Could somebody help me how to manage this problem?
    Thanks.

    may be you could create a instance of the class you wanted to access method from or pass the instance from one class to another.
    like this:
    public class A extends JFrame
    public B newB= new B();
    public A(){}
    public void someMethod()
    newB.someOtherMethod();
    public class B extends JFrame
    public B(){}
    public void someOtherMethod()
    i hope it is what you are looking for

  • Array of objects in class private data and calling overridden VIs on these objects?

    Hello
    I am developing part of an application using the actor framework and have run into problems.
    I have a several actors and will try briefly describe them and their intended functionality. All actors are started by a Controller actor and in the actor core for the controller I have the possibility to do a lot of intiliazation etc.
    Logger:
    Has a message (Send Log Message) that other actors can use to write to the log. It is supposed to take a string input and a log level (error, warning, debug etc). This message chain sends data to the actor core with a user event.
    The Actor Core of Logger is supposed to save the incoming message to a log, but should be able to do it in several different ways (file, database, email or whatever).
    Logger Output:
    Abstract class that has a dynamic dispatch vi called "Write Output" that all it's children are supposed to overwrite.
    Logger Output File
    Child of Logger Output and overwrites "Write Output" to save the string to a file on disk.
    Problem:
    I want to be able to set up the actor core for Logger once and for all but still be able to create new children of "Logger Output" and have them be handled in the Logger actor core.
    My idea was to have Logger use an array of objects as private data and initialize this array in the Controller actor core.
    In the logger actor core I could then auto index the array and use each element (each Logger Output child) and the abstract "Write Output" vi to get the correct functionality.
    HOWEVER, I cannot get this to work properly and I think I have misunderstood something or stared myself blind on this problem. I have tried 3 different methods when it comes to private data for Logger.
    1. Labview Object
    2. Array of Labview Object
    3. Array of Logger Output Object
    Of these 3 methods, I can only get the first one to work and that doesn't accomplish what I want in the end (being able to add more classes without changing private data / actor core for Logger).
    I have included 3 screenshots that show snippets of 2 of the actor cores and the private data. File names should correspond to my description above.
    The screenshot "Logger actor core.png" shows a very fast test of the 3 different methods I described above. Each of the 3 tunnel inputs to the event structure can be wired to the "Reference" input of "To More Specific Class", but only method 1 (Labview Object) works.
    If you need additional information / screenshots or whatever please ask.
    Thanks in advance
    Attachments:
    Logger ctl.PNG ‏8 KB
    Logger actor core.PNG ‏25 KB
    Controller Actor Core.PNG ‏11 KB

    Thanks for the reply and sorry for the confusing OP. It was meant as a quick test and a way to skip making 10+ screenshots .
    I updated the actor core for the Controller and Logger to be less confusing (hopefully) and attached 2 screenshots.
    I agree with you that it would be a good idea to make a message for the controller that can launch new children of the L" abstract actor, but for these tests I have just launched it the easy way (dragging it to the controller actor core).
    Both Logger Output and Logger Output File are actors and in Logger Output there is a dynamic dispatch vi called Write Output that I want to override in all its children.
    The problem is when I run the actor core of Logger (see the screenshot) only the abstract version (the one in Logger Output) of Write Output is executed, not the overridden version from Logger Output File.
    When I did the same thing with the actor cores looking like the did in my original post, then the correct overridden version got executed when I used the method with one Labview Object in private data (not any array or an array of Logger Output objects).
     EDIT: I just tried to have the Logger private data be a single Logger Output object and writing the Logger Output File to that piece of private data in the Controller and the correct Write Output override method gets called now. So apparently I have done something stupid when it comes to creating the array of Logger Output objects and writing them in the controller? The private data is in the Logger actor so I have simply right clicked and chosen "New VI for Data Member Access" and chosen "Write" for "Element of Array of Logger Output Objects".
    Attachments:
    Controller Actor core updated.PNG ‏10 KB
    Logger actor core updated.PNG ‏24 KB

  • How to create a view object and attach with extended AM

    Hi,
    I tried to create new vo and attach this vo with the extended AM. But it is throwing error like 'PC.NAME : invalid identifier' (Actually this PC.NAME is exiting one).
    Now i want to know how to create a view object similar like seeded one but with one additional condition in the where clause.
    It is possible though extension, but i want to create two view object similar like seeded one, one with some other condition in the where clause
    and another one with some other condition.
    So for my requirement, i'll extend one VO and i'll add my condition but how to do it for second condition.
    But i want same seeded VO with two different condition.
    Any suggestions please,
    SAN

    SAN,
    There is no need to attach the newly created VO with extended AM. You need to attach the same with the standard AM.
    Regards,
    Gyan

  • LoadClass    (error loading a class which extends other class  at run-time)

    Hey!
    I'm using the Reflection API
    I load a class called 'SubClass' which exists in a directory called 'subdir' at run-time from my program
    CustomClassLoader loader = new CustomClassLoader();
    Class classRef = loader.loadClass("SubClass");
    class CustomClassLoader extends ClassLoader. I have defined 'findClass(String className)' method in CustomClassLoader.
    This is what 'findClass(String className)' returns:
    defineClass (className,byteArray,0,byteArray.length);
    'byteArray' is of type byte[] and has the contents of subdir/SubClass.
    the problem:
    The program runs fine if SubClass does not extend any class.
    If however, SubClass extends another class, the program throws a NoClassDefFoundError. How is it conceptually different?
    Help appreciated in Advance..
    Thanks!

    Because i'm a newbie to the Reflection thing, i'm notI don't see reflection anywhere. All I see is class loading.
    sure what role does the superclass play when i'm
    trying to load the derived class and how to get away
    with the errorWell... hint: all the superclass's stuff is not copied into the subclass.
    I am quite sure it fails to load the superclass because of classpath issues.

  • How to create an instance of a class which is stored in a String?

    I've class name stored in a String Object.
    now i've to create an instance of that class name.
    How?

    This is very dangerous ground because you give up compile-time safety, but you can get a Class object using Class.forName(String). Then you can use methods of the class Class to operate on it (including creating an instance).

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

  • Creating array of object

    Using JNI, I'm trying to pass an array of object from the C native side to
    the Java side. I have the following code:
    JNIEXPORT jint JNICALL Java_classA_methodB(
    JNIenv *env,
    jobject obj,
    jobjectArray objArr )
    jclass objClass = ( *env )->FindClass( env, "arrObjClass" );
    jmethodID methodID = ( *env )->GetMethodID( env, objClass, "<init>", "()V" ); // Default constructor
    jobject objElement = ( *env )->NewObject( env, objClass, methodID );
    // ... Fill objElement with values
    ( *env )->SetObjectArrayElement( env, objArr, 0, objElement ); // <-- program core dumps here.  WHY? 
    return 1;
    The program core dumps at the line above and I don't understand why?
    objArr is originally set to null when pass to the native function. Does
    objArr have to be allocated using new before pass to the native function?
    Thank you in advance,
    Duong

    You seem to be trying to write into an array passed as an input argumenet, when you haven't in fact passed an array object.
    (At least that's what I interpreted you to say what you are doing.)
    Either construct an array in java and pass it to C++, or if that is probelmatic, then change the C++ return object from an int to an array, and do the construction in C++.

Maybe you are looking for

  • Preview increases pdf file size when saving

    When I save a PDF journal article using Preview, it often increases the file size by 2x - 4x, regardless of whether I have added annotations. In the attached image, you can see I downloaded a journal article (2.3 MB), opened it in Preview, duplicated

  • HP B110a multifunction ceases to function after Hp Update

    I have HP Photosmart B110a multifunction printer which ceases to work after applying "HP notification of Updates". Cannot print or access HP Solution Centre (nothing works). Only solution is to use the installation CD to completely uninstall the HP s

  • Internet/Mail issues

    I have searched through this (and other) forums but haven't been able to find an answer. I have just upgraded to ADSL2 in australia. Here are my issues. I can browse (Safari 2.0.4 and 3beta) bou only SOME pages. Even www.apple.com.au will only load t

  • I want to skip some html code part when refersh the page, how can we know

    Hi, i want to skip some html code part when refersh the page, how can we know when we pressed refresh button or F5 key thanks in advance....

  • Safari Crash When Microsoft Scrollwheel Used Over Quicktime Movie

    Lets say I have a Quicktime Movie displayed in a web page opened in Safari. If I put the cursor over the movie and scroll up and down with the scroll wheel, the movie will go into scrub mode briefly before completely crashing the system. The computer