Hi,

I have fixed some parameters to my constructor but unable to make them work.

Here is my sample code:-

public MyConstructor(String filename, int value1, int value2){

           this.filename = filename;
           this.value1 = value1;
           this.value2 = value2;

           File reading code
           BufferedReader fh = new BufferedReader(new FileReader(filename)); 
              ................

                 }

              public static void main(String args[]) {
                       String s1 = args[1];
                       String s2 = args[2];

                       int value1 = Integer.parseInt(s1.trim());
                       int value2 = Integer.parseInt(s2.trim());

         MyConstructor myobject = new MyConstructor(args[0], value1, value2);

                                                     }

Can anybody help me to fix this problem.

Thanks

Recommended Answers

All 14 Replies

Maybe, if we knew what "does not work" meant.

A little more information is needed, obviously.

Do you get compile time messages?
Do you get exceptions at runtime?
Does it run, but produce unexpected output? If so, how does it differ from the expected output?

If I create a method like

public void ReadFile(String filename, int Value1, int value2) {
    this.filename = filename;
    this.value1 = value1;
    this.value2 = value2;
.........................
    BufferedReader fh = new BufferedReader(new FileReader(filename));
 ............................................  
 }

Now if I want to call it in my previous example constructor like

public Constructor() {

...........................

  //How do I call my method ?
  //I am doing like this

   ReadFile(filename, range1, range2);
 }

and then I will call this method in the main as:-

public static void main(String args[]) {
     
         String s1 = args[1];
         String s2 = args[2];
         String filename = args[0];

         int value1 = Integer.parseInt(s1.trim());
         int value2 = Integer.parseInt(s2.trim());
  
       MyClass exmpl = new MyClass();
       exmpl.ReadFile(filename, value1, value2) 
      /// Will it work.. If not howto do then ?
}

Thanks

Most important am I calling the method correctly ? in the constructor ?

ReadFile(filename, value11, value2);

I am a bit confused about howto call a method inside a constructor and how do I handle exception in this case using this example reading file. I am already using try catch inside my ReadFile method.

Thanks

I am actually using a class inside a class. Can anybody point out my mistake. My code is compiling OK but when I run it. It gives me NullPointException at java.io.FileInputStream<init>. Like this one. Need help.

The basic structure of my code is like this:-

public class Class1 extends JFrame{

   public Class1(){this.somevalues
  setDefaultCloseOperation(EXIT_ON_CLOSE);
      setMinimumSize(new Dimension(1000, 200));
      class2obj = new Class2();
      getContentPane().add(class2obj, BorderLayout.CENTER);
      pack();
      }
      }

   static class Class2  extends JPanel implements MouseMotionListener {
   
   public String filename;
   public int value1;
   public int value2;

  public Class2(){
     super();
     readFile(filename, value1, value2);  
       }
  public readFile(String filename, int value1, int value2){
       this.filename = filename;
       this.value1 = value1;
       this.value2 = value2;
       ............
       try{
            BufferedReader fh = new BufferedReader(new FileReader(filename)); 
.............................
  fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
...............

public static void main(String args[]) {
         String s1 = args[1];
         String s2 = args[2];
         String filename = args[0];
         
         int value1 = Integer.parseInt(s1.trim());
         int value2 = Integer.parseInt(s2.trim()); 
          
         Class2 obj = new Class2();
         obj.readFile(filename, value1, value2);
         
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new Class1().setVisible(true);
      }
      });
      }
 }

Thanks

Reading a file from a constructor is normally not a good idea.

Also, why are you attempting to "read" it from both the constructor and the main method?

Also, are you closing the file before attempting to "open" it again?

Post the entire stack trace.

Hi this is my code. Can you plz help me make it work. I am unable to understand what I am missing.

