简体   繁体   English

标记x和y轴java gui

[英]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. 我正在尝试使用Java GUI创建一个图形计算器,(是的,我知道有些应用程序已经这样做了。)我正在使用Graphics2D类,只是想知道如何标记x和y轴。

Here's what I've written so far, which will sketch a basic parabola and the x and y axis. 这是我到目前为止所写的内容,它将绘制基本的抛物线和x和y轴。 Also if anyone can tell me how to change it so the axis lines are thinner that would be amazing! 此外,如果有人能告诉我如何更改它,所以轴线更薄,这将是惊人的!

Thanks in advance! 提前致谢! -Evan -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;
            }
        }

You could use Graphics.drawString() to draw both axis: 您可以使用Graphics.drawString()来绘制两个轴:

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. 旋转Graphics2D以绘制Y轴。 Make sure to have this as the last set of statements in paintComponent to avoid having to re-rotate Graphics2D . 确保将此作为paintComponent最后一组语句,以避免重新旋转Graphics2D

You can get thinner lines using: 您可以使用以下方式获得更细的线条

g2.scale(2.0, 2.0);

See: Graphics2D.scale() 请参阅: Graphics2D.scale()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM