I am trying to cast combo box to string but I have problems with it. I get NullPointerException?

fontStyle = (String)combo.getSelectedItem();
         size = (String)comboSize.getSelectedItem();
      
      
         if (fontStyle.equals("Regular") && size.equals("10"))	
         {
            Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
            text.setFont(font);
         }

that's a bit little information to go on, but, do you actually have an Item selected?
can you post the entire code, and the complete exception error message

import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.io.*;

    /*Original code form:
     *  4002-218 Day18
     *  Purpose: demonstrate the use of the file chooser to read a file 
     *
     */
   public class FileViewer extends JFrame
   {
      private JTextArea text;
      private JFileChooser fileChoose;
      private JPanel panel2;
      private JMenuItem fileOpenItem, fileSaveItem, fileNewItem, fileHelpItem, fileAboutItem, fileSaveAsItem, exitItem, editWordCount;
      private String fontChoser[] = {"Regular","Italic","Bold","Bold Italic"};
      private String fontSize[] = {"10","12","15"};
      private JButton setFontBtn;
        private JTextField fileNameText;
        private JComboBox comboSize, combo;



   /** Class constructor
     * @param titleText Title bar text
     */
      public FileViewer( String titleText )
      {
      //create text area with scroll bar
         text = new JTextArea();
         add( new JScrollPane( text ), BorderLayout.CENTER );
         text.setEditable( true );

         /** Present a dialog box to have the user select
      * the file for browsing
      * @return panel2 JPanel panel 
      */

        //panel 2 for file name displey

         panel2 = new JPanel();
         panel2.setLayout(new FlowLayout());

         JLabel filename = new JLabel("File Name:");
         panel2.add(filename);

         fileNameText = new JTextField(15);
         fileNameText.setEditable(false);
         panel2.add(fileNameText);

        //Panel 3 for buttons and combo boxes


         JPanel panel3 = new JPanel();
         panel3.setLayout(new GridLayout(3,0));


         combo = new JComboBox(fontChoser);

         JPanel panelcombo = new JPanel(new FlowLayout());          
         panelcombo.add(combo); // add combo box to panel



         comboSize = new JComboBox(fontSize);
         JPanel panelcombo2 = new JPanel(new FlowLayout());
         panelcombo2.add(comboSize);



         setFontBtn = new JButton("Set Font");
         setFontBtn.setMnemonic('T');

         JPanel panelcombo3 = new JPanel(new FlowLayout());
         panelcombo3.add(setFontBtn);

         panel3.add(panelcombo);
         panel3.add(panelcombo2);
         panel3.add(panelcombo3);

        // add panels to the frame
         add(panel2, BorderLayout.SOUTH);
         add(panel3, BorderLayout.EAST);



      /** Build the menu bar, menus, and menu items for
      * the file browser
      */

      //create menu bar and add menus
         JMenuBar menuBar = new JMenuBar();
         JMenu fileMenu = new JMenu( "File" );
         menuBar.add( fileMenu );

         JMenu editMenu = new JMenu( "Edit" );
         menuBar.add( editMenu );

         JMenu helpMenu = new JMenu( "Help" );
         menuBar.add( helpMenu );

      //create menu items for
         fileNewItem      = new JMenuItem("New");
         exitItem           = new JMenuItem( "Exit" );
         fileOpenItem       = new JMenuItem( "Open..." );
         fileSaveItem       = new JMenuItem("Save");


         fileAboutItem      = new JMenuItem("About");
         fileSaveAsItem     = new JMenuItem("Save As..");

         editWordCount = new JMenuItem( "Word Count");

         fileNewItem.setMnemonic(KeyEvent.VK_N);
         helpMenu.setMnemonic(KeyEvent.VK_H);
         fileAboutItem.setMnemonic(KeyEvent.VK_A);
         fileSaveAsItem.setMnemonic(KeyEvent.VK_S);
         fileMenu.add( fileNewItem );
         fileMenu.add( fileOpenItem );
         fileMenu.add( fileSaveItem );
         fileMenu.add( fileSaveAsItem );
         fileMenu.add( exitItem );

         editMenu.add(editWordCount);

         helpMenu.add( fileAboutItem );

        //set menu bar with menu items
         setJMenuBar( menuBar );

         FileListener listen = new FileListener(fileOpenItem, fileSaveItem, fileNewItem, fileAboutItem, fileSaveAsItem, exitItem, editWordCount, setFontBtn, text,fileNameText);

         HelpListener help = new HelpListener(fileAboutItem);


         setFontBtn.addActionListener(listen);


         fileAboutItem.addActionListener(help);

         fileOpenItem.addActionListener(listen);
         fileNewItem.addActionListener(listen);
         fileSaveItem.addActionListener(listen);
         fileSaveAsItem.addActionListener(listen);
         exitItem.addActionListener(listen);
         fileAboutItem.addActionListener(listen);
            editWordCount.addActionListener(listen);


         //set JFrame properties
         setTitle( titleText );
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         setSize( 500, 400 );
         setResizable(false);
        //pack();
         setVisible( true );

      }

      public static void main( String[] args )
      {
         new FileViewer( "FileViewer" );
      }
   }





import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;


public class FileListener implements ActionListener

{

  private JTextArea text;
  private JFileChooser fileChoose;
  private JPanel panel2;
  private JMenuItem fileOpenItem, fileSaveItem, fileNewItem, fileHelpItem, fileAboutItem, fileSaveAsItem, exitItem, editWordCount;
  private JButton setFontBtn;

  private int result = 0;
  private JTextField fileNameText;
  private String setNameFile;
  private String size, fontStyle;
  private String fontChoser[] = {"Regular","Italic","Bold","Bold Italic"};
  private String fontSize[] = {"10","12","15"};
  private JComboBox comboSize, combo;



 /** The font bold. */
  private Font fontBold = new Font(Font.SANS_SERIF, Font.BOLD, 12);

/** The font italic. */
  private  Font fontItallic = new Font(Font.SANS_SERIF, Font.ITALIC, 12);

/** The font bold and italic. */
  private Font ITALICbold = new Font(Font.SANS_SERIF, Font.ITALIC | Font.BOLD, 10);


/** The default font. */
  private Font font3 = new Font(Font.SANS_SERIF, Font.PLAIN, 12);




  public FileListener(JMenuItem fileOpenItem,JMenuItem fileSaveItem,JMenuItem fileNewItem,JMenuItem fileAboutItem,JMenuItem fileSaveAsItem,JMenuItem exitItem,JMenuItem editWordCount, JButton setFontBtn, JTextArea text,JTextField fileNameText)

  {
     this.exitItem = exitItem;
     this.fileOpenItem = fileOpenItem;
     this.fileSaveItem = fileSaveItem;
     this.fileNewItem = fileNewItem;
     this.fileAboutItem = fileAboutItem;
     this.fileSaveAsItem = fileSaveAsItem;
     this.editWordCount = editWordCount;
     this.setFontBtn = setFontBtn;
     this.text = text;
     this.fileNameText = fileNameText;
     this.comboSize = comboSize;
     this.combo = combo;



    //create file chooser
     fileChoose = new JFileChooser();


  }

  public void actionPerformed( ActionEvent ae )
  {
     if(ae.getSource() == fileOpenItem)
     {
       //loadFile();
        result = fileChoose.showOpenDialog(text);
        File file = fileChoose.getSelectedFile( );
        if ( file != null
        && result == JFileChooser.APPROVE_OPTION )
        {
           try
           {
           //open file
              BufferedReader in = new BufferedReader(new FileReader(file));
              StringBuffer sb = new StringBuffer(); // holds the incoming data

           // read all data from file
              String line = null;
              while( (line = in.readLine()) != null)
              {
                 sb.append(line + "\n");
              }

           // done getting data, place it in the text area
              text.setText(sb.toString());
           }
              catch(IOException ioe)
              {
              //unexpected problem as file was found
                 System.out.println(ioe.getMessage());
                 ioe.printStackTrace();
              }


        } //end if

        setNameFile = file.getName();
        fileNameText.setText(setNameFile);



     }
     else if (ae.getSource() == exitItem)
     {
        System.exit(0);
     }

     else if (ae.getSource() == fileNewItem)
     {
        text.setText("");
        text.grabFocus();

     }

     else if(ae.getSource() == fileSaveAsItem)
     {
        saveAs();
     }

     else if(ae.getSource() == fileSaveItem)
     {
        Save();
     }

     else if(ae.getSource() == fileAboutItem)
     {
        JOptionPane.showMessageDialog(null,"218 HW #8: FileViewer\nVersion 3.4\n February 21, 2012\n Developed by M", "About FileViewer", JOptionPane.INFORMATION_MESSAGE);
     }

     else if(ae.getSource() == setFontBtn)
     {
        setFontBtn();
     }





     else if(ae.getSource() == editWordCount)
     {
        WordCount();
        //JOptionPane.showMessageDialog(null, "Found Words", "Word Count", JOptionPane.INFORMATION_MESSAGE);
     }


  }




