Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 628
  • Last Modified:

JComboBox - error

Hi,
I have a JTextPane in which I write text and change the font of that text using the JComboBox as detailed in the code below:

    fonts = new JComboBox(fontArray);
    fonts.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        String name = fonts.getSelectedItem().toString();
        new StyledEditorKit.FontFamilyAction("font-family-" + name, name).actionPerformed(ae);
        writingPane.requestFocus();
      }
    });

When I'm using JBuilder 1.2 this works just fine, but when I'm using j2sdk 1.4.1 I get the following error:

java.lang.NullPoinerException
    at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.grabContainer(BasicPopupMenuUI.java:344)
    at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.requestAddGrab(BasicPopupMenuUI.java:227)
    at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.stateChanged(BasicPopupMenuUI.java:273)
    at javax.swing.MenuSelectionManager.fireStateChanged(MenuSelectionManager.java:158)
    at javax.swing.MenuSelectionManager.setSelectedPath(MenuSelectionManager.java:86)
    at javax.swing.JPopupMenu.setVisible(JPopupMenu.java:741)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:912)
    at javax.swing.plaf.basic.BasicComboPopup.show.(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboPopup.togglePopup.(BasicComboPopup.java:982)
    at javax.swing.plaf.basic.BasicComboPopup$InvocationMouseHandler.mousePressed.(BasicComboPopup.java:632)

and so on...


Any offers regarding solution for this error will be welcome.
Thanks,
edgar
0
etgaroy
Asked:
etgaroy
  • 9
  • 8
  • 7
  • +1
1 Solution
 
Mayank SAssociate Director - Product EngineeringCommented:
Is BasicPopupMenuUI.java your source-code. If so, then please post lines 344, 277 and 273.

Mayank.
0
 
etgaroyAuthor Commented:
Hi,
BasicPopupMenuUI.java is not my source code.
I think it is a class related to JComboBox.
Thanks,
Edgar
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Whatever.... please post some of the lines. There is obviously an object which has not been initialized but is being referenced (I mean, it is null initially and is still being referenced somewhere).

Mayank.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
etgaroyAuthor Commented:
This is part of this class (it is much longer and not all related to the issue).
There are some other classes as well in the program which do not appear here:


package com.Gui15;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.StyledEditorKit;
import java.util.*;
import com.Gui15.DisplayInfo;

public class Gui15 extends JFrame {
  private Container container;
  // items hels by fileMenu for manipulating files
  private JMenuItem newItem, openItem, saveItem, saveAsItem,
    closeItem, clearItem, exitItem;
  private JMenuItem sizeItem[];
  // menu items held by the upper menu bar
  private JMenu fileMenu, textFormatMenu, fontMenu, sizeMenu, helpMenu;
  // menu items in the button groups of textFormatMenu
  private JRadioButtonMenuItem sizeItems[], fontItems[];
  // button groups holding various options of font size and type in textFormatMenu
  private ButtonGroup sizeGroup, fontGroup;
  // strings representing the various font names
  private String currentFont,
    fontNames[] = { "TimesRoman", "Courier", "Helvetica" };
  // integers representing the various font size possible
  private int currentSize, currentFontStyle = Font.PLAIN;
  // layout of frame
  private BorderLayout borderLayout;
  // panel holding the central part of the frame
  private DisplayPanel centerPanel;
  // buttons for changing the font style
  private JButton underline, bold, italic;
  // images holding the symbol of font style
  private ImageIcon underlineIcon, boldIcon, italicIcon;
  // the upper menu bar
  private JMenuBar upperBar;
  // object holding information of current display
  private DisplayInfo displayInfo;
  // file to be manipulated by user
  private File fileName;
  private String[] fontArray, size = {"8", "10", "12", "14", "16", "18", "24", "36"};
  private final JComboBox fonts;
  private JTextPane writingPane, displayPane;
  private Hashtable commands;
  private Action[] actions;

  /****************************************************************************/
  /*  class:          Gui15                                                   */
  /*  method:         Gui15                                                   */
  /*  parameters:     none                                                    */
  /*  return value:   none                                                    */
  /*  description:    a constructor of class Gui15. The constructor           */
  /*                  initializes most of the graphic objects contained by    */
  /*                  the menu bar and it initializes centerPanel as well.    */
  /****************************************************************************/
  public Gui15()
  {
    super ("Cirius Display");               // setting title to page
    container = getContentPane();
    borderLayout = new BorderLayout (5,5);  // set the layout gap size

    container.setLayout(borderLayout);
    upperBar = new JMenuBar();            //upperBar is the first menu bar
    upperBar.setPreferredSize(new Dimension (2, 25));
    setJMenuBar (upperBar);               //set the menubar for the JFrame

    /* create file menu and its inner options */
    fileMenu = new JMenu (" File ");
    fileMenu.setMnemonic( 'F' );
    fileMenu.setLocation(0,200);
    // initializes the handler of file
    FileHandler fileHandler = new FileHandler();

    /* create file inner option new */
    newItem = new JMenuItem (" New ");
    newItem.setMnemonic( 'N' );
    // handler that creates a new file
    newItem.addActionListener(fileHandler);
    fileMenu.add(newItem);

    /* create file inner option open */
    openItem = new JMenuItem (" Open ");
    openItem.setMnemonic( 'O' );
    //handler that opens a file
    openItem.addActionListener(fileHandler);
    fileMenu.add(openItem);

    /* create file inner option save */
    saveItem = new JMenuItem (" Save ");
    saveItem.setMnemonic( 'S' );
    //handler that saves a file
    saveItem.addActionListener(fileHandler);
    fileMenu.add(saveItem);

    /* create file inner option save as */
    saveAsItem = new JMenuItem (" Save as ");
    saveAsItem.setMnemonic( 'a' );
    //handler that saves as a file
    saveAsItem.addActionListener(fileHandler);
    fileMenu.add(saveAsItem);

    /* create file inner option close */
    closeItem = new JMenuItem (" Close ");
    closeItem.setMnemonic( 'C' );
    //handler that closes a file
    closeItem.addActionListener(fileHandler);
    fileMenu.add(closeItem);

    /* create file inner option clear */
    clearItem = new JMenuItem (" Clear ");
    clearItem.setMnemonic( 'l' );
    //handler that clears old data
    clearItem.addActionListener(fileHandler);
    fileMenu.add(clearItem);

    /* create file inner option exit */
    exitItem = new JMenuItem (" Exit ");
    exitItem.setMnemonic( 'E' );
    //handler that exits the program
    exitItem.addActionListener(fileHandler);
    fileMenu.add(exitItem);

    // create Text Format menu and its inner options
    textFormatMenu = new JMenu ("Text Format");
    textFormatMenu.setMnemonic( 't' );


    // create Font sub menu
    fontMenu = new JMenu( "Font" );
    fontMenu.setMnemonic( 'n' );
    fontItems = new JRadioButtonMenuItem[ fontNames.length ];
    fontGroup = new ButtonGroup();

    // add all font type options to the font menu and link the text handler
/*    for ( int i = 0; i < fontItems.length; i++ ) {
      fontItems[i] = new JRadioButtonMenuItem( fontNames[i] );
      fontMenu.add( fontItems[ i ] );
      fontGroup.add( fontItems[ i ] );
      fontItems[i].addActionListener(textHandler);
    }

    // fontName[0] is initial font type so it is set to be true
    currentFont = fontNames[0];
    fontItems[0].setSelected( true );
    textFormatMenu.add(fontMenu);
    fontMenu.addSeparator();
*/
    centerPanel = new DisplayPanel();
    centerPanel.setGui(this);
    writingPane = centerPanel.getWritingPane();

    fontArray = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    fonts = new JComboBox(fontArray);
    fonts.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        String name = fonts.getSelectedItem().toString();
        new StyledEditorKit.FontFamilyAction("font-family-" + name, name).actionPerformed(ae);
        writingPane.requestFocus();
      }
    });

    fontMenu.add(fonts);

    commands = new Hashtable();
    actions = writingPane.getActions();
    for (int i = 0; i < actions.length; i++) {
      Action a = actions[i];
      commands.put(a.getValue(Action.NAME), a);
    }
    final Action boldAction = (Action)commands.get ("font-bold");
    final Action italicAction = (Action)commands.get ("font-italic");
    final Action underlineAction = (Action)commands.get ("font-underline");
    Action sizeAction[] = new Action[size.length];
    for (int j = 0; j < size.length; j++)
    {
      String sizeName = "font-size-"+size[j];
      sizeAction[j] = (Action)commands.get (sizeName);
    }

    //create size sub menu
    sizeMenu = new JMenu ("Size");
    sizeMenu.setMnemonic( 'i' );
    sizeItem = new JMenuItem[size.length];
    for (int i = 0; i < size.length; i++)
    {
      sizeItem[i] = sizeMenu.add(sizeAction[i]);
      sizeItem[i].setText(size[i]);
    }


    // create help menu and its inner options
    helpMenu = new JMenu ("Help");
    // initialize class that handles help events
    HelpHandler helpHandler = new HelpHandler();
    helpMenu.setMnemonic( 'H' );
    JMenuItem helpItem = new JMenuItem ("Help Topics");
    helpItem.setMnemonic( 'p' );
    helpItem.addActionListener(helpHandler);
    JMenuItem aboutItem = new JMenuItem ("About...");
    aboutItem.setMnemonic( 'b' );
    aboutItem.addActionListener(helpHandler);

    helpMenu.add(helpItem);
    helpMenu.add(aboutItem);

    JToolBar toolBar = new JToolBar();
    // initialize icons and buttons that represent different font styles
    underlineIcon = new ImageIcon ("underline.gif");
    boldIcon = new ImageIcon ("bold.gif");
    italicIcon = new ImageIcon ("italic.gif");
    underline = new JButton ();
    bold = new JButton ();
    italic = new JButton ();
    underline = toolBar.add(underlineAction);
    underline.setIcon(underlineIcon);
    bold = toolBar.add(boldAction);
    bold.setIcon(boldIcon);
    italic = toolBar.add(italicAction);
    italic.setIcon(italicIcon);
    // link font style buttons to the text handler
    // initialize display panel object


    // add all menu objects to the the menu bar
    upperBar.add (fileMenu);
    upperBar.add (fontMenu);
    upperBar.add (sizeMenu);
    upperBar.add (helpMenu);

    // glue the buttons underline anf highlight to the right side of the bar
    upperBar.add (Box.createHorizontalGlue());
    upperBar.add (toolBar);
    // add the menu bar and center panel to the frame
    container.add (centerPanel, BorderLayout.CENTER);
    pack();
    setSize (1024,768);
    show();
  }



