Java Graphics g2

时间:2018-02-20 06:08:25

标签: java

我正在尝试创建一个程序,询问用户他们想要出现哪种形状,然后根据该输入,它将询问形状的尺寸,然后在窗口中显示。我现在正在处理第一个形状,这是正方形,但我似乎无法让它出现在窗口中。我正在发布我在广场上的课程和我的主要方法。

import java.util.Scanner;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Frame;
import java.awt.Rectangle;

public class Square extends JComponent{

    private static int length; 

    public double getArea() {   
    return length * length;
    }
    public int getPerimeter() {
        return length * 4;
    }
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Rectangle square = new Rectangle(100,100,length,length);
        g2.draw(square);


    }
}
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Scanner;
import javax.swing.JFrame;


public class Main {

    static int input;
    static int length;

    public static void main(String[] args) {

        Scanner sc1 = new Scanner(System.in);
        while(true) {
            System.out.print("Which shape do you want?\n1 for square\n2 for restangle\n3 for triangle\n4 for circle\n5 to exit");
            input = sc1.nextInt();
            if(input == (5)) {
                break;
            }
            if(input == (1)) {


                System.out.print("Input the length:");
                length = sc1.nextInt();
                Square mySquare = new Square();
                mySquare.getPerimeter();





                JFrame frame = new JFrame();

                frame.setSize(300,400);
                frame.setTitle("ShapeViewer");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                frame.add(mySquare);
                frame.setVisible(true);

            }


        }
    }
}

我也试过把g2.draw放在主要部分,但它不会识别g2我不断收到错误。

2 个答案:

答案 0 :(得分:0)

你需要改变你的Square类。你没有开始它的长度。所以它默认为0因此你看不到你的方块。同时使它不是静态的,因为每个方格应该是不同的。

我添加了一个接受并设置长度的构造函数

public class Square extends JComponent{

        private int length; 

        public Square(int length) {
            this.length = length;
        }
        public double getArea() {   
        return length * length;
        }
        public int getPerimeter() {
            return length * 4;
        }
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            Rectangle square = new Rectangle(100,100,length,length);
            g2.draw(square);


        }
    }

答案 1 :(得分:0)

据我所见,Square.length始终为零。顺便说一句,为什么它是静态的?