Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey, Im sort of a beginner of java, and i at the moment of working on a program that takes the input of an equation (eg. y=3x) and plots possible values for it on a cartesian plane thats on a seperate JPanel.

Here is my code: This is Class 1

Java
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Graphs extends JFrame implements KeyListener
{
    GraphingPanel p = new GraphingPanel();
    JPanel[] Panel = new JPanel[2];
    JLabel[] Label = new JLabel[100];
    JTextField[] Field = new JTextField[100];
    JButton[] Enter = new JButton[100];
    JButton[] Clear = new JButton[100];
    JComboBox Subjects = new JComboBox();
    JComboBox Topics = new JComboBox();

    public Graphs()
    {
        super();
        setSize(600, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setUndecorated(true);
        setLocationRelativeTo(null);
        LoadUI();
    }

    public void LoadUI()
    {
        Field[0] = new JTextField();
        Panel[0] = new JPanel(null);
        Panel[1] = p;


        Field[0].setBounds(240, 20, 120, 30);
        Field[0].addKeyListener(this);

        Panel[0].add(Field[0]);
        Panel[0].add(Panel[1]);
        add(Panel[0]);
        setVisible(true);
    }

    public static void main(String[] args)
    {
        Graphs Main = new Graphs();
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        if(e.getKeyCode()==10)
        {
            String str = Field[0].getText();
            DrawGraph g = new DrawGraph(str);
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
}


The Second Class:

Java
import java.awt.*;
import java.awt.geom.*;

import javax.swing.*;

public class GraphingPanel extends JPanel
{
    public GraphingPanel()
    {
        setBounds(50, 50, 500, 400);
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        setBackground(Color.WHITE);
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponents(g);

        int panelWidth = getWidth();
        int panelHeight = getHeight();

        g.setColor(Color.WHITE);
        g.fillRect(0, 0, panelWidth, panelHeight);
        g.setColor(Color.BLACK);

        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(1f));


        g2.draw(new Line2D.Double( 0, panelHeight/2, panelWidth ,panelHeight/2 ));
        g2.draw(new Line2D.Double(panelWidth/2,0, panelWidth/2 ,panelHeight));
        g2.setFont(new Font("Times New Roman", Font.PLAIN, 13));

        for(int i=1;i<getWidth();i+=9)
        {
            g2.draw(new Line2D.Double(i, (getHeight()/2)-2, i, (getHeight()/2)+2));
        }

        for(int i=1;i<getHeight();i+=9)
        {
            g2.draw(new Line2D.Double((getWidth()/2)-2, i,(getWidth()/2)+2,i));
        }
    }
}


Im just struggling to figure out how to plot a line graph after the user has input his equation into the Text field.. Your help will be greatly appreciated:)
Posted

1 solution

some general:

Java
GraphingPanel p = new GraphingPanel();
    JPanel[] Panel = new JPanel[2];
    JLabel[] Label = new JLabel[100];
    JTextField[] Field = new JTextField[100];
    JButton[] Enter = new JButton[100];
    JButton[] Clear = new JButton[100];
    JComboBox Subjects = new JComboBox();
    JComboBox Topics = new JComboBox();


why do you declare such big fields of components??
Please name them variables starting with lower case, otherwise you will get in trouble with object names.

To your question:
You need to repaint() your JPanel.

EDIT:
Java
// Let's start with instances of what we really need:
// I'm using hungarian notation, which is one way to get a clear variable naming. 
// the "o" in front stands for "Object".
 
// by the way: this is a comment, you should use some to make clear what you do.
    GraphingPanel oGraphPanel = new GraphingPanel();
    JPanel oPanel = new JPanel();
    JLabel oLabel = new JLabel();
    JTextField oField = new JTextField();
    JButton oEnter = new JButton();
    JButton oClear = new JButton();
    JComboBox oSubjects = new JComboBox();
    JComboBox oTopics = new JComboBox();


/*
 * Ok, we've got our Components ready and now 
 * you should change your code to fit to this.
 */

// {YOUR CODE of class Graphs }

// to make it easier, I will add a methode for updating the GraphingPanel:
private void updateGraphPanel(){ // always make sure the component is there and initalized
    if(null != oGraphPanel){
        oGraphPanel.setText(oField.getText()); // passing the text from Graphs to GraphingPanel
        oGraphPanel.repaint(); // this triggers the paint method of GraphinPanel to be carried out again
    }
}


Java
// GraphingPanel
public class GraphingPanel extends JPanel
{
    private String strText=null; // init with null (=not valid)

    public void setText(String strText){
        this.strText = strText;
    }

// {Your code of GraphingPanel}


}



That's about all. the Text is passed to GraphingPanel and then the repaint is triggered.
The text is not yet used there - depends on what you want to do with it. But it's available - so have fun.

-----------------------------------------------------------------------------

EDIT2:
Here is a jump start. compare this to your code (eclipse: right click in Package Explorer -> Compare with...each other).


Java
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
 
public class GraphingPanel extends JPanel
{
    public GraphingPanel()
    {
        setBounds(50, 50, 500, 400);
        setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
        setBackground(Color.WHITE);
    }
 
    @Override
	public void paintComponent(Graphics g)
    {
        super.paintComponents(g);
 
        int panelWidth = getWidth();
        int panelHeight = getHeight();
 
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, panelWidth, panelHeight);
        g.setColor(Color.BLACK);
 
        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(1f));
 

        g2.draw(new Line2D.Double( 0, panelHeight/2, panelWidth ,panelHeight/2 ));
        g2.draw(new Line2D.Double(panelWidth/2,0, panelWidth/2 ,panelHeight));
        g2.setFont(new Font("Times New Roman", Font.PLAIN, 13));
 
        for(int i=1;i<getWidth();i+=9)
        {
            g2.draw(new Line2D.Double(i, (getHeight()/2)-2, i, (getHeight()/2)+2));
        }
 
        for(int i=1;i<getHeight();i+=9)
        {
            g2.draw(new Line2D.Double((getWidth()/2)-2, i,(getWidth()/2)+2,i));
        }
    }

	public void setValue(int iValue) {
		// dosomethingFancyWiththisValue(iValue);
		this.repaint();
		System.out.println("repainted");
	}
}


