Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labeling x and y axis java gui

first time poster so bear with me.

I'm trying to create a graphing calculator using Java GUI, (yes I know there are applications that do this already.) I'm using the Graphics2D class and just wondering how I can label the x and y axis.

Here's what I've written so far, which will sketch a basic parabola and the x and y axis. Also if anyone can tell me how to change it so the axis lines are thinner that would be amazing!

Thanks in advance! -Evan

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GraphWindow extends JPanel {

    /**
     * @param args
     */
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        double max=16;
        double min=0;
        double x[]= {-4,-3,-2,-1,0,1,2,3,4};
        double y[]={16,9,4,1,0,1,4,9,16};

        Graphics2D g2=(Graphics2D)g;
        setBackground(Color.WHITE);
        g2.translate(getWidth()/2,getHeight()/2);
        g2.scale(5.0, 5.0);
        g2.draw( new Line2D.Double(-4*100,0,4*100,0));
        g2.draw( new Line2D.Double(0,min*100,0,-max*100));
        for(int i=0;i<x.length;i++){
            if(i+1<x.length){
            g2.setColor(Color.RED);
            g2.draw(new Line2D.Double(x[i], -y[i], x[i+1], -y[i+1]));
            }
            else{
                break;
            }
        }
like image 611
Evan Hirtenfeld Avatar asked Jan 16 '26 20:01

Evan Hirtenfeld


1 Answers

You could use Graphics.drawString() to draw both axis:

g.setColor(Color.black);
g.setFont(new Font("SansSerif", Font.BOLD, 8));

g.drawString("X Axis", 30, 10);

// rotate for Y axis
g2.rotate(-Math.PI/2);
g.drawString("Y Axis", 20, -8);

The Graphics2D is rotated for drawing the Y axis. Make sure to have this as the last set of statements in paintComponent to avoid having to re-rotate Graphics2D.

You can get thinner lines using:

g2.scale(2.0, 2.0);

See: Graphics2D.scale()

like image 170
Reimeus Avatar answered Jan 19 '26 19:01

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!