# Best way to plot points on graph?

• (2 Pages)
• 1
• 2

## 15 Replies - 44959 Views - Last Post: 22 November 2010 - 10:59 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=200348&amp;s=a430a57fc9c3942ffc254c866635e298&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

# Best way to plot points on graph?

Posted 15 November 2010 - 10:31 PM

Hello, I was looking to see what would be the best way to make a window. On one side have a list of points(x,y cordinates), and on the other a actual graph of these with a line connecting them all. What would be the best way of graphing these points?
Is This A Good Question/Topic? 0

## Replies To: Best way to plot points on graph?

### #2 bcranger

• D.I.C Lover

Reputation: 253
• Posts: 1,199
• Joined: 01-February 10

## Re: Best way to plot points on graph?

Posted 15 November 2010 - 11:28 PM

You have several options:
-Create a series of points
-Use a Polyline
-Use a Line2D with Stroking
- Can also use BasicStroke API to fine tune the looks
-Also, there are several arc/curve classes in the java.awt.geom package

If you aren't worried about picture perfect quality, I'd say you should use a polyline or a series of loosely placed points to give you an outline of the graph. Using a line2D.Double with BasicStroke, rounded cap, and rounded joints will give you a really nice, smooth graph.

### #3 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 15 November 2010 - 11:36 PM

Here is my first try at simply drawing lines. Am I on the right track? How do I go about splitting the window into two distinct locations, is there a way to contain the graph of the lines in one section of gridlayout, and list in the other?

Also unsure exactly how to go about altering code to implement use of various user-inputed coordinates. Simple as adjusting drawline(x1,y1,x2,x2) all the way through and adjusting variables thereafter?

Any insight or input if my code is flawed is appreciated.

```import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.Graphics.*;

public class PaintExample
{
public static void main(String args[])
{
JFrame	f;
f=new PaintExampleFrame();
f.setVisible(true);
}

}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class PaintExampleFrame extends JFrame
{

PaintExampleFrame()
{
System.out.println("Yay");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Paint Attempts");
setSize(300,200);
setLocation(new Point(500,500));
setVisible(true);
setBackground(Color.black);

}

public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawLine(0,0,200,200);
g.setColor(Color.blue);
g.drawLine(200,200,70,133);
g.setColor(Color.orange);
g.drawLine(70,133,400,15);
}

}

```

### #4 bcranger

• D.I.C Lover

Reputation: 253
• Posts: 1,199
• Joined: 01-February 10

## Re: Best way to plot points on graph?

Posted 16 November 2010 - 04:43 PM

There are many ways to split the frame but I think JSplitPane may be a good bet.

You probably want to add two JPanels, 1 to the right and 1 to the left component of the splitpane. Then, you can override the paintComponent method on one JPanel to draw your graph.
- Prompt for an equation of the graph on the other side of the splitpane
- Take that equation and validate for equation format if you wish
- You might want to decode the equation into usable parts such as coefficients, exponents,operations, etc
- Store those meaningful parts into arrays
- Use a loop to go through to solve for the points
- Those points become the basis for your graphing
- Think about quality v. efficiency (more points == finer look but less efficient/more resource consuming)

### #5 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 17 November 2010 - 07:23 PM

Thanks, SplitPane was exactly what I was eyeing and managed to get it working. However, I'm still not finding anything on how to paint only the left splitPane. I'm just not that familiar with graphics models yet so I'm sure its right under my nose. Are there any noteable online resources for a greater understanding?

User input will be in form of a land call instead of an equation. Something like "N 45 25 W 15" , once they add it will display in list on right side. and plot point on left. I'm fairly sure I got my logic on point for converting it. I'm just not certain on the above.

This post has been edited by peepsrct: 17 November 2010 - 07:35 PM

### #6 bcranger

• D.I.C Lover

Reputation: 253
• Posts: 1,199
• Joined: 01-February 10

## Re: Best way to plot points on graph?

Posted 17 November 2010 - 09:11 PM

You want to add two JPanels, one to the right, one to the left component of the JSplitPane (it consists of two components).
Then you can override the paintcomponent method and do your drawing on one of the jpanels. The other is for you to organize your input fields, etc into.

### #7 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 17 November 2010 - 10:03 PM

Here is what I have so far. The first window info isn't linked to second page yet. Just put in some defaults to test it all out. When I click the button on left pane though, I want it to just color that window black for a canvas. Then draw a line to test it out.

When clicked it closes the left pane out leaving a blank window, with a working copy also open below it. Also, doesn't draw line at this time. Any help is appreciated. Thanks as always.

