JButton in inner class  cuasing Null Pointer Excp

Ok so i have this class called "square" and in it there is a JButton. There is a method called createButton() and getButton().
In create button it takes the classes JButton called button and instantiates:
public void createButton() {
button = new JButton("");
and
public JButton getButton() {
return button;
Now I make a frame and a panel in a upper class called "program" and i make a multidimensional array of squares. Then i make call createButton() for each square.
Then later on I call
panel.add(square[z][q].getButton());
Now all of this compiles fine but when i run it i get a null pointer exception on the line above. Why????
Thanks,
PS: 5 duke dollars for person who helps me.

What I think is happening is you are doing something like this (Where 'Square' is the name of the class that creates the button):
Square square[8][8] = new Square[8][8];
The problem is that this does not create the actual square objects. It simply creates an array that can hold the square objects but all the objects in the array are null. You should just initialized the objects by using two for loops:
Square square[8][8] = new Square[8][8];
for(int x = 0; x = square.length; x++)
for(int y = 0; y = square[x].length; y++)
square[x][y] = new Square(---);
That will put things into the array and they won't be null.

Similar Messages

  • Can enclosing instance for an inner class be null?

    I have a class Solution, which defines an inner class, SolutionStep.
    In a third class I construct several SolutionStep objects, and later use them to construct a Solution.
    In this third class I have statements like this:
    Solution solution = null;
    aCollection.add(solution.new SolutionStep(arg1, arg2);
    This has been working fine, but recently a customer reported an error,which seems to be a NullPointerException at the line above.
    Now that I look at this code, I'm not very happy about it and I'll clean it up, but I am left with the basic question of whether what I'm doing is legal. Can the enclosing instance used to construct an inner class be null? I have not been able to find a definitive answer.
    Any help appreciated.

    Yes, you're right, I dropped a parenthesis. Sorry.
    The offending statement is actually
    aCollection.add(solution.new SolutionStep(arg1,
    arg2));
    And that is certainly legal. The inner class does not
    need to be qualified when it's constructed in the
    context of an enclosing instance.Very interesting.
    The following code demonstrates this....
        class Solution
            class SolutionStep
                public SolutionStep()
        public class ThirdClass
            static public void main(String[] args)
            Solution solution = null;
            //Solution solution = new Solution();  // This produces no null exception.
            Solution.SolutionStep s = solution.new SolutionStep();
    Using jikes and javac doesn't change the behavior so that means it is VM rather than compiler specific.
    I am using 1.4.2_04 on windows and I get the null pointer exception.
    Looking at the javap output suggests that invokespecial has to be checking this (although I could have overlooked something when I checked.)
    This probably comes from the following in the VM spec under invokespecial...
    Otherwise, if objectref is null, the invokespecial instruction throws a NullPointerException.

  • Null pointer exception with inner class

    Hi everyone,
    I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
    java.lang.NullPointerException      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)      
    at Rotary$animateArea.paintComponent(Rotary.java:251)      
    at javax.swing.JComponent.paint(JComponent.java:808)      
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)      
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)      
    at javax.swing.JComponent._paintImmediately(JComponent.java:4668)      
    at javax.swing.JComponent.paintImmediately(JComponent.java:4477)      
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)      
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)      
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)      
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)      
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)      
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)      
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Do inner classes have to be compiled seperately or anything?
    Thanks a million for you time,
    CurtinR

    I think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
    Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
    This is the code for the applet:
    import java.applet.*;
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.util.StringTokenizer;
    import java.net.*;
    public class Rotary extends JApplet implements ActionListener, MouseListener
    public boolean rotating;
    private Timer timer;
    private int delay = 1000;
    private AffineTransform transform;
    private JTextArea txtTest; //temp
    private Container c;
    private animateArea wheelPanel;
    private JButton btPlay, btStop;
    private BoxLayout layout;
    private JPanel btPanel;
    public Image wheel;
    public int currentSector;
    public String members[];
    public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
    final int TOTAL_SECTORS= 48;
    //creates polygon array - each polygon represents a sector on wheel
    public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
    polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
    polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
    polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
    polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
    public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
                      polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
                      polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
                      polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
                      polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
    public void init()
    members = new String[TOTAL_SECTORS];
    coordsX= new int[TOTAL_SECTORS][4];
    coordsY= new int[TOTAL_SECTORS][4];
    currentSector = -1;
    rotating = true;
    transform = new AffineTransform();
    //***********************************Create GUI**************************
    wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
    wheelPanel.setSize(600,580);
    wheelPanel.setBackground(Color.yellow);
    btPanel = new JPanel(); //create a panel for the buttons
    btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
    btPanel.setBackground(Color.blue);
    btPanel.setMaximumSize(new Dimension(30,580));
    btPanel.setMinimumSize(new Dimension(30,580));
    btPlay = new JButton("Play");
    btStop = new JButton("Stop");
    //txtTest = new JTextArea(5,5); //temp
    btPanel.add(btPlay);
    btPanel.add(btStop);
    // btPanel.add(txtTest); //temp
    c = getContentPane();
    layout = new BoxLayout(c,layout.X_AXIS);
    c.setLayout(layout);
    c.add(wheelPanel); //add panel and animate canvas to the applet
    c.add(btPanel);
    wheel = getImage(getDocumentBase(),"rotary2.gif");
    getParameters();
    for(int k = 0; k <TOTAL_SECTORS; k++)
    polySectors[k] = new Polygon();
    for(int n= 0; n<4; n++)
    polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
    btPlay.addActionListener(this);
    btStop.addActionListener(this);
    wheelPanel.addMouseListener(this);
    startAnimation();
    public void mouseClicked(MouseEvent e)
    if (rotating == false) //user can only hightlight a sector when wheel is not rotating
    for(int h= 0; h<TOTAL_SECTORS; h++)
    if(polySectors[h].contains(e.getX(),e.getY()))
    currentSector = h;
    wheelPanel.repaint();
    email();
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void email()
    try
    URL rotaryMail = new URL("mailto:[email protected]");
    getAppletContext().showDocument(rotaryMail);
    catch(MalformedURLException mue)
    System.out.println("bad url!");
    public void getParameters()
    StringTokenizer stSector;
    String parCoords;
    for(int i = 0; i <TOTAL_SECTORS; i++)
    {               //put member names in applet parameter list into an array
    members[i] = getParameter("member"+i);
    //separate coordinate string and store coordinates in 2 arrays
    parCoords=getParameter("sector"+i);
    stSector = new StringTokenizer(parCoords, ",");
    for(int j = 0; j<4; j++)
    coordsX[i][j] = Integer.parseInt(stSector.nextToken());
    coordsY[i][j] = Integer.parseInt(stSector.nextToken());
    public void actionPerformed(ActionEvent e)
    wheelPanel.repaint(); //repaint when timer event occurs
    if (e.getActionCommand()=="Stop")
    stopAnimation();
    else if(e.getActionCommand()=="Play")
    startAnimation();
    public void startAnimation()
    if(timer == null)
    timer = new Timer(delay,this);
    timer.start();
    else if(!timer.isRunning())
    timer.restart();
    Thanks so much for your help!

  • EvaluatingTteststand 4.2.1: Null pointer access violation (error 17502) when attempting to use a mixed-mode std::map / boost shared_ptr class contained in a DLL through an interface from a different DLL

    Hi there.
    I have been working on a test system which will potentially have TestStand at its core, and downloaded/installed the 4.2.1 evaluation. Current details from the information dialog are:
    TestStand Engine version 4.2.1 (4.2.1.83)
    Sequence Editor Verison 4.2.1.83
    The system will drive mobile radio devices using RS232 serial interfaces, usnig a variety of serial protocols (Hayes, and a couple of proprietary binary protocols for other work).
    We already have in existence a soak tester, written in VS2005 with MFC unmanaged DLLs and also managed DLLs, which are mixed up together to provide different aspects of the functionality required for the binary protocols.
    I have created:
    1. a "master wrapper" DLL for the constellation of other DLLs - this offers up a simple C-API interface which I hope TestStand will use. It's called "SerialSessionMgr.dll""
    2. a mixed managed / unmanaged "IJW" (it just works) DLL which wraps up the binary logging protocol control interfaces, which are entirely in managed C++/CLI: the "master wrapper" DLL calls into this through an unmanaged interface to create instances of the CLI-compiled class which interfaces to the underlying managed DLLs imlpementing the logging protocol. This is called "WinTseInterface.dll".
    Before I started evaluating TestStand, I knocked up a test harness using CPPUnit / MFC, with which I was able to test SerialSessionMgr.dll and its' use of WinTseInterface.dll and verify they worked. The harness loads the DLL dynamically at run-time using AfxLoadLibrary() to try to emulate the way TestStand uses it.
    When we open a
    TSE session:
    The SerialSessionManager makes a call to the
    WinTseInterface.dll to "create" a logging instance. The instance is
    created in a std::map which is held by the CWinApp derived class, this map
    contains boost::shared_ptr of the class which works with a managed class. So we
    have a call trace: Client
    app->SerialSessionManager{TseStartSession()}->WinTseInterface{WINTSE_GetWinTseBridge()} - WINTSE_GetWinTseBridge()
    just creates a new instance of the unmanaged class which interfaces through to
    the managed CLI/C++ class beneath, and returns the address to the
    SerialSessionManager, which stores it.
    The SerialSessioManager actually initialises the WinTseBridge using a method of a C++ pure virtual interface class to the class in the std::map in the WinTseInterface DLL
    implements. The initialise call passes miscellaneous details and actually calls
    "gcnew" to create the managed class which interfaces to the
    underlying managed DLLs which implement the logging protocol.
    My logs of the DLL loading as seen in VS2005 debug output are attached this message as PDFs
    While trying to fix this, I have tried:
    Enhancing the WinTseInterface DLL so it manually loads all the other assemblies in the logging system, including the managed portion of WinTseInterface itself (no effect)
    All the different options for the way the C DLL adapter loads and unloads the DLL in the DLL adapter steptype in TestStand
    I've even tried calling directly into the WinTseInterface DLL before trying any SerialSessionManager DLL calls to try to load the WinTseInterface DLL completely beforehand
    and I cannot stop this exception.
    It seems like the object is created in the WinTseInterface DLL OK (I have debugged the creation step which runs for WINTSE_GetWinTseBridge() and the object is created OK) when the SerialSessionManager makes the call, but when it calls the first managed function, which creates the managed object, the DLL is reloaded as managed - I suspect this causes the object to be destroyed or overwritten, and thus the call to initialise bombs with null pointer violation.
    Have I done something obviously wrong, and what other approaches can I take? 
    Does TestStand 4.2.1 have issues with driving DLLs which use managed/unmanaged DLLs beneath them?
    My nuclear option is to throw the WinTseInterface DLL out completely and wrap up the managed C++ CLI code in a new interface, entirely managed, and use the TestStand ".Net" adaptor to drive that, creating my step library to run to that directly. This isn't ideal as I have some co-ordination of the protocols which is implemented in the SerialSessionMgr DLL.
    I hope someone can help. This one's low level, dirty and a stumper to me.
    Many thanks to the NI community. This is my first posting!
    Solved!
    Go to Solution.
    Attachments:
    CPPUnit Test Harness DLL load debug output.pdf ‏18 KB
    TestStand DLL load & crash debug output.pdf ‏43 KB

    Hi there Ray.
    First - many thanks for engaging with this thorny problem. Love the avatar BTW.
    I've been using the C/C++ DLL adapter: the original premise of the Serial Session Manager DLL was to provide a simple C type functional interface, using simple data types, so that TestStand would be able to drive the underlying functionality easily through a single DLL.
    Seeing as you've been kind enough to respond, I should explain the makeup of the DLLs a little more, I think.
    The SerialSessionManager (SSMgr) DLL uses C++ and MFC internally. This is the DLL which TestStand calls into directly through the C/C++ adapter. This DLL does have one odd feature though - because the it uses the Windows Multimedia Timer (implemented in WinMM.dll) I had to artificially create a scenario where it would load the .Net mscoree DLL _before_ it loads WinMM.dll - (http://connect.microsoft.com/VisualStudio/feedback/details/329819/freelibrary-in-the-winmm-dlls-modu...), basically WinMM.dll's init code gets rather upset when .Net DLLs load, which causes the entire executable to be unloaded with subsequent crashes.
    To work around this crash, the SSMgr has a single, completely empty, file which is compiled for CLR, effectively forcing a dependency into the DLL on the .Net subsystems and turning the DLL into a "IJW" binary. The resulting DLL doesn't actually have any executable managed .Net assemblies, but I'm guessing that it does contain enough .Net related stubs and information that when the DLL is loaded, mscoree.dll loads before WinMM.dll - and this means the system doesn't crash.
    Now, on to the WinTseInterface DLL. My initial description of this little software system was done in something of a hurry.
    This DLL is the C++/CLI "IJW" DLL which actually contains managed and unmanaged code. Underneath the WinTseInterface DLL is another system of (this time exclusively C++/CLI) DLL assemblies which implement the TSE protocol interpretation system.
    When the SSMgr DLL needs to start a TSE protocol session, it calls a C-API function in the WinTseInterface which creates a new CWinTseBridge class. Here's the steps in a little more detail:
    SSMgr DLL calls WINTSE_GetWinTseBridge(), passing in the name of the device which needs it (this is used to put the new WinTseBridge into a std::map in the WinTseInterface DLL) - this call runs just fine, and returns the address of the CWinTseBridge C++ object. This is stored in the SSMgr, because the CWinTseBridge class implements a pure virtual interface which is used by the SSMgr as a way of accessing the CWinTseBridge methods. 
    We now use the address from (1) to make a call to CWinTseBridge::Initialise(), passing some basic configuration details.
    I've run VS2005 debug on the Sequence Editor when running the test, and done F11 step-throughs of the code loading each parameter in the Initialise() call onto the stack, and what appears to happen is that when the call is made, the whole lot steps off into oblivion (a reference to 0x00000000 is made, I think).
    Do you think it's worth trying to get this approach to work? It would be useful to retain the control surface in the top of the SSMgr as there is co-ordination of the protocols within the logic of that component. If I move the Wintse control out into a separate managed DLL I may not have that co-ordination (this might be overcome with some design, as I've confirmed that it is possible to "reach into" the WinTseInterface DLL with TestStand and create and use managed objects from assemblies contained within).
    Are there any known issues with this version of TestStand using C/C++ CLI IJW DLLs? I haven't found much out there on the web.
    Attachments:
    Tse_Test.seq ‏7 KB

  • Null Pointer exception returned when object is not null!

    I've isolated the problem and cut down the code to the minimum. Why do I get a null pointer exception when the start method is called, when the object objJTextField is not null at this point???? I'm really stuck here, HELP!
    (two small java files, save as BasePage.java and ExtendedPage.java and then run ExtendedPage)
    first file
    ~~~~~~~
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public abstract class BasePage extends JFrame implements ActionListener
    private JPanel objJPanel = null;
    public BasePage()
    setSize(300,200);
    Container objContentPane = getContentPane();
    objJPanel = new JPanel();
    createObjects();
    createPage();
    // Add panels to content pane
    objContentPane.add(objJPanel);
    public void addComponentToPage(JComponent objJComponent)
    objJPanel.add(objJComponent);
    public void addButtonToPage(JButton objJButton)
    objJButton.addActionListener(this);
    objJPanel.add(objJButton);
    public void actionPerformed(ActionEvent objActionEvent)
    System.out.println("Action performed");
    userDefinedButtonClicked(objActionEvent.getActionCommand());
    // overide
    public abstract void createObjects();
    public abstract void createPage();
    public abstract void userDefinedButtonClicked(String sActionCommand);
    file 2
    ~~~~
    import javax.swing.*;
    public class ExtendedPage extends BasePage
    private JTextField objJTextField = null;
    private JButton objJButtonBrowse = null;
    public ExtendedPage()
    super();
    public void createObjects()
    objJTextField = new JTextField(20);
    objJButtonBrowse = new JButton("Start");
    objJButtonBrowse.setActionCommand("START");
    public void createPage()
    addComponentToPage(objJTextField);
    addButtonToPage(objJButtonBrowse);
    public void userDefinedButtonClicked(String sActionCommand)
    if ((sActionCommand != null) && (sActionCommand.equals("START")) )
    start();
    private void start()
    objJTextField.setText("Doesn't work");
    public static void main(String[] args)
    ExtendedPage objEP = new ExtendedPage();
    objEP.show();

    Hello ppaulf,
    Your problem is in your ExtendedPage.java file. You can fix this by changing the line
    private JTextField objJTextField = null;to:
    private JTextField objJTextField = new JTextField();This creates a proper instance.
    Good luck,
    Ming
    Developer Technical Support
    http://www.sun.com/developers/support

  • When passing Node to parse() method get NULL pointer exception.

    All,
    I trying to pass a Node to parse method to get the NodeType object back and getting
    null pointer exception.
    Example
    xml
    <root>
    <Test>
    <someData>ABC</someData>
    </Test>
    </root>
    if pass the Test node to get Test object back I am getting null pointer exception.
    Thanks for all ur help
    Shoeb

    file 2
    ~~~~
    import javax.swing.*;
    public class ExtendedPage extends BasePage
    private JTextField objJTextField = null;
    private JButton objJButtonBrowse = null;
    Change the line in bold to
    private JTextField objJTextField;
    And everything works.

  • Null pointer exception in embedded component

    Hi all,
    I am trying to build a custom component that serves as a container. Unfortunately I consistently hit a null pointer exception in javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion when my custom component contains a JPanel.
    You'll find below the smallest code that reproduces the problem and the exception that comes with it.
    In my testing I noticed few things:
    - If the contained object is simple (a JButton for example), there is no problem.
    - When I turn off double buffering, there is no problem.
    - I figured out that I need to set the contained component size and its internal components to have it display properly.
    I can't figure out what would make this work.
    I'm using JDK 6.
    package test;
    import java.awt.*;
    import javax.swing.*;
    public class Test {
         public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
         private static void createAndShowGUI() {
              // internal panel
              JPanel lPanel = new JPanel();
              JButton lButton = new JButton("Button 1");
              lButton.setSize(lButton.getPreferredSize());
              lPanel.add(lButton);
              IntComponent b = new IntComponent(lPanel);
              JFrame lFrame = new JFrame("internal panel test");
              //RepaintManager.currentManager(null).setDoubleBufferingEnabled(false);
              lFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              lFrame.getContentPane().add(b);
              lFrame.pack();
              lFrame.setVisible(true);
    class IntComponent extends JComponent {
         private JComponent mInternalComponent;
         public IntComponent(JComponent iComponent) {
              mInternalComponent=iComponent;
              mInternalComponent.setSize(mInternalComponent.getPreferredSize());
         public Dimension getMaximumSize() {
              return getPreferredSize();
         public Dimension getMinimumSize() {
              return getPreferredSize();
         public Dimension getPreferredSize() {
              return mInternalComponent.getPreferredSize();
         protected void paintComponent(Graphics g) {
              mInternalComponent.paint(g);
    }Exception:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(BufferStrategyPaintManager.java:406)
         at javax.swing.BufferStrategyPaintManager.endPaint(BufferStrategyPaintManager.java:370)
         at javax.swing.RepaintManager.endPaint(RepaintManager.java:1192)
         at javax.swing.JComponent.paint(JComponent.java:1016)
         at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
         at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
         at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
         at java.awt.Container.paint(Container.java:1797)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:734)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:679)
         at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:659)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

    import java.awt.*;
    import javax.swing.*;
    class Test {
      public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
      private static void createAndShowGUI() {
        JPanel lPanel = new JPanel();
        JButton lButton = new JButton("Button 1");
        lPanel.add(lButton);
        IntComponent b = new IntComponent(lPanel);
        JFrame lFrame = new JFrame("internal panel test");
        lFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        lFrame.getContentPane().add(b);
        lFrame.pack();
        lFrame.setVisible(true);
    class IntComponent extends JComponent {
      private JComponent mInternalComponent;
      public IntComponent(JComponent iComponent) {
        mInternalComponent=iComponent;
        setLayout(new FlowLayout());//<--added
        add(mInternalComponent);//<--added
      public Dimension getMaximumSize() {
        return getPreferredSize();
      public Dimension getMinimumSize() {
        return getPreferredSize();
      public Dimension getPreferredSize() {
        return mInternalComponent.getPreferredSize();
      protected void paintComponent(Graphics g) {
        //mInternalComponent.paint(g);//<--error from this
        super.paintComponent(g);//<---added
    }

  • Help with Null Pointer Exception

    Hi, I am working on a simple menu program. It compiles and works correctly except for one item. I am having a problem with Greying out a menu item...... Specifically, When I press the EDIT / OPTIONS / READONLY is supposed to Greyout the Save and SaveAs options. But, when I do that it displays a Null Pointer Exception error message in the command window.
    Your advice would be much appreciated!
    Now for the code
    /  FileName Menutest.java
    //  Sample Menu
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MenuTest extends JFrame {
       private Action saveAction;
         private Action saveAsAction;
         private JCheckBoxMenuItem readOnlyItem;
       // set up GUI
       public MenuTest()
          super( "Menu Test" );
    //*   file menu and menu items
          // set up File menu and its menu items
          JMenu fileMenu = new JMenu( "File" );
          // set up New menu item
          JMenuItem newItem = fileMenu.add(new TestAction( "New" ));
          // set up Open menu item
          JMenuItem openItem = fileMenu.add(new TestAction( "Open" ));
              //  add seperator bar
              fileMenu.addSeparator();
          // set up Save menu item
          JMenuItem saveItem = fileMenu.add(new TestAction( "Save" ));
          // set up Save As menu item
          JMenuItem saveAsItem = fileMenu.add(new TestAction( "Save As" ));
              //  add seperator bar
              fileMenu.addSeparator();
              // set up Exit menu item
          JMenuItem exitItem = new JMenuItem( "Exit" );
          exitItem.setMnemonic( 'x' );
          fileMenu.add( exitItem );
          exitItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // terminate application when user clicks exitItem
                public void actionPerformed( ActionEvent event )
                   System.exit( 0 );
             }  // end anonymous inner class
          ); // end call to addActionListener
    //*   Edit menu and menu items
              // set up the Edit menu
              JMenu editMenu = new JMenu( "Edit" );
              //JMenuItem editMenu = new JMenu( "Edit" );
          // set up Cut menu item
          Action cutAction = new TestAction("Cut");
          cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
          // set up Copy menu item
          Action copyAction = new TestAction("Copy");
          copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif") );
          // set up Paste menu item
          Action pasteAction = new TestAction("Paste");
          pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif") );
              editMenu.add(cutAction);
              editMenu.add(copyAction);
              editMenu.add(pasteAction);
          //  add seperator bar
              editMenu.addSeparator();
              // set up Options menu, and it submenus and items
              JMenu optionsMenu = new JMenu("Options");
              readOnlyItem = new JCheckBoxMenuItem("Read-only");
              readOnlyItem.addActionListener(
                   new ActionListener()
                   {  //  anonymous inner class
                        public void actionPerformed( ActionEvent event)
                          saveAction.setEnabled(!readOnlyItem.isSelected());
                          saveAsAction.setEnabled(!readOnlyItem.isSelected());
                }  // end anonymous inner class
              ); // end call to addActionListener
              optionsMenu.add(readOnlyItem);
              // add seperator bar
              optionsMenu.addSeparator();
              //  Work on Radio Buttons
              ButtonGroup textGroup = new ButtonGroup();
              JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
              insertItem.setSelected(true);
              JRadioButtonMenuItem overTypeItem = new JRadioButtonMenuItem("Overtype");
              textGroup.add(insertItem);
              textGroup.add(overTypeItem);
              optionsMenu.add(insertItem);
              optionsMenu.add(overTypeItem);
              editMenu.add(optionsMenu);
    //*   Help menu and menu items
              // set up the Help menu
              JMenu helpMenu = new JMenu( "Help" );
              helpMenu.setMnemonic( 'H' );
          // set up index menu item
          JMenuItem indexItem = helpMenu.add(new TestAction( "Index" ));
          indexItem.setMnemonic( 'I' );
          helpMenu.add( indexItem );
              // set up About menu item
          JMenuItem aboutItem = new JMenuItem( "About" );
          aboutItem.setMnemonic( 'A' );
          helpMenu.add( aboutItem );
          aboutItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // display message dialog when user selects Open
                public void actionPerformed( ActionEvent event )
                   JOptionPane.showMessageDialog( MenuTest.this,
                      "This is MenuTest.java \nVersion 1.0 \nMarch 15, 2004",
                      "About", JOptionPane.PLAIN_MESSAGE );
             }  // end anonymous inner class
          ); // end call to addActionListener
          // create menu bar and attach it to MenuTest window
          JMenuBar bar = new JMenuBar();
          setJMenuBar( bar );
          bar.add( fileMenu );
              bar.add( editMenu );
              bar.add( helpMenu );
          setSize( 500, 200 );
          setVisible( true );
       } // end constructor
       public static void main( String args[] )
          MenuTest application = new MenuTest();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
       // inner class to handle action events from menu items
       private class ItemHandler implements ActionListener {
          // process color and font selections
          public void actionPerformed( ActionEvent event )
           repaint();
          } // end method actionPerformed
       } // end class ItemHandler
       //  Prints to action name to System.out
      class TestAction extends AbstractAction
              public TestAction(String name) { super(name); }
          public void actionPerformed( ActionEvent event )
             System.out.println(getValue(Action.NAME) + " selected." );
       } // end class TestAction
    } // end class MenuTest

    alan, I've been trying to figure out a solution.
    You can initialize it like this
    private Action saveAction= new Action();
         private Action saveAsAction=new Action();
    THE ABOVE WILL NOT WORK.
    because Action is an interface. An interface does not have constructors. However, interface references are used for polymorphic purposes.
    Anyway, all you have to do is find some class that implemets Action interface.... I cant seem to find one. Or maybe this is not how its supposed to be done?
    Hopefully, someone can shed some light on this issue.
    FYI,
    http://java.sun.com/products/jfc/swingdoc-api-1.1/javax/swing/Action.html

  • Main method not found and how to put event handlers in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Bet you're trying "java JournalFrame" when you need to "java JournalApp".
    Couple pointers toward good code.
    1) Use white space (extra returns) to separate your code into logical "paragraphs" of thought.
    2) Add comments. At a minimum a comment at the beginning should name the file, state its purpose, identify the programmer and date written. A comment at the end should state that you've reached the end. In the middle, any non-obvious code should be commented and closing braces or parens should have a comment stating what they close (if there is non-trivial separation from where they open).
    Here's a sample:
    // JournalFrame.java - this does ???
    // saisoft, 4/18/03
    // constructor
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        radioPanel.setLayout(gridLayout1);
        statusPanel.setLayout(flowLayout1);
        textAreaPanel.setLayout(gridLayout2);
        buttonPanel.setLayout(gridLayout3);
        personalButton.setSelected(true);
        personalButton.setText("Personal");
        personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
        businessButton.setText("Business");
        status.setText("");
        entryArea.setText("");
        entryArea.setColumns(10);
        entryArea.setLineWrap(true);
        entryArea.setRows(30);
        entryArea.setWrapStyleWord(true);
    } // end constructor
    // end JournalFrame.java3) What would you expect to gain from that inner class? It might be more cool, but would it be more clear? I give the latter (clarity) a lot of importance.

  • Main method not found and how to implement events in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Here is the complete code (with crappy indentation) :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
        private JLabel dateLabel = new JLabel("Date: ");
        private JTextField dateField = new JTextField(20);
        private JPanel datePanel = new JPanel(new FlowLayout());
        BorderLayout borderLayout1 = new BorderLayout();
        JPanel radioPanel = new JPanel();
        JPanel statusPanel = new JPanel();
        JPanel textAreaPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        GridLayout gridLayout1 = new GridLayout();
        FlowLayout flowLayout1 = new FlowLayout();
        GridLayout gridLayout2 = new GridLayout();
        GridLayout gridLayout3 = new GridLayout();
        JRadioButton personalButton = new JRadioButton();
        JRadioButton businessButton = new JRadioButton();
        JLabel status = new JLabel();
        JTextArea entryArea = new JTextArea();
        JButton clearButton = new JButton();
        JButton saveButton = new JButton();
        ButtonGroup entryType = new ButtonGroup();
        public JournalFrame(){
            try {
                jbInit();
            catch(Exception e){
                e.printStackTrace();
        private void initWidgets(){
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(borderLayout1);
            radioPanel.setLayout(gridLayout1);
            statusPanel.setLayout(flowLayout1);
            textAreaPanel.setLayout(gridLayout2);
            buttonPanel.setLayout(gridLayout3);
            personalButton.setSelected(true);
            personalButton.setText("Personal");
            personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
            businessButton.setText("Business");
            status.setText("");
            entryArea.setText("");
            entryArea.setColumns(10);
            entryArea.setLineWrap(true);
            entryArea.setRows(30);
            entryArea.setWrapStyleWord(true);
            clearButton.setPreferredSize(new Dimension(125, 25));
            clearButton.setText("Clear Journal Entry");
            clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
            saveButton.setText("Save Journal Entry");
            saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
            this.setTitle("Journal");
            gridLayout3.setColumns(1);
            gridLayout3.setRows(0);
            this.getContentPane().add(datePanel, BorderLayout.NORTH);
            this.getContentPane().add(radioPanel, BorderLayout.WEST);
            this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
            this.getContentPane().add(buttonPanel, BorderLayout.EAST);
            entryType.add(personalButton);
            entryType.add(businessButton);
            datePanel.add(dateLabel);
            datePanel.add(dateField);
            radioPanel.add(personalButton, null);
            radioPanel.add(businessButton, null);
            textAreaPanel.add(entryArea, null);
            buttonPanel.add(clearButton, null);
            buttonPanel.add(saveButton, null);
            this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
            statusPanel.add(status, null);
            this.pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void saveEntry() throws IOException{
            if( personalButton.isSelected()){
                String file = "Personal.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                entryArea.getText();
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
            else if (businessButton.isSelected()){
                String file = "Business.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
        void clearButton_actionPerformed(ActionEvent e) {
            dateField.setText("");
            entryArea.setText("");
            status.setText("");
        void saveButton_actionPerformed(ActionEvent e){
            try{saveEntry();}catch(IOException error){
                status.setText("Error: Could not save journal entry");
        void personalButton_actionPerformed(ActionEvent e) {
        class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.personalButton_actionPerformed(e);
    }BadLands

  • Null Pointer Exception, don't know why...

    Hi everyone,
    This may well be really simple, but it's driving me crazy...
    The program puts lots of panels into other panels and when a combo box is set to a certain value the number of panels alters.
    Here is some of the code:
                 *  Fourth User
                // First user main panel
                pn_u4 = new JPanel();
                pn_u4.setLayout( new BorderLayout(5,5) );
                pn_u4.setPreferredSize( new Dimension(800,80) );
                pn_u4.setBackground(Color.WHITE);
                // First user top panel that goes into the
                // main panel North
                pn_u4T = new JPanel();
                pn_u4T.setLayout( new BorderLayout(5,5) );
                pn_u4T.setPreferredSize( new Dimension(800,40) );
                pn_u4T.setBackground(Color.WHITE);
                // First user bottom panel that goes into the
                // main panel South
                pn_u4B = new JPanel();
                pn_u4B.setLayout( new BorderLayout(5,5) );
                pn_u4B.setPreferredSize( new Dimension(800,40) );
                pn_u4B.setBackground(Color.WHITE);
                // First user top panel left, goes into the
                // top panel West
                pn_u4TL = new JPanel();
                pn_u4TL.setLayout( new FlowLayout() );
                pn_u4TL.setPreferredSize( new Dimension(400,40) );
                pn_u4TL.setBackground(Color.WHITE);
                    lbl_u4Name = new JLabel("Name");
                    lbl_u4Name.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u4Name = new JTextField(28);
                pn_u4TL.add(lbl_u4Name);
                pn_u4TL.add(tf_u4Name);
                // First user top panel right, goes into the
                // top panel East
                pn_u4TR = new JPanel();
                pn_u4TR.setLayout( new FlowLayout() );
                pn_u4TR.setPreferredSize( new Dimension(400,40) );
                pn_u4TR.setBackground(Color.WHITE);
                    lbl_u4ID = new JLabel("GNAS ID");
                    lbl_u4ID.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u4ID = new JTextField(28);
                pn_u4TR.add(lbl_u4ID);
                pn_u4TR.add(tf_u4ID);
                pn_u4T.add(pn_u4TL, BorderLayout.WEST);
                pn_u4T.add(pn_u4TR, BorderLayout.EAST);
                // First user bottom panel left, goes into the
                // bottom panel West
                pn_u4BL = new JPanel();
                pn_u4BL.setLayout( new FlowLayout() );
                pn_u4BL.setPreferredSize( new Dimension(400,40) );
                pn_u4BL.setBackground(Color.WHITE);
                    lbl_u4Round = new JLabel("Round Name");
                    lbl_u4Round.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u4Round = new JTextField(24);
                pn_u4BL.add(lbl_u4Round);
                pn_u4BL.add(tf_u4Round);
                // First user bottom panel right, goes into the
                // bottom panel East
                pn_u4BR = new JPanel();
                pn_u4BR.setLayout( new FlowLayout() );
                pn_u4BR.setPreferredSize( new Dimension(400,40) );
                pn_u4BR.setBackground(Color.WHITE);
                    lbl_u4Bow = new JLabel("Bow Type                                                ");
                    lbl_u4Bow.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    cb_u4Bow = new JComboBox();
                    cb_u4Bow.addActionListener(this);
                        cb_u4Bow.addItem("    Compound    ");
                        cb_u4Bow.addItem("    Long Bow    ");
                        cb_u4Bow.addItem("    Recurve     ");
                pn_u4BR.add(lbl_u4Bow);
                pn_u4BR.add(cb_u4Bow);
                pn_u4B.add(pn_u4BL, BorderLayout.WEST);
                pn_u4B.add(pn_u4BR, BorderLayout.EAST);
                pn_u4.add(pn_u4T, BorderLayout.NORTH);
                pn_u4.add(pn_u4B, BorderLayout.SOUTH);
                //pn_u3u4.add(pn_u4, BorderLayout.NORTH);
                pn_2.add(pn_u1u2, BorderLayout.NORTH);
                pn_2.add(pn_u3u4, BorderLayout.SOUTH);           
                //initialWindow.add(pn_topAll);//BorderLayout.NORTH);
                initialWindow.add(pn_topAll, BorderLayout.NORTH);
                initialWindow.add(pn_2, BorderLayout.CENTER);
               pack();    There are a total of four users, but too much code to paste here,
    Now there's the event listener:
    public void actionPerformed(ActionEvent e)
                if (e.getSource() == cb_noOfPeople)
                    if(cb_noOfPeople.getSelectedItem() == "  1  ")
    ***                if(pn_u3u4.getComponentCount() > 0)
                            pn_u3u4.remove(pn_u3);
                            pn_u3u4.remove(pn_u4);
                        else
                        if(pn_u1u2.getComponentCount() == 2)
                            pn_u1u2.remove(pn_u2);
                        else
                        initialWindow.repaint();
                        initialWindow.validate();
                    else if(cb_noOfPeople.getSelectedItem() == "  2  ")
                        if(pn_u3u4.getComponentCount() > 0)
                            pn_u3u4.remove(pn_u3);
                            pn_u3u4.remove(pn_u4);
                        else
                        pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                        initialWindow.repaint();
                        initialWindow.validate();
                    else if(cb_noOfPeople.getSelectedItem() == "  3  ")
                        if(pn_u3u4.getComponentCount() == 2)
                            pn_u3u4.remove(pn_u4);
                        else
                        pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                        pn_u3u4.add(pn_u3, BorderLayout.NORTH);
                        initialWindow.repaint();
                        initialWindow.validate();
                    else if(cb_noOfPeople.getSelectedItem() == "  4  ")
                        pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                        pn_u3u4.add(pn_u3, BorderLayout.NORTH);
                        pn_u3u4.add(pn_u4, BorderLayout.SOUTH);
                        initialWindow.repaint();
                        initialWindow.validate();
                    else
                }Everything works until it reaches:
    ***     if(pn_u3u4.getComponentCount() > 0)
                            pn_u3u4.remove(pn_u3);
                            pn_u3u4.remove(pn_u4);
                        else
                        if(pn_u1u2.getComponentCount() == 2)
                            pn_u1u2.remove(pn_u2);
                        else
                        }(please ignore the three stars, just to indicate where that code was)
    Wihout the above bit of code inplace everything works fine, I can change the value of the combo box and things are removed and added, but when I add the above if statements to the value "1" area, i get the null pointer, which doesn't make sence to me.
    Exception in thread "main" java.lang.NullPointerException
    at InitialScreen.actionPerformed(InitialScreen.java:601)
    Thanks for help in advance (I can provide all 600 lines of code if needed)
    Victoria

    Your actionListener for your cb_noOfPeople is being fired before the rest of the components are being initialized. I just moved the addition of the actionListener to right before the pack() statement to ensure that all of your variables get initialized and it works like a charm. Here you go:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.util.*;
    *  @author Victoria
    *  @version v1.01
    *  Start date 29th Nov 06
    class InitialScreen extends JFrame implements ActionListener
         Container initialWindow;
         JLabel titleBar, lbl_noOfUsers, lbl_u1Name, lbl_u1ID, lbl_u1Bow, lbl_u1Round, lbl_u2Name, lbl_u2ID, lbl_u2Bow, lbl_u2Round, lbl_u3Name, lbl_u3ID, lbl_u3Round, lbl_u3Bow, lbl_u4Name, lbl_u4ID, lbl_u4Round, lbl_u4Bow;
            JComboBox cb_noOfPeople, cb_u1Bow, cb_u2Bow, cb_u3Bow, cb_u4Bow;
            JTextField tf_u1Name, tf_u1ID, tf_u1Round, tf_u2Name, tf_u2ID, tf_u2Round, tf_u3Name, tf_u3ID, tf_u3Round, tf_u4Name, tf_u4ID, tf_u4Round, tf_compDate, tf_compTime, tf_compID;
            JPanel pn_1, pn_2, pn_3, pn_u1u2, pn_u3u4, pn_top, pn_top2, pn_top3, pn_topAll, pn_u1, pn_u1T, pn_u1TL, pn_u1TR, pn_u1B, pn_u1BL, pn_u1BR, pn_u2, pn_u2T, pn_u2TL, pn_u2TR, pn_u2B, pn_u2BL, pn_u2BR, pn_u3, pn_u3T, pn_u3TL, pn_u3TR, pn_u3B, pn_u3BL, pn_u3BR, pn_u4, pn_u4T, pn_u4TL, pn_u4TR, pn_u4B, pn_u4BL, pn_u4BR, pn_shootInfo, pn_button;
         JButton but_go, but_reset, but_exit;
             *  Constructor for the initial screen
         public InitialScreen()
                //  Create a window pane called initial Window
                //  and set it to a preferred size of 800x600
                initialWindow = getContentPane();
                initialWindow.setLayout( new BorderLayout(5,5) );
                setPreferredSize( new Dimension(800,600) );
                initialWindow.setBackground(Color.WHITE);
                //pn_1 = new JPanel();
                //pn_1.setLayout( new BorderLayout(5,5) );
                //pn_1.setPreferredSize( new Dimension(800,40) );
                //pn_1.setBackground(Color.WHITE);
                pn_2 = new JPanel();
                pn_2.setLayout( new BorderLayout(5,5) );
                pn_2.setPreferredSize( new Dimension(800,40) );
                pn_2.setBackground(Color.WHITE);
                //pn_3 = new JPanel();
                //pn_3.setLayout( new BorderLayout(5,5) );
                //pn_3.setPreferredSize( new Dimension(800,40) );
                //pn_3.setBackground(Color.WHITE);
                // First top panel just houese the label that
                // says what the program is and fill in info
                pn_top = new JPanel();
                pn_top.setLayout( new BorderLayout(5,5) );
                pn_top.setPreferredSize( new Dimension(800,40) );
                pn_top.setBackground(Color.WHITE);
                    titleBar = new JLabel("Archery Scoring Program - Please fill in the following information \n ", JLabel.CENTER);
                    titleBar.setFont( new Font("Times New Roman",Font.PLAIN,20) );
                //pn_top.add(titleBar, BorderLayout.NORTH);
                //pn_top.add(lbl_noOfUsers, BorderLayout.WEST);
                //pn_top.add(cb_noOfPeople, BorderLayout.EAST);
                pn_top.add(titleBar);
                // Second panel contains the how many people
                // ComboBox
                pn_top2 = new JPanel();
                pn_top2.setLayout(new FlowLayout());
                pn_top2.setPreferredSize( new Dimension(360,40) );
                pn_top2.setBackground(Color.WHITE);
                    lbl_noOfUsers = new JLabel("No of members shooting on this target");
                    lbl_noOfUsers.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    cb_noOfPeople = new JComboBox();
                    //cb_noOfPeople.addActionListener(this);
                        cb_noOfPeople.addItem("  1  ");
                        cb_noOfPeople.addItem("  2  ");
                        cb_noOfPeople.addItem("  3  ");
                        cb_noOfPeople.addItem("  4  ");
                pn_top2.add(lbl_noOfUsers);
                pn_top2.add(cb_noOfPeople);
                // Third panel contains nothing but alligns
                // the second panel correctly
                pn_top3 = new JPanel();
                pn_top3.setLayout( new FlowLayout() );
                pn_top3.setPreferredSize( new Dimension(440,40) );
                pn_top3.setBackground(Color.WHITE);
                // Last top panel contains all the previous
                // top panels and adds the other top
                // panels to it
                pn_topAll = new JPanel();
                pn_topAll.setLayout( new BorderLayout(5,5) );
                //pn_topAll.setPreferredSize( new Dimension(450,100) );
                pn_topAll.setBackground(Color.WHITE);
                pn_topAll.add(pn_top, BorderLayout.NORTH);
                pn_topAll.add(pn_top2, BorderLayout.WEST);
                pn_topAll.add(pn_top3, BorderLayout.EAST);
                pn_u1u2 = new JPanel();
                pn_u1u2.setLayout( new BorderLayout(5,5) );
                pn_u1u2.setPreferredSize( new Dimension(800,160) );
                pn_u1u2.setBackground(Color.WHITE);
                 *  First User
                 *  As long as the if statement is correctly working
                 *  The first user panel will be added upon load
                 *  User two, three and four will be added depending on
                 *  the value of the combobox which asks how many
                 *  users are shooting on the target
                // First user main panel
                pn_u1 = new JPanel();
                pn_u1.setLayout( new BorderLayout(5,5) );
                pn_u1.setPreferredSize( new Dimension(800,80) );
                pn_u1.setBackground(Color.WHITE);
                // First user top panel that goes into the
                // main panel North
                pn_u1T = new JPanel();
                pn_u1T.setLayout( new BorderLayout(5,5) );
                pn_u1T.setPreferredSize( new Dimension(800,40) );
                pn_u1T.setBackground(Color.WHITE);
                // First user bottom panel that goes into the
                // main panel South
                pn_u1B = new JPanel();
                pn_u1B.setLayout( new BorderLayout(5,5) );
                pn_u1B.setPreferredSize( new Dimension(800,40) );
                pn_u1B.setBackground(Color.WHITE);
                // First user top panel left, goes into the
                // top panel West
                pn_u1TL = new JPanel();
                pn_u1TL.setLayout( new FlowLayout() );
                pn_u1TL.setPreferredSize( new Dimension(400,40) );
                pn_u1TL.setBackground(Color.WHITE);
                    lbl_u1Name = new JLabel("Name");
                    lbl_u1Name.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u1Name = new JTextField(28);
                pn_u1TL.add(lbl_u1Name);
                pn_u1TL.add(tf_u1Name);
                // First user top panel right, goes into the
                // top panel East
                pn_u1TR = new JPanel();
                pn_u1TR.setLayout( new FlowLayout() );
                pn_u1TR.setPreferredSize( new Dimension(400,40) );
                pn_u1TR.setBackground(Color.WHITE);
                    lbl_u1ID = new JLabel("GNAS ID");
                    lbl_u1ID.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u1ID = new JTextField(28);
                pn_u1TR.add(lbl_u1ID);
                pn_u1TR.add(tf_u1ID);
                pn_u1T.add(pn_u1TL, BorderLayout.WEST);
                pn_u1T.add(pn_u1TR, BorderLayout.EAST);
                // First user bottom panel left, goes into the
                // bottom panel West
                pn_u1BL = new JPanel();
                pn_u1BL.setLayout( new FlowLayout() );
                pn_u1BL.setPreferredSize( new Dimension(400,40) );
                pn_u1BL.setBackground(Color.WHITE);
                    lbl_u1Round = new JLabel("Round Name");
                    lbl_u1Round.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u1Round = new JTextField(24);
                pn_u1BL.add(lbl_u1Round);
                pn_u1BL.add(tf_u1Round);
                // First user bottom panel right, goes into the
                // bottom panel East
                pn_u1BR = new JPanel();
                pn_u1BR.setLayout( new FlowLayout() );
                pn_u1BR.setPreferredSize( new Dimension(400,40) );
                pn_u1BR.setBackground(Color.WHITE);
                    lbl_u1Bow = new JLabel("Bow Type                                                ");
                    lbl_u1Bow.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    cb_u1Bow = new JComboBox();
                    cb_u1Bow.addActionListener(this);
                        cb_u1Bow.addItem("    Compound    ");
                        cb_u1Bow.addItem("    Long Bow    ");
                        cb_u1Bow.addItem("    Recurve     ");
                pn_u1BR.add(lbl_u1Bow);
                pn_u1BR.add(cb_u1Bow);
                pn_u1B.add(pn_u1BL, BorderLayout.WEST);
                pn_u1B.add(pn_u1BR, BorderLayout.EAST);
                pn_u1.add(pn_u1T, BorderLayout.NORTH);
                pn_u1.add(pn_u1B, BorderLayout.SOUTH);
                pn_u1u2.add(pn_u1, BorderLayout.NORTH);
                 *  Second User
                // First user main panel
                pn_u2 = new JPanel();
                pn_u2.setLayout( new BorderLayout(5,5) );
                pn_u2.setPreferredSize( new Dimension(800,80) );
                pn_u2.setBackground(Color.WHITE);
                // First user top panel that goes into the
                // main panel North
                pn_u2T = new JPanel();
                pn_u2T.setLayout( new BorderLayout(5,5) );
                pn_u2T.setPreferredSize( new Dimension(800,40) );
                pn_u2T.setBackground(Color.WHITE);
                // First user bottom panel that goes into the
                // main panel South
                pn_u2B = new JPanel();
                pn_u2B.setLayout( new BorderLayout(5,5) );
                pn_u2B.setPreferredSize( new Dimension(800,40) );
                pn_u2B.setBackground(Color.WHITE);
                // First user top panel left, goes into the
                // top panel West
                pn_u2TL = new JPanel();
                pn_u2TL.setLayout( new FlowLayout() );
                pn_u2TL.setPreferredSize( new Dimension(400,40) );
                pn_u2TL.setBackground(Color.WHITE);
                    lbl_u2Name = new JLabel("Name");
                    lbl_u2Name.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u2Name = new JTextField(28);
                pn_u2TL.add(lbl_u2Name);
                pn_u2TL.add(tf_u2Name);
                // First user top panel right, goes into the
                // top panel East
                pn_u2TR = new JPanel();
                pn_u2TR.setLayout( new FlowLayout() );
                pn_u2TR.setPreferredSize( new Dimension(400,40) );
                pn_u2TR.setBackground(Color.WHITE);
                    lbl_u2ID = new JLabel("GNAS ID");
                    lbl_u2ID.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u2ID = new JTextField(28);
                pn_u2TR.add(lbl_u2ID);
                pn_u2TR.add(tf_u2ID);
                pn_u2T.add(pn_u2TL, BorderLayout.WEST);
                pn_u2T.add(pn_u2TR, BorderLayout.EAST);
                // First user bottom panel left, goes into the
                // bottom panel West
                pn_u2BL = new JPanel();
                pn_u2BL.setLayout( new FlowLayout() );
                pn_u2BL.setPreferredSize( new Dimension(400,40) );
                pn_u2BL.setBackground(Color.WHITE);
                    lbl_u2Round = new JLabel("Round Name");
                    lbl_u2Round.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u2Round = new JTextField(24);
                pn_u2BL.add(lbl_u2Round);
                pn_u2BL.add(tf_u2Round);
                // First user bottom panel right, goes into the
                // bottom panel East
                pn_u2BR = new JPanel();
                pn_u2BR.setLayout( new FlowLayout() );
                pn_u2BR.setPreferredSize( new Dimension(400,40) );
                pn_u2BR.setBackground(Color.WHITE);
                    lbl_u2Bow = new JLabel("Bow Type                                                ");
                    lbl_u2Bow.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    cb_u2Bow = new JComboBox();
                    cb_u2Bow.addActionListener(this);
                        cb_u2Bow.addItem("    Compound    ");
                        cb_u2Bow.addItem("    Long Bow    ");
                        cb_u2Bow.addItem("    Recurve     ");
                pn_u2BR.add(lbl_u2Bow);
                pn_u2BR.add(cb_u2Bow);
                pn_u2B.add(pn_u2BL, BorderLayout.WEST);
                pn_u2B.add(pn_u2BR, BorderLayout.EAST);
                pn_u2.add(pn_u2T, BorderLayout.NORTH);
                pn_u2.add(pn_u2B, BorderLayout.SOUTH);
                //pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                pn_u3u4 = new JPanel();
                pn_u3u4.setLayout( new BorderLayout(5,5) );
                pn_u3u4.setPreferredSize( new Dimension(800,160) );
                pn_u3u4.setBackground(Color.WHITE);
                 *  Third User
                // First user main panel
                pn_u3 = new JPanel();
                pn_u3.setLayout( new BorderLayout(5,5) );
                pn_u3.setPreferredSize( new Dimension(800,80) );
                pn_u3.setBackground(Color.WHITE);
                // First user top panel that goes into the
                // main panel North
                pn_u3T = new JPanel();
                pn_u3T.setLayout( new BorderLayout(5,5) );
                pn_u3T.setPreferredSize( new Dimension(800,40) );
                pn_u3T.setBackground(Color.WHITE);
                // First user bottom panel that goes into the
                // main panel South
                pn_u3B = new JPanel();
                pn_u3B.setLayout( new BorderLayout(5,5) );
                pn_u3B.setPreferredSize( new Dimension(800,40) );
                pn_u3B.setBackground(Color.WHITE);
                // First user top panel left, goes into the
                // top panel West
                pn_u3TL = new JPanel();
                pn_u3TL.setLayout( new FlowLayout() );
                pn_u3TL.setPreferredSize( new Dimension(400,40) );
                pn_u3TL.setBackground(Color.WHITE);
                    lbl_u3Name = new JLabel("Name");
                    lbl_u3Name.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u3Name = new JTextField(28);
                pn_u3TL.add(lbl_u3Name);
                pn_u3TL.add(tf_u3Name);
                // First user top panel right, goes into the
                // top panel East
                pn_u3TR = new JPanel();
                pn_u3TR.setLayout( new FlowLayout() );
                pn_u3TR.setPreferredSize( new Dimension(400,40) );
                pn_u3TR.setBackground(Color.WHITE);
                    lbl_u3ID = new JLabel("GNAS ID");
                    lbl_u3ID.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u3ID = new JTextField(28);
                pn_u3TR.add(lbl_u3ID);
                pn_u3TR.add(tf_u3ID);
                pn_u3T.add(pn_u3TL, BorderLayout.WEST);
                pn_u3T.add(pn_u3TR, BorderLayout.EAST);
                // First user bottom panel left, goes into the
                // bottom panel West
                pn_u3BL = new JPanel();
                pn_u3BL.setLayout( new FlowLayout() );
                pn_u3BL.setPreferredSize( new Dimension(400,40) );
                pn_u3BL.setBackground(Color.WHITE);
                    lbl_u3Round = new JLabel("Round Name");
                    lbl_u3Round.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u3Round = new JTextField(24);
                pn_u3BL.add(lbl_u3Round);
                pn_u3BL.add(tf_u3Round);
                // First user bottom panel right, goes into the
                // bottom panel East
                pn_u3BR = new JPanel();
                pn_u3BR.setLayout( new FlowLayout() );
                pn_u3BR.setPreferredSize( new Dimension(400,40) );
                pn_u3BR.setBackground(Color.WHITE);
                    lbl_u3Bow = new JLabel("Bow Type                                                ");
                    lbl_u3Bow.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    cb_u3Bow = new JComboBox();
                    cb_u3Bow.addActionListener(this);
                        cb_u3Bow.addItem("    Compound    ");
                        cb_u3Bow.addItem("    Long Bow    ");
                        cb_u3Bow.addItem("    Recurve     ");
                pn_u3BR.add(lbl_u3Bow);
                pn_u3BR.add(cb_u3Bow);
                pn_u3B.add(pn_u3BL, BorderLayout.WEST);
                pn_u3B.add(pn_u3BR, BorderLayout.EAST);
                pn_u3.add(pn_u3T, BorderLayout.NORTH);
                pn_u3.add(pn_u3B, BorderLayout.SOUTH);
                //pn_u3u4.add(pn_u3, BorderLayout.NORTH);
                 *  Fourth User
                // First user main panel
                pn_u4 = new JPanel();
                pn_u4.setLayout( new BorderLayout(5,5) );
                pn_u4.setPreferredSize( new Dimension(800,80) );
                pn_u4.setBackground(Color.WHITE);
                // First user top panel that goes into the
                // main panel North
                pn_u4T = new JPanel();
                pn_u4T.setLayout( new BorderLayout(5,5) );
                pn_u4T.setPreferredSize( new Dimension(800,40) );
                pn_u4T.setBackground(Color.WHITE);
                // First user bottom panel that goes into the
                // main panel South
                pn_u4B = new JPanel();
                pn_u4B.setLayout( new BorderLayout(5,5) );
                pn_u4B.setPreferredSize( new Dimension(800,40) );
                pn_u4B.setBackground(Color.WHITE);
                // First user top panel left, goes into the
                // top panel West
                pn_u4TL = new JPanel();
                pn_u4TL.setLayout( new FlowLayout() );
                pn_u4TL.setPreferredSize( new Dimension(400,40) );
                pn_u4TL.setBackground(Color.WHITE);
                    lbl_u4Name = new JLabel("Name");
                    lbl_u4Name.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u4Name = new JTextField(28);
                pn_u4TL.add(lbl_u4Name);
                pn_u4TL.add(tf_u4Name);
                // First user top panel right, goes into the
                // top panel East
                pn_u4TR = new JPanel();
                pn_u4TR.setLayout( new FlowLayout() );
                pn_u4TR.setPreferredSize( new Dimension(400,40) );
                pn_u4TR.setBackground(Color.WHITE);
                    lbl_u4ID = new JLabel("GNAS ID");
                    lbl_u4ID.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u4ID = new JTextField(28);
                pn_u4TR.add(lbl_u4ID);
                pn_u4TR.add(tf_u4ID);
                pn_u4T.add(pn_u4TL, BorderLayout.WEST);
                pn_u4T.add(pn_u4TR, BorderLayout.EAST);
                // First user bottom panel left, goes into the
                // bottom panel West
                pn_u4BL = new JPanel();
                pn_u4BL.setLayout( new FlowLayout() );
                pn_u4BL.setPreferredSize( new Dimension(400,40) );
                pn_u4BL.setBackground(Color.WHITE);
                    lbl_u4Round = new JLabel("Round Name");
                    lbl_u4Round.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    tf_u4Round = new JTextField(24);
                pn_u4BL.add(lbl_u4Round);
                pn_u4BL.add(tf_u4Round);
                // First user bottom panel right, goes into the
                // bottom panel East
                pn_u4BR = new JPanel();
                pn_u4BR.setLayout( new FlowLayout() );
                pn_u4BR.setPreferredSize( new Dimension(400,40) );
                pn_u4BR.setBackground(Color.WHITE);
                    lbl_u4Bow = new JLabel("Bow Type                                                ");
                    lbl_u4Bow.setFont( new Font("Times New Roman",Font.PLAIN,17) );
                    cb_u4Bow = new JComboBox();
                    cb_u4Bow.addActionListener(this);
                        cb_u4Bow.addItem("    Compound    ");
                        cb_u4Bow.addItem("    Long Bow    ");
                        cb_u4Bow.addItem("    Recurve     ");
                pn_u4BR.add(lbl_u4Bow);
                pn_u4BR.add(cb_u4Bow);
                pn_u4B.add(pn_u4BL, BorderLayout.WEST);
                pn_u4B.add(pn_u4BR, BorderLayout.EAST);
                pn_u4.add(pn_u4T, BorderLayout.NORTH);
                pn_u4.add(pn_u4B, BorderLayout.SOUTH);
                //pn_u3u4.add(pn_u4, BorderLayout.NORTH);
                pn_2.add(pn_u1u2, BorderLayout.NORTH);
                pn_2.add(pn_u3u4, BorderLayout.SOUTH);           
                //initialWindow.add(pn_topAll);//BorderLayout.NORTH);
                initialWindow.add(pn_topAll, BorderLayout.NORTH);
                initialWindow.add(pn_2, BorderLayout.CENTER);
                // Boolean tests, to see if the combobox
                // has been set, and if so how many panels to
                // add to the initialWindow panel
                if(u1 == true)
                    //initialWindow.add(pn_u1);
                if(u2 == true)
                    pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                    //initialWindow.add(pn_u2);
                    initialWindow.repaint();
                    initialWindow.validate();
                if(u3 == true)
                    pn_u3u4.add(pn_u3, BorderLayout.NORTH);
                    //initialWindow.add(pn_u3);
                if(u4 == true)
                    pn_u3u4.add(pn_u4, BorderLayout.SOUTH);
                    //initialWindow.add(pn_u4);
             cb_noOfPeople.addActionListener(this);
                pack();   
          *  Event listener for the initial screen
             *  Items it's listening to are:
             *  Combo Box - cb_noOfPoeple
          *  quit button
          *  login button
          *  reset button
         public void actionPerformed(ActionEvent e)
                if (e.getSource() == cb_noOfPeople)
                    if(cb_noOfPeople.getSelectedItem() == "  1  ")
                        if(pn_u3u4.getComponentCount() > 0)
                            pn_u3u4.remove(pn_u3);
                            pn_u3u4.remove(pn_u4);
                        else
                        if(pn_u1u2.getComponentCount() == 2)
                            pn_u1u2.remove(pn_u2);
                        else
                        initialWindow.repaint();
                        initialWindow.validate();
                    else if(cb_noOfPeople.getSelectedItem() == "  2  ")
                        if(pn_u3u4.getComponentCount() > 0)
                            pn_u3u4.remove(pn_u3);
                            pn_u3u4.remove(pn_u4);
                        else
                        pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                        initialWindow.repaint();
                        initialWindow.validate();
                    else if(cb_noOfPeople.getSelectedItem() == "  3  ")
                        if(pn_u3u4.getComponentCount() == 2)
                            pn_u3u4.remove(pn_u4);
                        else
                        pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                        pn_u3u4.add(pn_u3, BorderLayout.NORTH);
                        initialWindow.repaint();
                        initialWindow.validate();
                    else if(cb_noOfPeople.getSelectedItem() == "  4  ")
                        pn_u1u2.add(pn_u2, BorderLayout.SOUTH);
                        pn_u3u4.add(pn_u3, BorderLayout.NORTH);
                        pn_u3u4.add(pn_u4, BorderLayout.SOUTH);
                        initialWindow.repaint();
                        initialWindow.validate();
                    else
         public static void main(String[] argv) { new InitialScreen().setVisible(true); }
    }

  • Reference to enclosing instance in inner class constructor

    Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) here
    super();
    class Global {
    public Global(int x) {

    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
    inner class always has an implicit reference to an
    instance of the enclosing class.Try this:
    class Outer {
    int m;
    class Inner extends Global {
    public Inner(int x) {
    super(x);
    protected void init(int x) {
    xxx = Outer.this.m + x; // Null pointer exception!!!
    class Global {
    int xxx;
    public Global(int x) {
    init(x);
    protected void init(int x) {
    xxx = x;

  • Accessing Enclosing Class Members From Inner Class Subclass

    I have the following scenario that I cannot get to work. Notice the comments in B.doWork() for the problem code. In B.doWork(), how do I access m_strA?
    * A.java
    * Created on July 5, 2002, 2:20 PM
    package Projects.InnerTrouble.Files;
    public class A {
         public abstract class InnerA {
              public abstract void doWork ();
         public String m_strA;
         /** Creates new A */
         public A ()
                   new InnerA() {
                             public void doWork ()
                                       System.out.println("A$InnerA$1's doWork() called!");
                                       m_strA = "Annonymous subclass of InnerA's doWork did this";
                        }.doWork();
         * @param args the command line arguments
         public static void main (String args[])
                   A oTemp = new A();
                   System.out.println(oTemp.m_strA);
                   B.getB(oTemp).doWork();
                   System.out.println(oTemp.m_strA);
    class B extends A.InnerA {
         public B (A a)
                   a.super();
         public void doWork ()
                   System.out.println("B's doWork() called!");
                   // How do I access m_strA within B's doWork() method?  The following is what I would expect to be the answer, but it does not compile
                   // A.this.m_strA = "B's doWork did this";
         private static A.InnerA sm_oInnerA;
         public static A.InnerA getB (A a)
                   if (sm_oInnerA == null)
                        sm_oInnerA = new B(a);
                   return (sm_oInnerA);

    The whole point is that B is not an inner class of A
    so it does not have access to A's member variables.
    Eventhough B extends an inner class of A, that does
    not make B an inner class of A. That is in the JLS,
    but not so elegantly as I have put it, hehe.
    If B were an innerclass of InnerA, then it would
    qualify to access A's member variables.OK, I think that you are finally getting through to my thick skull on this one. Let me restate and get your check-off on my understanding of the situation.
    The only classes with access to A's this reference are A and inner classes of A that are found within the definition of A. So, despite the fact that A and B are in the same package (and B should have access to A's non-private members because B and A are in the same package), and despite the fact that we would normally state that B "is a" InnerA (which is an inner class of A and would have access to a reference to the A.this reference), B is not allowed access to A.this (because B "is not really a" InnerA in the same way that the anonymous implementation of InnerA "is a" InnerA). However, nothing would prevent me from giving B access to a reference of the enclosing A as long as it was done via a method of InnerA, and as long as the implementation of that method is contained in A's implementation.
    Does this "access" rule realy make sense? Are you aware of the justification for this rule? Or is the justification stated in the JLS? I would think that the compiler ought to be able to figure this kind of thing out and allow it. It seems to me the fact that I defined B in the way that I did, and the fact that B "is a" InnerA, implies that I desired a fairly tight relationship to A. In fact, I desired the exact relationship that exists for the anonymous implementation of InnerA.
    The following is a modified version of my original example that runs as I originally wanted it to, but works around the access rules discussed on this forum thread:
    * A.java
    * Created on July 5, 2002, 2:20 PM
    package Projects.InnerTrouble.Files;
    public class A {
         public abstract class InnerA {
              public abstract void doWork ();
              /** added to allow implementors of InnerA that are not enclosed in A's class definition to have access to the enclosing class */
              public A myEnclosingInstance ()
                        return (A.this);
         public String m_strA;
         /** Creates new A */
         public A ()
                   new InnerA() {
                             public void doWork ()
                                       System.out.println("A$InnerA$1's doWork() called!");
                                       m_strA = "Annonymous subclass of InnerA's doWork did this";
                        }.doWork();
         * @param args the command line arguments
         public static void main (String args[])
                   A oTemp = new A();
                   System.out.println(oTemp.m_strA);
                   B.getB(oTemp).doWork();
                   System.out.println(oTemp.m_strA);
    class B extends A.InnerA {
         public B (A a)
                   a.super();
         public void doWork ()
                   System.out.println("B's doWork() called!");
                   // The following is what I would expect to be the answer, but it does not compile
                   // A.this.m_strA = "B's doWork did this";
                   // added myEnclosingInstance() to get functionality desired above
                   myEnclosingInstance().m_strA = "B's doWork did this";
         private static A.InnerA sm_oInnerA;
         public static A.InnerA getB (A a)
                   if (sm_oInnerA == null)
                        sm_oInnerA = new B(a);
                   return (sm_oInnerA);
    }

  • ActionListener and Inner Class Issue

    When I add ".addActionListener()" to buttons and create an inner class to listen/handle the action, my main class does not display the GUI. If I remove the ".addActionListener()" from the buttons and the inner class, the GUI displays. Below is my code. Anyone know what is wrong with my code?
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(new ButtonHandler());
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class package projects.web;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileBrowser{
         JFileChooser fileChooser = new JFileChooser();
         public FileBrowser(){
              int fileChooserOption = fileChooser.showOpenDialog(null);
         } // end constructor
    } // end class fileBrowser

    Encephalopathic wrote:
    Dan: When it doesn't display, what happens? Do you see any error messages? Also, please take a look at your other thread in this same forum as it has relevance to our conversations in the java-forums.org about whether to add GUIs to root containers or the other way around. /PeteI fiddled with the code some more and it seems that the problem is the inner code. When I changed from the inner class to the main class implementing ActionListener and had the main class implement the actionPerformed method, the GUI displayed and JFileChooser worked as well. I've add this version of the code at the bottom of this message.
    To answer your question: When it doesn't display, what happens? -- The web page loads and is blank. And there are no error messages.
    I took a look at the other thread is this forum (the one relates to our conversation in the other forum); the problem may be the way I've add the GUI. I'll try it the other way and see what happens.
    Thanks,
    Dan
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI implements ActionListener{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(this);
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class

  • Inner Classes doubts

    Hi All,
    I am trying to learn Inner classes in Java. I am referring to the book Core Java by Horstmann and Cornell.
    I know that there are various types of inner classes namely:
    - Nested Inner classes
    - Local Inner classes
    - Annonymous Inner classes
    - static inner classes
    First I am on with Nested Inner classes :
    Following is the code which I am executing :
    package com.example.innerclass;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    public class InnerClassTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TalkingClock clock = new TalkingClock(1000,true);
              clock.start();
    //          JOptionPane.showMessageDialog(null,"Quit Program");
    //          System.exit(0);
    class TalkingClock
         private int interval;
         private boolean beep;
         public TalkingClock(int interval, boolean beep){
              this.interval = interval;
              this.beep = beep;          
         public void start(){
              ActionListener listener = new TimePrinter();
              Timer t = new Timer(interval,listener);
              t.start();
         private class TimePrinter implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   Date now = new Date();
                   System.out.println("At the tone time is : "+now);
                   if(beep)
                        Toolkit.getDefaultToolkit().beep();
    }Following are my doubts :
    1. Why do we need to give the line
    JOptionPane.showMessageDialog(null,"Quit Program");
    System.exit(0);without this line the program doesn't show any output.
    2. I didn't understand this syntax.
    You can write inner object constructor more explicitly using the syntax. :
    outerObject.new InnerClass(construction parameters)
    For e.g.
    ActionListener listener = this.new TimePrinter();
    Here the outer class reference of the newly constructed TimePrinter object is set to this reference of the method that creates the inner class object. the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicilty naming it. For e.g if TimePrinter were a public inner class, you could construct a TimePrinter for any talking clock.
    TalkingClock jabberer = new TalkingClock(1000,true);
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    Please do help me understand this concept.
    Thanks
    Siddharth

    I have understood that this explanation :
    i) assuming that TimePrinter is an inner class of TalkingClock, that you'd need an instance of the later in order to create an instance of the former.Yes.
    Being a non-static inner class, it can not be instantiated out of context ... which context is the outer class.No. See my reply 11. The "context" is an instance of the outer class - it bears repeating.
    ii) jabberer is the outer instance that you are providing.Yes (more accurately it's a reference to an instance of the outer class, but that would be nit-picking).
    The left side is identifying the class, the right side is identifying the instanceNo.
    I'm not sure what you're calling left side and right side.
    If you're talking about both sides of the equals sign, then no, it's completely wrong.
    If you're talking about both sides of the "point" sign, then it's wrong too, just a bit less wrong.
    Let's revise this step by step (good thought process).
    1. in first line we are getting an outer class reference with this code
    TalkingClock jabberer = new TalkingClock(1000,true);
    this line is very natural and easily understood. Yes. The correct wording would be merely "we are getting a reference to an instance of the outer class". Sorry to insist densely.
    2. Now when we come to the second line, i.e. where we try to instantiate an inner class with this line of code
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    - I do understand the concept that we need an instance of outer class in order to create an instance of inner class as inner class is visible only to outer class.No. We need an instance of the outer class as the inner class is non-static, and by definition needs an instance of the outer class. That has nothing to do with visibility (public vs private vs...). Again, some words have special meanings in the Java world.
    - I also do understand that it cant be instantiated out of context. I see you like this expression, but it is too vague and misleads you. Please forget about it for a moment (no offense to otherwise helpful and knowledgeable abillconsl).
    - I also do understand that left side is identifying the class and right side is identifying the instance. ANDAgain I'm afraid of which "sides" you're talking about.
    - that in this line TalkingClock.TimePrinter listener = new TalkingClock().new TimePrinter();
    the outer class is anonymous (new TalkingClock()) as we don't require its name here Poor choice of words again. Anonymous classes do exist in Java, but are a totally different concept, that is not related to this line.
    - Also in this line TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    I understood the left side part i.e. TalkingClock.TimePrinter listener =
    We are attaching the outer class reference with the inner class that's absolutely understandable. Not at all!
    This just declares a variable listener, whose type is TalkingClock.TimePrinter (or more accurately com.example.innerclass.TalkingClock.TimePrinter).
    Then follows an assignment:
    WHAT I don't understand is the right hand side, i.e., the statement jabberer.new TimePrinter();
    1. I am unable to digest the fact that we can do something like anobject.new
    new is an operator that is used to instantiate an instance of an object. I am unable to digest that we can do x.new?See my previous reply. This is short-hand syntax Sun chose to pass a reference to an instance of the outer class (here, jabberer) to the constructor of the inner class. They could have chosen something else. Again, bear with it.
    I only know that we can do is new SomeClass(); AND NOT instance.new SomeClass();
    Now you know better:
    The second form is valid - only if SomeClass is a non-static inner class defined in a class of which instance is an instance.
    2. Is there something to this conceptually OR this is only a syntax and that I should learn it.
    I want to understand and grasp if there is some concept behind it rather than just learn and mug up. See my previous reply. Each instance of a non-static inner class stores a reference to an instance of the outer class. There must be a way (a syntax) to specify which instance (of the outer class) should be stored in the instance (of the inner class).
    This particular syntax is just a syntax, the "concept" is that the instance of the inner class stores a (unmodifiable) reference to the instance of the outer class that was specified when the instance of the inner class was created.
    I don't know if that deserves to be called a concept, but that's an interesting thing to keep in mind (there are some not-so-obvious implications in terms of, e.g. garbage collection).
    Best regards.
    J.

Maybe you are looking for