import java.io.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;

      class Class1 extends JFrame {
              public Color color;
              public int skeeing;
              public int myfix1;
              public int myfix2;
              public int width;
              public String text;
              public int end;

           
              private JPanel InnerClass;
              public Class1(){
                  
              }

      public Class1(int skeeing, int myfix1, int width, int myfix2, Color c,String text) {
        this.color = c;
        this.skeeing = skeeing;
        this.myfix1 = myfix1;
        this.width = width;
        this.myfix2 = myfix2;
        this.text = text;

      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setMinimumSize(new Dimension(400, 400));
      InnerClass = new InnerClass();
      getContentPane().add(InnerClass, BorderLayout.CENTER);
      pack();
      }
      static class InnerClass extends JPanel implements MouseMotionListener, MouseListener {
      public List<Glyph> glyphs;
          public int skeeing;
          public int bottom;
          public int width;
          public String f[];
          public int value1;
          public int value2;
          private final static int NUM_FIELDS = 8;
          BufferedImage image;
	  Graphics2D g2d;
          Point startPoint = null;
          Point endPoint = null;
         
          public int start;
          public int x;
          public int y;
          int scaledvalue;
          public int end;
         
          
          public String filename = null;
          
          
        public InnerClass(){
 
           super();
           addMouseMotionListener(this);
           addMouseListener(this);
           boolean mouseClicked = false;
            
          readFile(filename);         
      }
        
       public void readFile(String filename){
           this.filename = filename;
         
           glyphs = new ArrayList<Glyph>();
           String n = null;  
           BufferedReader fh;
        try{
            fh = new BufferedReader(new FileReader(filename));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){

                f = n.split("\t");
                skeeing = Integer.parseInt(f[1].trim());
                bottom = Integer.parseInt(f[2].trim());
               
                width = bottom - skeeing; 
                int fixvalue1 = 60;
                int fixvalue2 = 27;
 
              
                String text = f[3];
                Color color = new Color(Integer.parseInt(f[4]));

                glyphs.add(new Glyph(skeeing, fixvalue1, width, fixvalue2, color, text));

            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
       }
      public void paintComponent(Graphics g) {
      super.paintComponent(g);
      for (Glyph glyph : glyphs){
      glyph.draw(g);
      }
      			
      }
      		private void createEmptyImage()
		{
			image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
			g2d = (Graphics2D)image.getGraphics();
			g2d.setColor(Color.BLUE);
			g2d.drawString("Studying Hard", 40, 15);
		}

		public void clear()
		{
			createEmptyImage();
			repaint();
		}
      public void mousePressed(MouseEvent e) {
				             
      } 
      public void mouseDragged(MouseEvent e) {
          			   
      }
      public void mouseReleased(MouseEvent e) {
          			
      }
      public void mouseMoved(MouseEvent e) {
      for(Glyph g : glyphs){
      g.showLabel( g.contains(e.getX(), e.getY()) );
      }
      scaledvalue = start * 100;

      repaint();
      }
   
      public void mouseClicked(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      }

      static class Glyph {
      private Rectangle bounds;
      private Color color;
      private Paint paint;
      private String label;
      private boolean showLabel = false;
      public Glyph(int x, int y, int width, int height, Color color, String label) {
      bounds = new Rectangle(x, y, width, height);
      this.color = color;
      this.paint = new GradientPaint(x, y, color, x, y+height, Color.WHITE);
      this.label = label;
      }
      public void draw(Graphics g){
      Graphics2D g2 = (Graphics2D)g;
      g2.setPaint(paint);
      g2.fill(bounds);
      if (showLabel){
      g2.setColor(Color.BLACK);
      int labelWidth = g2.getFontMetrics().stringWidth(label);
      int fontHeight = g2.getFontMetrics().getHeight();
      g2.drawString( label,
      (int)(bounds.getX()),
      (int)(bounds.getY()));
      }
      }
      public boolean contains(int x, int y){
      return bounds.contains(x,y);
      }
      public void showLabel(boolean show){
      showLabel = show;
      }
      }
      public static void main(String args[]) {
        
         String filename = args[0];
         
          
         InnerClass test = new InnerClass();
         test.readFile(filename);
         
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new Class1().setVisible(true);
      }
      });
      }
    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), skeeing, myfix1, width, myfix2, text);
    }
      }

Thanks

Like I said, post the entire stacktrace. Don't just throw code at people and cry "fix it".

This the runtime error that I am getting:-

Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at ClassInner1$InnerClass.readFile.(Class1 java : 95)
at ClassInner1$InnerClass<init>(Class1 java : 85)
at Class1.main.(Class1 java : 200)

I am really not understanding what's wrong with it :(

Here are these troubling lines:_

readFile(filename) - line 85
fh = new BufferedReader(new FileReader(filename)); - line 95
InnerClass test = new InnerClass(); - line 200

Thanks a need help

Do you see a problem here:

....
    static class InnerClass extends JPanel implements  MouseMotionListener, MouseListener {
        ....
        public String filename = null;
        ....

        public InnerClass() {
            ....
            readFile(filename);         
        }
....

OK here is the complete code

import java.io.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;

      public class Testing extends JFrame {
              public Color color;
              public int wow;
              public int fixvalue1;
              public int fixvalue2;
              public int width;
              public String text;
              public int end;


              private JPanel InnerClass;
              public Testing(){

              }

      public Testing(int wow, int fixvalue1, int width, int fixvalue2, Color c,String text) {
        this.color = c;
        this.wow = wow;
        this.fixvalue1 = fixvalue1;
        this.width = width;
        this.fixvalue2 = fixvalue2;
        this.text = text;

      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setMinimumSize(new Dimension(800, 400));
      InnerClass = new InnerClass();
      getContentPane().add(InnerClass, BorderLayout.CENTER);
      pack();
      }
      static class InnerClass extends JPanel implements MouseMotionListener, MouseListener {
      public List<Glyph> glyphs;
          public int wow;
          public int bottom;
          public int width;
          public String f[];
          public int value1;
          public int value2;
          private final static int NUM_FIELDS = 9;
          BufferedImage image;
      Graphics2D g2d;
          Point startPoint = null;
          Point endPoint = null;
          private int xMin;
          private int xMax;
      private int yMin;
      private int yMax;
          public int start;
          public int x;
          public int y;
          int scaledvalue;
          public int end;

          public int first;
          public int second;


          public String filename = null;


        public InnerClass() {

           super();
           addMouseMotionListener(this);
           addMouseListener(this);
           boolean mouseClicked = false;
           InnerClass wow = new InnerClass(); 
           wow.readFile(filename);  
      }

       public void readFile(String filename){
           this.filename = filename;

           glyphs = new ArrayList<Glyph>();
           String n = null;  
           BufferedReader fh;
        try{
            fh = new BufferedReader(new FileReader(filename));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){

                f = n.split("\t");
                value1 = Integer.parseInt(f[5].trim());
                value2 = Integer.parseInt(f[6].trim());

                width = Integer.parseInt(f[3].trim());;  
                int arms = Integer.parseInt(f[0].trim());
                String text = f[5];
                Color color = new Color(Integer.parseInt(f[7]));
                int fixvalue1 = 60;
                int fixvalue2 = 27;

                glyphs.add(new Glyph(value1, fixvalue1, width, fixvalue2, color, text));

            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
       }
      public void paintComponent(Graphics g) {
      super.paintComponent(g);
      for (Glyph glyph : glyphs){
      glyph.draw(g);
      }
                if (image == null)
            {
                createEmptyImage();
            }

            g.drawImage(image, 0, 0, null);


            if (startPoint != null && endPoint != null)
            {
                x = Math.min(startPoint.x, endPoint.x);
                y = Math.min(startPoint.y, endPoint.y);
                width = Math.abs(startPoint.x - endPoint.x);
                int height = Math.abs(startPoint.y - endPoint.y);
                g.drawRect(x, y, width, height);
                                int shuru = startPoint.x * 360000;
                                int khatam = endPoint.x * 360000;

            }
      }
            private void createEmptyImage()
        {
            image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            g2d = (Graphics2D)image.getGraphics();
            g2d.setColor(Color.BLUE);
            g2d.drawString("Trying Hard", 40, 15);
        }

        public void clear()
        {
            createEmptyImage();
            repaint();
        }
      public void mousePressed(MouseEvent e) {
                startPoint = e.getPoint();
                xMin = startPoint.x;
                xMax = startPoint.x;
                yMin = startPoint.y;
                yMax = startPoint.y;                   
      } 
      public void mouseDragged(MouseEvent e) {
                    endPoint = e.getPoint();
                xMin = Math.min(xMin, endPoint.x);
                xMax = Math.max(xMax, endPoint.x);
                yMin = Math.min(yMin, endPoint.y);
                yMax = Math.max(yMax, endPoint.y);
                repaint(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1);      
      }
      public void mouseReleased(MouseEvent e) {
                    x = Math.min(startPoint.x, endPoint.x);
                y = Math.min(startPoint.y, endPoint.y);
                width = Math.abs(startPoint.x - endPoint.x);
                int height = Math.abs(startPoint.y - endPoint.y);
                                //g2d.scale(2.0,2.0);
                                //int transparency = Transparency.OPAQUE; 
                                g2d.dispose();
                g2d.setColor( e.getComponent().getForeground() );
                                //g2d.setColor(new Color(128, 255, 128, 56)); // Translucent color
                g2d.drawRect(x, y, width, height);
                startPoint = null;

      }
      public void mouseMoved(MouseEvent e) {
      for(Glyph g : glyphs){
      g.showLabel( g.contains(e.getX(), e.getY()) );
      }
      scaledvalue = start * 100;

      repaint();
      }

      public void mouseClicked(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      }

      static class Glyph {
      private Rectangle bounds;
      private Color color;
      private Paint paint;
      private String label;
      private boolean showLabel = false;
      public Glyph(int x, int y, int width, int height, Color color, String label) {
      bounds = new Rectangle(x, y, width, height);
      this.color = color;
      this.paint = new GradientPaint(x, y, color, x, y+height, Color.WHITE);
      this.label = label;
      }
      public void draw(Graphics g){
      Graphics2D g2 = (Graphics2D)g;
      g2.setPaint(paint);
      g2.fill(bounds);
      if (showLabel){
      g2.setColor(Color.BLACK);
      int labelWidth = g2.getFontMetrics().stringWidth(label);
      int fontHeight = g2.getFontMetrics().getHeight();
      g2.drawString( label,
      (int)(bounds.getX()),
      (int)(bounds.getY()));
      }
      }
      public boolean contains(int x, int y){
      return bounds.contains(x,y);
      }
      public void showLabel(boolean show){
      showLabel = show;
      }
      }
      public static void main(String args[]) {

         String filename = args[0];


         InnerClass obj = new InnerClass();
         obj.readFile(filename);

      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new Testing().setVisible(true);
      }
      });
      }
    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), wow, fixvalue1, width, fixvalue2, text);
    }
      }

Hope it helps

I never said I didn't have enough code, and I thought I already said don't just regurgitate a bunch of code expect someone else to clean it up. I pointed out your problem in my last post. Read that again.

Here is my input file sample

12 andrew 3ghd 50 one 1 50 000
14 symon 8hds 48 two 51 101 000

Thanks

Is the problem bcoz I am setting filename to null ?
Or bcoz I have to set the filename also as static ?

I am a newbie so plz be kind to my mistakes.

Thanks

The error is nullpointerexception, right?

commented: right +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.