Thanks,
edgar
0
 
Mayank SAssociate Director - Product EngineeringCommented:
And at which line in this class is it giving the NullPointerException (it must be specifying the line number either in this class or some other).

Mayank.
0
 
glottisCommented:
whn exactly does the exception occur ?
when you click the combobox?
when you make the selection?
when the combobox pops up?
when ?
0
 
etgaroyAuthor Commented:
Hi Mayank,
The error I get is as I described it. I do not get a reference to some location in my code (not even when I've used printStackTrac()).
How can I find the line where the error occurs?
Thanks,
edgar
0
 
etgaroyAuthor Commented:
Hi glottis,
The exception occurs when I select one of the options in the JComboBox. The combobox disappears and does not perform its task.
Thanks,
Edgar
0
 
glottisCommented:
try this for debugging:

fonts = new JComboBox(fontArray);
fonts.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent ae) {
  System.out.println("Line 0");
  String name = (fonts.getSelectedItem()).toString();
  System.out.println("Line 1");
  (new StyledEditorKit.FontFamilyAction("font-family-" + name, name)).actionPerformed(ae);
  System.out.println("Line 2");
  writingPane.requestFocus();
  System.out.println("Line 3");
 }
});

then in your output see which lines its printing.
if it prints:
Line 1
Line 2
then exception, then it means that in between Line 2 and Line 3 there is a error