 /** Present a dialog box to have the user save
 * the file for later use
 */
  public void saveAs()

  {
     int result = fileChoose.showSaveDialog(text);
     File file = fileChoose.getSelectedFile();
     if ( file != null && result == JFileChooser.APPROVE_OPTION )
        try {
           BufferedWriter out = new BufferedWriter(new FileWriter(file));
           out.write(text.getText());
           out.close();
        } 
           catch( IOException ioe ) {
              ioe.printStackTrace();
           }

     setNameFile = file.getName();
     fileNameText.setText(setNameFile);

  }

  public void Save()

  {
     File newFile = new File(fileNameText.getText());
  //String getAreaName = text.getText();
  //setNameFile = file.getName();

     String whatIsIn = text.getText();

     try {

     /*    BufferedWriter out = new BufferedWriter(new FileWriter(newFile));
        out.write(text.getText());
        out.close();

        */


        /*
                    PrintWriter fos = new PrintWriter(newFile);
                    fos.print(text.getText());
                    fos.close(); */


        if (newFile.exists()) {
           FileOutputStream fos = new FileOutputStream(newFile, false);
           fos.write(whatIsIn.getBytes());
           fos.close();

        }





     } 
        catch( IOException ioe ) {
           ioe.printStackTrace();
        }

     setNameFile = newFile.getName();
     fileNameText.setText(setNameFile);

  }

  public void WordCount()

  {

     String data = text.getText();
     Scanner s = new Scanner(data);
     Pattern p = Pattern.compile(" ");
     String words = null;
     int count = 0;
     while (s.hasNext())
     {
        words = s.next();
        count += 1;
     }
     JOptionPane.showMessageDialog(null, "Word Count:  " + count);


  }




  public void setFontBtn()

  {
     fontStyle = (String)combo.getSelectedItem();
     size = (String)comboSize.getSelectedItem();


     if (fontStyle.equals("Regular") && size.equals("10"))  
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
        text.setFont(font);
     }

     else if (fontStyle.equals("Regular") && size.equals("12")) 
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        text.setFont(font);
     }


     else if (fontStyle.equals("Regular") && size.equals("15")) 
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
        text.setFont(font);
     }

     // italic

     else if (fontStyle.equals("Italic") && size.equals("10"))  
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
        text.setFont(font);
     }

     else if (fontStyle.equals("Italic") && size.equals("12"))  
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        text.setFont(font);
     }

     else if (fontStyle.equals("Italic") && size.equals("15"))  
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
        text.setFont(font);
     }

     //bold

     else if (fontStyle.equals("Bold") && size.equals("10"))    
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
        text.setFont(font);
     }

     else if (fontStyle.equals("Bold") && size.equals("12"))    
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        text.setFont(font);
     }

     else if (fontStyle.equals("Bold") && size.equals("15"))    
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
        text.setFont(font);
     }

     // bold italic

     else if(fontStyle.equals("Bold Italic") && size.equals("10"))  
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
        text.setFont(font);
     }

     else if (fontStyle.equals("Bold Italic") && size.equals("12")) 
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        text.setFont(font);
     }

     else if (fontStyle.equals("Bold Italic") && size.equals("15")) 
     {
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
        text.setFont(font); 


     }


  }

}



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;


public class HelpListener implements ActionListener

{


  private JMenuItem fileAboutItem;


    public HelpListener(JMenuItem fileAboutItem)

    {
    this.fileAboutItem = fileAboutItem;

    }

 public void actionPerformed( ActionEvent ae )
  {



        JOptionPane.showMessageDialog(null, 
           "218 HW #8: FileViewer\nVersion 3.4\n February 21, 2012\n Developed by Marin", "About FileViewer",
           JOptionPane.INFORMATION_MESSAGE);

  }


}

Edited 3 Years Ago by peter_budo: Removed name

and the error message

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at FileListener.setFontBtn(FileListener.java:249)
	at FileListener.actionPerformed(FileListener.java:137)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6290)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
	at java.awt.Component.processEvent(Component.java:6055)
	at java.awt.Container.processEvent(Container.java:2039)
	at java.awt.Component.dispatchEventImpl(Component.java:4653)
	at java.awt.Container.dispatchEventImpl(Container.java:2097)
	at java.awt.Component.dispatchEvent(Component.java:4481)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
	at java.awt.Container.dispatchEventImpl(Container.java:2083)
	at java.awt.Window.dispatchEventImpl(Window.java:2482)
	at java.awt.Component.dispatchEvent(Component.java:4481)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:648)
	at java.awt.EventQueue.access$000(EventQueue.java:84)
	at java.awt.EventQueue$1.run(EventQueue.java:607)
	at java.awt.EventQueue$1.run(EventQueue.java:605)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$2.run(EventQueue.java:621)
	at java.awt.EventQueue$2.run(EventQueue.java:619)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:618)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

