Simple java issue

Associate
Joined
13 Jan 2007
Posts
2,424
Location
Belfast,Northern Ireland
Basically I want to be able to call a method i.e. drawCircle in my main method, containing arguements read in through a file. Now I have my main iterating through the data fine. I also have another class called Draw extending JPanel with paintComponent so I have a background on screen. Now I could add to this from the Draw class by typing g.fillOval or whatever but I want to do it from the main as I said above?

This would mean my code would be lots tidier and allow me to have things such as fillOval(array, array[i+1) etc in my main which would be handy.

I know this is a very simple problem, im just brain dead at the moment it seems. Any way to fix this or get around it easily enough?
 
Could you post the code for the classes? This would help as it's not immediately clear what you are trying to do from your description.
 
Code:
//Research.java

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


public class Research {

	public static void main(String[] args) {
		
		JFrame f = new JFrame("Circuit");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Draw d = new Draw();
		f.add(d);
		f.setSize(700, 500);		
		f.setVisible(true);
		
		try
		{
			Scanner s = new Scanner(new File("C:\\Users\\Shicky\\Desktop\\sampleTestData.txt"));
			ArrayList<String> tokens = new ArrayList<String>();
			
			int z = 0;
						
			while(s.hasNext())
			{
				String str = s.nextLine();
				if( str.length() >0)
				{
					String[] p = str.split("\\s+");
					switch (str.charAt(0))
					{
						//case '*': System.out.println("ignore");
						case 'c': 
							z++; 
						    System.out.println(p[0]);
						    
						    break;
						case 'l':
						    
						
					}	
					
				}
			}
			
			System.out.println(z);	
		
			s.close();
			
		}
		catch(Exception e)
		{
			
			System.out.println("Could not open file." );
			e.printStackTrace();
		}
		
	}

}

Code:
//Draw.java

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

public class Draw extends JPanel {

	public void paintComponent(Graphics g){
		super.paintComponent(g);
		this.setBackground(Color.WHITE);
	}
			
}

*Sorry that might have been unclear, had to jump out there. Basically in my switch statement when it hits the l case I want it to draw a circle on the canvas. The co-ordinates and additional detail I want to use for labels etc comes from parts of the split string. So essentially right now I can make a circle no problem, but I must do this inside the Draw class. What I want to do is draw a circle from the main class by saying g.fillOval(p[1], [2]) etc? I realise g.fillOval wont work from main but I want to find what will
 
Last edited:
Just out of interest, is this for the HND in computing course? I remember doing something very similar years ago.
 
Why don't you just write drawCircleWithLabels in the draw class and call that?

d.drawCircleWithLabels(p[1],p[2])

Im not sure I understand you correctly but if so I couldn't access p from the draw class?

Essentially im wondering is there anyway to call the paintComponent/paint methods from outside the draw class i made and if not, any possible solutions anyone sees?
 
no, you write the drawCircleWithLabels in the draw class and as you have an instance of it in the main one, you can reference it and pass it the p[1] variables.


Just call it with
Code:
String[] p = str.split("\\s+");
switch (str.charAt(0))
{
	//case '*': System.out.println("ignore");
	case 'c': 
	    z++; 
	    System.out.println(p[0]);	    
            d.drawCircleWithLabels(p[1],p[2])
            break;
	case 'l':
	   
	
}

You must be able to get create a new graphics instance in the draw class and paint that to the screen?

Something like this.Add(newComponent)
 
Last edited:
New Class

Code:
import javax.swing.*;
import java.awt.*;

class MyOval extends JPanel {

private string _lbl1;
private string _lbl2;

    public MyOval(string lbl1, string lbl2) {
        _lbl1 = lbl1;
		_lbl2 = lbl2;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);       
		g.drawOval(0, 0, 100, 50);
        // Draw Text
        g.drawString(_lbl1,10,20);
		g.drawString(_lbl2,10,20);
    }  
}

then
Just call it with
Code:
String[] p = str.split("\\s+");
switch (str.charAt(0))
{
	//case '*': System.out.println("ignore");
	case 'c': 
	    z++; 
	    System.out.println(p[0]);	    
            f.add(new MyOval(p[1],p[2]))
            break;
	case 'l':
	   
	
}

No idea if that's syntactically correct as I just dragged bits from the Sun Java site.
 
That seemed to work and make sense for the most part but when I implemented it, I then had problems with Draw d = new Draw(), it wanted to match the new constructor with labels passed in or for a new constructor completely. This was my attempt but getting all sorts of errors at the moment.

Code:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;


public class Research {

	public static void main(String[] args) {
		
		JFrame f = new JFrame("Circuit");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Draw d = new Draw();
		f.add(d);
		f.setSize(700, 500);		
		f.setVisible(true);
		
		try
		{
			Scanner s = new Scanner(new File("C:\\Users\\Shicky\\Desktop\\sampleTestData.txt"));
			ArrayList<String> tokens = new ArrayList<String>();
			
			int z = 0;
						
			while(s.hasNext())
			{
				String str = s.nextLine();
				if( str.length() >0)
				{
					String[] p = str.split("\\s+");
					switch (str.charAt(0))
					{
						//case '*': System.out.println("ignore");
						case 'c': 
							z++; 
						    System.out.println(p[0]);
						    
						    break;
						case 'l':
							f.add(new Draw(p[7], p[8]));				    
						
					}	
					
				}
			}
			
			System.out.println(z);	
		
			s.close();
			
		}
		catch(Exception e)
		{
			
			System.out.println("Could not open file." );
			e.printStackTrace();
		}
		
	}

}

Code:
import javax.swing.*;
import java.awt.*;

public class Draw extends JPanel {
	
	private String _coord1;
	private String _coord2;
	
	public Draw(String coord1, String coord2){
		_coord1 = coord1;
		_coord2 = coord2;		
	}

	public Draw(){
		
	}

	public void paintComponent(Graphics g){
		super.paintComponent(g);
		this.setBackground(Color.WHITE);
		
		g.setColor(Color.GREEN);
		g.drawOval(Integer.parseInt(_coord1), Integer.parseInt(_coord2), 50, 50);
		
	}	
			
}

This cant possibly be as difficult as it seems to draw a circle! Properly stressing me out now

Program runs fine till it gets to the parseInt stage i think and then I get the following errors:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Draw.paintComponent(Draw.java:23)

The full length is rather long but very similar to that involving various paint stuff. Any ideas?
 
I think you might find that the error may be coming from the first
Draw d = new Draw()
line.
You are creating a new instance of the draw class but without the _coord1 values being set.
so when it calls it's own paintComponent it doesn't have anything to draw the oval with. _coord 1 and _coord2 are nothing so parseInt fails.

Either set _coord1 and _coord2 to 0 when they are declared or better yet skip the drawOval if it doesn't have values in either of the _coord variables.
 
Cheers for you efforts SimonCHere but it became a little muddled for me, found a solution using a Circlelist
 
You want everything in main, but at the same time want things kept tidy?

Does not compute :p

That's a bit of an oxymoron tbh :)
 
I wanted to 'call' everything from main just, as I have done, not have everything in the main class
 
You're doing a lot more than just calling in Main. You've got lots of logic in there (i.e. your for loops, many if statements, splits etc.)
 
Back
Top Bottom