I have 3 different functions superimposed on each other and I'm trying to add radio buttons so that when button1 is selected, the function associated with it will draw, and the others will be invisible. If there is a better way to do this, I'll do that.
import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.*;
public class DrawingStuff extends JComponent {
DrawingStuff(){
JRadioButton line1 = new JRadioButton("F(x)");
JRadioButton line2 = new JRadioButton("G(x)");
JRadioButton line3 = new JRadioButton("Cos(2x)");
ButtonGroup bG = new ButtonGroup();
bG.add(line1);
bG.add(line2);
bG.add(line3);
this.setLayout( new FlowLayout());
this.add(line1);
this.add(line2);
this.add(line3);
line1.setSelected(true);
this.setVisible(true);
}
public void paintComponent(Graphics g)
{
//w is x, and h is y (as in x/y values in a graph)
int w = this.getWidth()/2;
int h = this.getHeight()/2;
Graphics2D g1 = (Graphics2D) g;
g1.setStroke(new BasicStroke(2));
g1.setColor(Color.black);
g1.drawLine(0,h,w*2,h);
g1.drawLine(w,0,w,h*2);
g1.drawString("0", w - 7, h + 13);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2));
g2.setColor(Color.red);
int scale = 4;
//Path2D path1 = new Path2D.Double();
//path1.moveTo(w, h);
Polygon p = new Polygon();
for (int x = 0; x <= 4; x++) {
//path1.lineTo(w+scale*x, h - scale*((x*x*x) + x - 3));
p.addPoint(w+scale*x, h - scale*((x*x*x) + x - 3));
}
//g2.draw(path1);
g2.drawPolyline(p.xpoints, p.ypoints, p.npoints);
Polygon p1 = new Polygon();
//Path2D path2 = new Path2D.Double();
//path2.moveTo(w, h);
for (int x = -10; x <= 10; x++) {
//path2.lineTo(w+scale*x, h - scale * ((x*x*x)/100) - x + 10);
p1.addPoint(w + scale * x, h - scale * ((x*x*x)/100) - x + 10);
}
//g2.draw(path2);
g2.drawPolyline(p1.xpoints, p1.ypoints, p1.npoints);
Path2D path = new Path2D.Double();
for (int i = 0; i < 100; i++) {
double theta = i * 2 * Math.PI / 100;
double r = Math.cos(2 * theta);
double dX = w * r * Math.cos(theta) + w;
double dY = h * r * Math.sin(theta) + h;
if (i == 0) {
path.moveTo(dX, dY);
} else {
path.lineTo(dX, dY);
}
}
path.closePath();
g2.draw(path);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setTitle("Graphs");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
DrawingStuff draw = new DrawingStuff();
frame.add(draw);
frame.setVisible(true);
}
}
I'm not sure how to call the buttons from the constructor, and when I attempted to set a function aside for the buttons, they would replicate whenever I would maximize or restore down the window.
I also don't know how to erase a a line once plotted.
Thanks.