I'll have a look at it, I'll start with that nullpointerexception.
I'll let you know if I find something.
but to make it easier for yourself, you may want to look into spacing and white lines in your code, it doesn't make it easier to read as well formatted code :)

nullpointerexception: you are selecting your value in the FileReader class, but your FileListener class is trying to select it from the one in there, in which you haven't select anything. you need to get the value in the FileReader class, and send it as a parameter to the FileListener class.

in your FileListener constructor, you set all the data from the FileReader class,but you shouldn't do that. whatever you select, press, ... all the events are occuring in the FileReader class.

you need to rethink your entire gui.
you are now passing all your Swing elements to your FileListener class, and creating doubles there.

DON'T do that.
you are actually selecting a value in your FileReader class, and pressing a button there, so the actionlistener and actionperformed are also there. but, since you copied your swing elements in your FileListener class, you try to get the selectedItem there, but you copied them in there, in the original state. nothing is selected.

so, just run the actionPerformed in your FileReader class, select the value there and pass it as a parameter to your FileListener class.

public BtnListener(JButton setFontBtn,JTextArea text, JComboBox comboSize,JComboBox combo )
		
		{
		this.setFontBtn = setFontBtn;
		this.text = text;
		this.combo = combo;
		this.comboSize = comboSize;
		
		}

I got it know

Thanks

ehm ... I'm not exactly sure what you've just done, but it doesn't look like a correct sollution, when I look at the previous code you've shown.

BTW: I've just noticed I made a mistake in my previous posts, sorry for that:
you should deal with your actionlisteners and getValue in the FileViewer class (have a FileReader class myself here, which I saw open)

Can you show me the code you have now, because I'm not really sure about how you've solved your problem, would like to know.

I did seperete class for button

import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.io.*;


public class BtnListener implements ActionListener

{


      private JButton setFontBtn;
     		 private JComboBox comboSize, combo;
			        private JTextArea text;

		
		public BtnListener(JButton setFontBtn,JTextArea text, JComboBox comboSize,JComboBox combo )
		
		{
		this.setFontBtn = setFontBtn;
		this.text = text;
		this.combo = combo;
		this.comboSize = comboSize;
		
		}

 public void actionPerformed( ActionEvent ae )
      {
  				String fontStyle = (String)combo.getSelectedItem();
            String size = (String)comboSize.getSelectedItem();
         
         
            if (fontStyle.equals("Regular") && size.equals("10"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Regular") && size.equals("12"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
               text.setFont(font);
            }
            
            
            else if (fontStyle.equals("Regular") && size.equals("15"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
               text.setFont(font);
            }
            
            // italic
            
            else if (fontStyle.equals("Italic") && size.equals("10"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Italic") && size.equals("12"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Italic") && size.equals("15"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
               text.setFont(font);
            }
            
            //bold
            
            else if (fontStyle.equals("Bold") && size.equals("10"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Bold") && size.equals("12"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Bold") && size.equals("15"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
               text.setFont(font);
            }
            
            // bold italic
            
            else if(fontStyle.equals("Bold Italic") && size.equals("10"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 10);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Bold Italic") && size.equals("12"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
               text.setFont(font);
            }
            
            else if (fontStyle.equals("Bold Italic") && size.equals("15"))	
            {
               Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15);
               text.setFont(font);	
            
            
            }
    
      }


}

still I need to finish fonts

Edited 4 Years Ago by mehnihma: n/a

I can see that you've just created a new class, but that's not what you should have done. your listener is not supposed to contain UI elements, it's supposed to be applied to them.

Then I dont understand what I needed to do because this now works, can you also tell me why my save is not working in this program?

i has to save a file, if I open same text document it needs to save it and overwrite original

I have succeeded to do it, it works now

thanks for the help

but I still dont understand part with containing UI elements

I'll give you a for instance: at this point, you have a Button Listener. that comes in handy, BUT, ...
and here comes the Big Bad But ... you won't be able to use it in another application, since it 'll need those exact parameters to exist and to be passed to it, to work.

at the other point, you have your UI components, which you basically duplicate, so just use extra memory.

here 's a link to the official Swing tutorials, look over them, maybe that 'll make some things a bit more clear: Swing tutorial

This question has already been answered. Start a new discussion instead.