```import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.lang.*;
import javax.swing.event.*;
import java.awt.Graphics.*;
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
public class LandDeed
{
public static void main(String args[])
{
JFrame	f;
f=new LandDeedFrame();
f.setVisible(true);
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class LandDeedFrame extends JFrame implements ActionListener,DocumentListener
{
JPanel	mainPanel;
Container cp;
JSpinner	dirSpinner;
JSpinner	dir2Spinner;
JTextField	angleTo;
JTextField	minutesTo;
JTextField	remainingTo;
JButton		cancel;
JLabel		angleLabel;
JLabel		dirLabel;
JLabel		dir2Label;
JLabel		minutesLabel;
JLabel		remainingLabel;

JPanel jsp1 = new JPanel();
JPanel jsp2 = new JPanel();
LandDeedFrame()
{
String[]	cardDir={"N","NE","E","SE","S","SW","W","NW"};
SpinnerModel sm=new SpinnerListModel(cardDir);
dirSpinner = new JSpinner(sm);
dirLabel   = new JLabel("Inital Direction: ");

angleTo= new JTextField();
angleTo.setText("0");
angleLabel= new JLabel("Angle Degree: ");

minutesTo= new JTextField();
minutesTo.setText("0");
minutesLabel= new JLabel("Angle Degree: ");

dir2Spinner = new JSpinner(sm);
dir2Label   = new JLabel("Second Heading: ");

remainingTo= new JTextField();
remainingTo.setText("0");
remainingLabel= new JLabel("Remaining Distance: ");

JLabel blankLabel=new JLabel();

cancel=new JButton("Cancel");

mainPanel=new JPanel(new GridLayout(6,2));

cp=getContentPane();

setupMainFrame();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void setupMainFrame()
{
Toolkit tk;
Dimension   d;

tk = Toolkit.getDefaultToolkit();
d = tk.getScreenSize();
setSize(d.width/3, d.height/3);
setLocation(d.width/5,d.height/5);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Project #4 - Deed/Call");
setVisible(true);
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
public void actionPerformed(ActionEvent e)
{
{
showList();

}
if(e.getActionCommand().equals("PNT"))
{
repaint();
}
}
//=========================( ChangeListener Goodies )=======================
public void stateChanged(ChangeEvent ce)
{
validateFields();
}
//=========================( DocumentListeners Goodies )=======================
public void insertUpdate(DocumentEvent e)
{
validateFields();
}
public void removeUpdate(DocumentEvent e)
{
validateFields();
}
public void changedUpdate(DocumentEvent e)
{
;
}
public void validateFields()
{
try
{

int degrees;
int minutes;
int distance;

//	numDoors=Double.parseDouble(String.valueOf(doorSpinner.getValue()));
degrees=Integer.parseInt(angleTo.getText());
minutes=Integer.parseInt(minutesTo.getText());
distance=Integer.parseInt(remainingTo.getText());

System.out.println("Validated Fool");
}
catch(NumberFormatException eee)
{
System.out.print("Error Fool");
}
}
//=========================( Show List & Graph )===============================
public void showList()
{
Toolkit tk1;
Dimension   d1;
JFrame newFrame=new JFrame();
JButton graph = new JButton("j");

tk1 = Toolkit.getDefaultToolkit();
d1 = tk1.getScreenSize();

newFrame.setSize(d1.width/3, d1.height/3);
newFrame.setLocation(d1.width/10,d1.height/10);
newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
newFrame.setTitle("Project #4 - Deed/Call");
newFrame.setVisible(true);

graph.setActionCommand("PNT");
setTitle("Example of Split Pane");
setSize(300, 300);
setLocation(400,300);
String[] coordinates = { "X=0, Y=0", "X=0, Y=1", "X=0, Y=2", "X=0, Y=3", "X=1, Y=0", "X=1. Y=1",
"X=1,Y=2"};
JList list;
list = new JList(coordinates);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true, jsp1, jsp2);

splitPane.setOneTouchExpandable(true);

}
//=============================================================================
public void paintComponent(Graphics g) {
int x=100;
int y=100;
jsp1.setBackground(Color.BLACK);
g.setColor(Color.red);
g.drawLine(0,0,100,100);
}
}

```

This post has been edited by peepsrct: 17 November 2010 - 10:08 PM

### #8 bcranger

• D.I.C Lover

Reputation: 253
• Posts: 1,199
• Joined: 01-February 10

## Re: Best way to plot points on graph?

Posted 17 November 2010 - 10:28 PM

Make sure you are overriding the JPanel's paintComponent method, not the JFrame or splitpane. Also, you need a super call:
```public void paintComponent(Graphics g)
{
super.paintComponent(g);
}

```