ps. this was just an xample
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Just try System.out.println ( e ) ; instead of System.out.println ( e.printStackTrace () ) ;.

Mayank.
0
 
glottisCommented:
try this for debugging:

fonts = new JComboBox(fontArray);
fonts.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent ae) {
  System.out.println("Line 0");
  String name = (fonts.getSelectedItem()).toString();
  System.out.println("Line 1");
  (new StyledEditorKit.FontFamilyAction("font-family-" + name, name)).actionPerformed(ae);
  System.out.println("Line 2");
  writingPane.requestFocus();
  System.out.println("Line 3");
 }
});

then in your output see which lines its printing.
if it prints:
Line 1
Line 2
then exception, then it means that in between Line 2 and Line 3 there is a error

ps. this was just an xample
0
 
glottisCommented:
opps, sorry for double post
0
 
OviCommented:
Why are you putting a JComboBox in a Application menu? You can create dinamically a cascading type of menu....
0
 
OviCommented:
If you are following the stack trace, you will see that the method grabContainer(...) try to obtain a awtTreeLock on a null component, which should be the parent of your combobox. The parent is null because the add method of the menu does not set'it.
0
 
etgaroyAuthor Commented:
Hi Ovi,
Then How can I set the parent of my ComboBox properly?

Thanks
0
 
