Results 1 to 9 of 9
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default another nullpointer in swing

    The next code copied from the Core Java book (first vol) results into an null pointer which is related to
    the method: public static boolean isValid(String s)...
    Anybody knows why this happened?


    Exception in thread "main" java.lang.NullPointerException
    at javax.swing.text.JTextComponent.getText(JTextCompo nent.java:1721)
    at willemlearningjava.IntTextField.isValid(Validation Test.java:164)
    at java.awt.Component.invalidateIfValid(Component.jav a:2815)
    at java.awt.Component.setLocale(Component.java:1885)
    at javax.swing.JComponent.<init>(JComponent.java:592)
    at javax.swing.text.JTextComponent.<init>(JTextCompon ent.java:297)
    at javax.swing.JTextField.<init>(JTextField.java:212)
    at javax.swing.JTextField.<init>(JTextField.java:193)
    at willemlearningjava.IntTextField.<init>(ValidationT est.java:147)
    at willemlearningjava.ValidationTestFrame.<init>(Vali dationTest.java:47)
    at willemlearningjava.ValidationTest.main(ValidationT est.java:25)
    Java Result: 1




    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package willemlearningjava;
    
    /**
     *
     * 
     */
    
     import java.awt.*;
     import java.awt.event.*;
     import java.awt.geom.*;
     import javax.swing.*;
     import javax.swing.event.*;
     import javax.swing.text.*;
     import javax.swing.undo.*;
    
     public class ValidationTest
     {
        public static void main(String[] args)
        {
           ValidationTestFrame frame = new ValidationTestFrame();
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setVisible(true);
        }
     }
    
     /**
        A frame with a clock and text fields to set the time.
     */
     class ValidationTestFrame extends JFrame
     {
        public ValidationTestFrame()
        {
           setTitle("ValidationTest");
           setSize(WIDTH, HEIGHT);
    
           Container contentPane = getContentPane();
    
           JPanel panel = new JPanel();
    
           // add text fields
    
           hourField = new IntTextField(12, 3);
           panel.add(hourField);
    
           minuteField = new IntTextField(0, 3);
           panel.add(minuteField);
    
           // add Set button
    
           JButton setButton = new JButton("Set");
           panel.add(setButton);
           setButton.addActionListener(new
              ActionListener()
              {
                 public void actionPerformed(ActionEvent event)
                 {
                    if (hourField.isValid() && minuteField.isValid())
                       clock.setTime(
                          hourField.getValue(),
                          minuteField.getValue());
                 }
              });
    
           contentPane.add(panel, BorderLayout.SOUTH);
    
           // add clock
    
           clock = new ClockPanel();
           contentPane.add(clock, BorderLayout.CENTER);
        }
    
        public static final int WIDTH = 300;
        public static final int HEIGHT = 300;
    
        private IntTextField hourField;
        private IntTextField minuteField;
        private ClockPanel clock;
     }
      /**
        A document that can only hold valid integers or their
        substrings
     */
     class IntTextDocument extends PlainDocument
     {
        public void insertString(int offs, String str,
           AttributeSet a)
           throws BadLocationException
        {
           if (str == null) return;
    
           String oldString = getText(0, getLength());
           String newString = oldString.substring(0, offs)
              + str + oldString.substring(offs);
    
           if (canBecomeValid(newString))
              super.insertString(offs, str, a);
        }
    
        /**
           A helper function that tests whether a string is a valid
           integer
           @param s a string
           @return true if s is a valid integer
         */
        public static boolean isValid(String s)
        {
           try
           {
              Integer.parseInt(s);
              return true;
           }
           catch(NumberFormatException e)
           {
              return false;
           }
        }
    
    
        /**
           A helper function that tests whether a string is a
           substring of a valid integer
           @param s a string
           @return true if s can be extended to a valid integer
        */
        public static boolean canBecomeValid(String s)
        {
           return s.equals("") || s.equals("-") || isValid(s);
        }
     }
    
     /**
        A text field for editing integer values
     */
     class IntTextField extends JTextField
     {
        /**
           Constructs an IntTextField.
           @param defval the default value
           133.    */
        public IntTextField(int defval, int size)
        {
           super("" + defval, size);
           setInputVerifier(new IntTextFieldVerifier());
           //      Document doc = getDocument();
           //      doc.addUndoableEditListener(new UndoListener());
       }
    
         protected Document createDefaultModel()
         {
           return new IntTextDocument();
        }
    
         /**
          Checks if the contents of this field is a valid integer.
           @return true of the field contents is valid
        */
        public boolean isValid()
        {
           return IntTextDocument.isValid(getText());
        }
    
        /**
           Gets the numeric value of the field contents.
           @param the number that the user typed into the field, or
           0 if the field contents is not valid.
        */
        public int getValue()
        {
           try
           {
              return Integer.parseInt(getText());
           }
           catch(NumberFormatException e)
           {
              return 0;
          }
        }
     }
    
     /**
        A verifier that checks if the contents of a text component
        is a valid integer.
     */
     class IntTextFieldVerifier extends InputVerifier  {
        public boolean verify(JComponent component)
        {
           String text = ((JTextComponent)component).getText();
           return IntTextDocument.isValid(text);
        }
     }
    
     /**
       A panel that draws a clock. (Unchanged from TextTest.)
     */
     class ClockPanel extends JPanel
     {
        public void paintComponent(Graphics g)
        {
            // draw the circular boundary
    
           super.paintComponent(g);
           Graphics2D g2 = (Graphics2D)g;
           Ellipse2D circle
              = new Ellipse2D.Double(0, 0, 2 * RADIUS, 2 * RADIUS);
           g2.draw(circle);
    
           // draw the hour hand
    
           double hourAngle
              = Math.toRadians(90 - 360 * minutes / (12 * 60));
           drawHand(g2, hourAngle, HOUR_HAND_LENGTH);
    
           // draw the minute hand
    
           double minuteAngle
              = Math.toRadians(90 - 360 * minutes / 60);
           drawHand(g2, minuteAngle, MINUTE_HAND_LENGTH);
       }
    
        public void drawHand(Graphics2D g2,
           double angle, double handLength)
        {
           Point2D end = new Point2D.Double(
              RADIUS + handLength * Math.cos(angle),
              RADIUS - handLength * Math.sin(angle));
           Point2D center = new Point2D.Double(RADIUS, RADIUS);
           g2.draw(new Line2D.Double(center, end));
        }
    
        /**
           Set the time to be displayed on the clock
           @param h hours
           @param m minutes
       */
        public void setTime(int h, int m)
        {
           minutes = h * 60 + m;
           repaint();
        }
    
        private double minutes = 0;
        private double RADIUS = 100;
        private double MINUTE_HAND_LENGTH = 0.8 * RADIUS;
        private double HOUR_HAND_LENGTH = 0.6 * RADIUS;
     }

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default Re: another nullpointer in swing

    It is not related to public static boolean, it is related to public boolean isValid() at your IntTextField class (at willemlearningjava.IntTextField.isValid(Validation Test.java:164))
    The problem is the name of your method. isValid is a method of the component class (Component (Java Platform SE 6)), so you overwrite this method. It`s called before your textfield documents is set, so you will get this NPE!
    So you have a few options. The best would be (in my opinion) to rename this method!

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default Re: another nullpointer in swing

    eRaaaa is right. Still, I think that's a lot of code for a simple requirement. It does, of course respect separation of responsibilities far better that this, which I created for the same need.
    Java Code:
    import javax.swing.JTextField;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.DocumentFilter.FilterBypass;
    import javax.swing.text.PlainDocument;
    
    public class LongTextField extends JTextField {
    
      public LongTextField() {
        super();
      }
    
      public LongTextField(int columns) {
        super("", columns);
      }
    
      public LongTextField(String text) {
        super(filterText(text));
      }
    
      public LongTextField(String text, int columns) {
        super(filterText(text), columns);
      }
    
      private static String filterText(String text) {
        return text.replaceAll("[^\\d]", "");
      }
    
      {
        ((PlainDocument) getDocument()).setDocumentFilter(new DocumentFilter() {
    
          @Override
          public void insertString(FilterBypass fb, int offset, String text,
                  AttributeSet attr) throws BadLocationException {
            if (text != null) {
              text = text.replaceAll("[^\\d]", "");
              if (text.isEmpty()) {
                return;
              }
              if (getText().equals("0")) {
                super.replace(fb, 0, 1, text, attr);
              } else {
                super.insertString(fb, offset, text, attr);
              }
              removeLeadingZeros(fb);
            }
          }
    
          @Override
          public void remove(FilterBypass fb, int offset, int length)
                  throws BadLocationException {
            super.remove(fb, offset, length);
            removeLeadingZeros(fb);
          }
    
          @Override
          public void replace(FilterBypass fb, int offset, int length,
                  String text, AttributeSet attrs) throws BadLocationException {
            if (text != null) {
              text = text.replaceAll("[^\\d]", "");
              if (text.isEmpty()) {
                return;
              }
              super.replace(fb, offset, length, text, attrs);
              removeLeadingZeros(fb);
            }
          }
    
          private void removeLeadingZeros(FilterBypass fb)
                  throws BadLocationException {
            while (!getText().isEmpty() && getText().charAt(0) == '0') {
              super.remove(fb, 0, 1);
            }
          }
        });
      }
    
      public long getValue() {
        if (getText().isEmpty()) {
          return 0;
        }
        return Long.parseLong(getText());
      }
    
      public void setValue(long value) {
        setText(Long.toString(value));
      }
    }
    Note that typing too many digits will lead to a NumberFormatException. You can easily add code to prevent that.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: another nullpointer in swing

    eRaaaa I suspected something like that, thank you very much!
    wow, db, I'll study your code instead: great!
    (so Italic in netbeans means overwrite, right?)

  5. #5
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: another nullpointer in swing

    (so Italic in netbeans means overwrite, right?) maybe not?
    yes changed isValid into isValid2 and code runs, perfect!

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default Re: another nullpointer in swing

    Quote Originally Posted by willemjav View Post
    (so Italic in netbeans means overwrite, right?) maybe not?
    There's a setting for that. In my settings (and I haven't changed many defaults), italic means static.

    Oh, and it's override, not overwrite.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  7. #7
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: another nullpointer in swing

    but the funny thing is that override means also overwrite, right?
    because that's what you practically do.

  8. #8
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: another nullpointer in swing

    Many thanks to both of you, and thread closed.

  9. #9
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default Re: another nullpointer in swing

    Quote Originally Posted by willemjav View Post
    but the funny thing is that override means also overwrite, right?
    because that's what you practically do.
    And methods perform functions, but Java has methods -- not functions. Using the correct term is important for communication.

    [OT] In my younger days, when transistors were just becoming affordable to hobbyists, a much older friend threw together an ultrasound oscillator, wired to a tweeter. Only he called it a supersonic generator. We knew what he meant, and communication wasn't hampered. But. What if he had posted on some forum (doh, this was long before the internet!) about a problem with a supersonic generator? He might not have been understood at all.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. why this pgm is getting NUllPointer.
    By javastuden in forum New To Java
    Replies: 2
    Last Post: 02-23-2013, 10:13 AM
  2. Replies: 1
    Last Post: 05-11-2012, 06:41 PM
  3. Nullpointer exception
    By naveen516 in forum New To Java
    Replies: 2
    Last Post: 12-19-2011, 04:36 AM
  4. NullPointer help
    By moosick in forum AWT / Swing
    Replies: 1
    Last Post: 04-02-2011, 02:35 AM
  5. Nullpointer Exception???
    By kipcorn91 in forum AWT / Swing
    Replies: 5
    Last Post: 10-28-2010, 11:19 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •