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
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:
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:)