glottisCommented:
wooo...

i didnt look this thing before.
you are adding fonts to fontMenu.

you cannot add a JComboBox to a JMenu.
you have to add JComboBox to a container.
0
 
etgaroyAuthor Commented:
Hi glottis,
I've tried your suggestion but it did not work.
It did not print any of the lines.

Hi mayankeagle,
Ive tried to print e as you suggested but got nothing.

Any other offers?
Thanks,
edgar
0
 
OviCommented:
You can add, since get's visible. The problem is that will be not proper initialized. I have looked for a solution but I'm afraid there is no one under current circumstances. My sugestion is to use cascading menus.
0
 
OviCommented:
Those line will be printed only after the combobox will fire action events to listeeners. This will happend NEVER sinceyou cannot even open the combobox for selection.
0
 
etgaroyAuthor Commented:
What are cascading menus? How can I use them? and Why do they solve my problem?

Thanks
0
 
glottisCommented:
etgaroy u have to add the combobox to a container, then only you will be able to select the selections.

0
 
OviCommented:
Replace the part where you add the combobox with this:

          JMenu fonts = new JMenu("Fonts");
          for (int i = 0; i < fontArray.length; i++) {
               JMenuItem item = new JMenuItem(fontArray[i]);
               final int idx = i;
               item.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                         String name = fontArray[idx];
                         new StyledEditorKit.FontFamilyAction("font-family-" + name, name).actionPerformed(ae);
                         writingPane.requestFocus();
                    }
               });
               fonts.add(item);
          }
     fontMenu.add(fonts);
0
 
OviCommented:
adding the combo to a container will have the same result (just tested).
0
 
glottisCommented:
Ovi really ? hmm ok.

wow that would bring one big Menu :p
0
 
OviCommented:
Yes, indeed. Depending on the fonts installed on the host system, the menu would be acceptable as height or will get out of the screen. Normally when you implement editors (I believe we speak here about a editor application), the font chooser and eventualy the font size chooser components, should be used in a toolbar. To use'it as a menu entry, will be fesable only when the menu is a custom one, similar with scrolling menus of windows. This means will display a limited amount of entries and one for expanding the menu. Should be a nice menu implementation something like:

 -------
| Font1 |
| Font2 |
| Font3 |
| Font4 |
|  \/   |
 -------

 -------
|   /\   |
| Font15 |
| Font16 |
| Font17 |
| Font18 |
| Font19 |
| Font20 |
 -------
0
 
etgaroyAuthor Commented:
Thanks Ovi,
Its working
0
 
OviCommented:
Yes, indeed. Depending on the fonts installed on the host system, the menu would be acceptable as height or will get out of the screen. Normally when you implement editors (I believe we speak here about a editor application), the font chooser and eventualy the font size chooser components, should be used in a toolbar. To use'it as a menu entry, will be fesable only when the menu is a custom one, similar with scrolling menus of windows. This means will display a limited amount of entries and one for expanding the menu. Should be a nice menu implementation something like:

 -------
| Font1 |
| Font2 |
| Font3 |
| Font4 |
|  \/   |
 -------

 -------
|   /\   |
| Font15 |
| Font16 |
| Font17 |
| Font18 |
| Font19 |
| Font20 |
 -------
0
 
OviCommented:
me too
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 9
  • 8
  • 7
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now