Java
public class Graphs extends JFrame
{
    // renaming variables
    private GraphingPanel oGraphPanel = new GraphingPanel();
    private JPanel oPanel = new JPanel();
    private JLabel oLabel = new JLabel();
    private JTextField oField = new JTextField();
    private JButton oEnter = new JButton();
    private JButton oClear = new JButton();
    private JComboBox oSubjects = new JComboBox();
    private JComboBox oTopics = new JComboBox();
 
    public Graphs()
    {
        super();
        setSize(600, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
//        setUndecorated(true); 
        setLocationRelativeTo(null);
        loadUI();
    }
 
    public void loadUI()
    {
        oField = new JTextField();
        oPanel = new JPanel(null);
 

        oField.setBounds(240, 20, 120, 30);
        oField.addKeyListener(new KeyAdapter(){
        	 @Override
        	    public void keyPressed(KeyEvent e)
        	    {// always try to work with constant values - it's safer!
        	        if(e.getKeyCode()==KeyEvent.VK_ENTER) 
        	        {
        	        	String strValue = oField.getText();
        	        	System.out.println("Enter pressed. Value: " + strValue);
        	        	//You probably want numbers entered in the TextBox - so you should check for the entered Value to be a number:
        	        	validateIsNumber(strValue);
        	        	oGraphPanel.setValue(Integer.parseInt(strValue));
//        	            DrawGraph g = new DrawGraph(oField.getText());
        	        }
        	    }

        }
        		); 
 
        oPanel.add(oField);
        oPanel.add(oGraphPanel);
        add(oPanel);
        setVisible(true);
    }
    
    private void validateIsNumber(String strValue) {
    	try{
    		Integer.parseInt(strValue); // just trying to parse the number, exception pops when not possible
    	} catch(Exception oException){
    		 JOptionPane.showMessageDialog(this, oException.getLocalizedMessage(),
                    "oooops", JOptionPane.ERROR_MESSAGE);
    	}
	}
    
 
    public static void main(String[] args)
    {
        new Graphs();
    }
 
   
}
 
Share this answer
 
v3
Comments
Umar2 9-Aug-12 3:28am    
Thanks for the advice
TorstenH. 9-Aug-12 4:25am    
did it work out? mark it green if so ("accept answer"), tell us what's on otherwise.
Umar2 9-Aug-12 4:35am    
Im not exactly a programmer, its more of a hobby, so could you walk me through as to what i must do
TorstenH. 9-Aug-12 6:42am    
developer - you should try to become developer.

I added some, check it out and add it to your code.
Umar2 9-Aug-12 7:39am    
Then do I just add the new statements in the paint() method after it called repaint() from the updateGraphPanel() method?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900