?
Solved

JComboBox - error

Posted on 2003-03-20
28
Medium Priority
?
617 Views
Last Modified: 2010-08-05
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
Comment
Question by:etgaroy
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 8
  • 7
  • +1
28 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 8172619
Is BasicPopupMenuUI.java your source-code. If so, then please post lines 344, 277 and 273.

Mayank.
0
 

Author Comment

by:etgaroy
ID: 8172637
Hi,
BasicPopupMenuUI.java is not my source code.
I think it is a class related to JComboBox.
Thanks,
Edgar
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8172708
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
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 

Author Comment

by:etgaroy
ID: 8172749
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 8172814
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
 
LVL 2

Expert Comment

by:glottis
ID: 8173203
whn exactly does the exception occur ?
when you click the combobox?
when you make the selection?
when the combobox pops up?
when ?
0
 

Author Comment

by:etgaroy
ID: 8173215
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
 

Author Comment

by:etgaroy
ID: 8173227
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
 
LVL 2

Expert Comment

by:glottis
ID: 8173232
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 8173244
Just try System.out.println ( e ) ; instead of System.out.println ( e.printStackTrace () ) ;.

Mayank.
0
 
LVL 2

Expert Comment

by:glottis
ID: 8173262
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
 
LVL 2

Expert Comment

by:glottis
ID: 8173265
opps, sorry for double post
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8173286
Why are you putting a JComboBox in a Application menu? You can create dinamically a cascading type of menu....
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8173418
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
 

Author Comment

by:etgaroy
ID: 8173436
Hi Ovi,
Then How can I set the parent of my ComboBox properly?

Thanks
0
 
LVL 2

Expert Comment

by:glottis
ID: 8173489
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
 

Author Comment

by:etgaroy
ID: 8173510
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
 
LVL 9

Expert Comment

by:Ovi
ID: 8173511
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
 
LVL 9

Expert Comment

by:Ovi
ID: 8173519
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
 

Author Comment

by:etgaroy
ID: 8173535
What are cascading menus? How can I use them? and Why do they solve my problem?

Thanks
0
 
LVL 2

Expert Comment

by:glottis
ID: 8173536
etgaroy u have to add the combobox to a container, then only you will be able to select the selections.

0
 
LVL 9

Accepted Solution

by:
Ovi earned 80 total points
ID: 8173561
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
 
LVL 9

Expert Comment

by:Ovi
ID: 8173580
adding the combo to a container will have the same result (just tested).
0
 
LVL 2

Expert Comment

by:glottis
ID: 8173688
Ovi really ? hmm ok.

wow that would bring one big Menu :p
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8173749
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
 

Author Comment

by:etgaroy
ID: 8173764
Thanks Ovi,
Its working
0
 
LVL 9

Expert Comment

by:Ovi
ID: 8173769
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
 
LVL 9

Expert Comment

by:Ovi
ID: 8173772
me too
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month12 days, 10 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question