Here's a sample code I whipped up so you can see how it works:
```import java.awt.*;
import javax.swing.*;

public class GraphicsDemo extends JFrame
{

public GraphicsDemo()
{
JSplitPane sp = new JSplitPane();
// not middle, just hasty setting
sp.setDividerLocation(200);

sp.setLeftComponent(new CirclePanel());
sp.setRightComponent(new JPanel());

setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("DEMO");
setVisible(true);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GraphicsDemo();
}
});
}

// inner class for demo, best not to use inner
private class CirclePanel extends JPanel
{
public CirclePanel()
{
setBackground(Color.BLACK);
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
// smoother look
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.fillOval(10,10,40,40);
}
}

}

```

Now, as you can see, you can draw to the left and input on the right or vice versa. That was mainly to show you how to do the paintcomponent part

Feel free to post after another stab at it!

### #9 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 17 November 2010 - 10:59 PM

Thanks again, that's exactly what I needed. Now I think only thing left for me is finishing up computation and writing constructors for Deed()

### #10 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 21 November 2010 - 05:00 PM

Hello again, I've found time to finish up a constructor for storing my deed. But I'm not sure how to get my Add button to save a copy of the input as a Call. Would i need to write a method inside my Call class below or, would it be a method within my LandDeed Class? Thanks.

```public class Call
{
public int orgMinutes;
public int orgDegrees;
public int secDistance;
public String orgDirection;
public String secDirection;

public Call()
{
orgDirection="N";
orgDegrees=0;
orgMinutes=0;
secDirection="N";
secDistance=0;
}
public Call(String angle2,int degrees2, int minutes2, String turn2, int distance , String comment)
{
orgDirection=angle2;
orgDegrees=degrees2;
orgMinutes=minutes2;
secDirection=turn2;
secDistance=distance;
}
public void displayCall()
{
System.out.println("OrigDir: "+orgDirection+" OrigDegreees: "+orgDegrees+" OrigMinutes: "+orgMinutes+" SecDirection :"+secDirection+"SecDistance: "+secDistance+" Comments: " + comments);
}
}
```

### #11 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12742
• Posts: 45,924
• Joined: 27-December 08

## Re: Best way to plot points on graph?

Posted 21 November 2010 - 06:34 PM

Perhaps you should store a Vector<Call> in your LandDeedFrame class, and each time the Add button is clicked, add a new Call object to the Vector. The reason I suggest a Vector over an ArrayList is b/c you can pass the Vector to the JList when you go to display the Calls.

### #12 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 21 November 2010 - 08:42 PM

I've yet to work with vectors, so In my first attempt I got the following errors. Is my location not right, or am I simply missing something.
```import java.util.Vector.*;

public static void main(String args[])
{
JFrame	f;
f=new LandDeedFrame();
f.setVisible(true);
Vector<Call> vc=new Vector<Call>();

}

```

And the errors...
```\LandDeed.java:18: cannot find symbol
symbol  : class Vector
location: class LandDeed
Vector<Call> vc=new Vector<Call>();
^
\LandDeed.java:18: cannot find symbol
symbol  : class Call
location: class LandDeed
Vector<Call> vc=new Vector<Call>();
^
\LandDeed.java:18: cannot find symbol
symbol  : class Vector
location: class LandDeed
Vector<Call> vc=new Vector<Call>();
^
\LandDeed.java:18: cannot find symbol
symbol  : class Call
location: class LandDeed
Vector<Call> vc=new Vector<Call>();
^
4 errors

Tool completed with exit code 1

```

Thanks as always for any help.

### #13 pbl

• There is nothing you can't do with a JTable

Reputation: 8381
• Posts: 31,956
• Joined: 06-March 08

## Re: Best way to plot points on graph?

Posted 21 November 2010 - 08:59 PM

You are talking and talking around for a trivial problem
The onlyest method I know to do that is

easy to use an ArrayList or a Vector as the array parameter

This post has been edited by pbl: 21 November 2010 - 09:00 PM

### #14 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 22 November 2010 - 03:19 PM

All errors above fixed, and graphics working fine. However, to add to the vector I tried adding a method like this
``` public void addCall()
{
myCall[numCalls].displayCall();
numCalls++;
System.out.println("Num Calls="+numCalls);

}

```

But I get can not find symbols errors for myCall, numCalls, and callVector. Is there a way around this, or am I making a simple scoping mistake?

### #15 peepsrct

Reputation: 11
• Posts: 151
• Joined: 29-March 09

## Re: Best way to plot points on graph?

Posted 22 November 2010 - 03:34 PM

peepsrct, on 22 November 2010 - 02:19 PM, said:

All errors above fixed, and graphics working fine. However, to add to the vector I tried adding a method like this
``` public void addCall()
{
myCall[numCalls].displayCall();
numCalls++;
System.out.println("Num Calls="+numCalls);

}

```

But I get can not find symbols errors for myCall, numCalls, and callVector. Is there a way around this, or am I making a simple scoping mistake?

Solved myself, Thanks again everyone.