我正在做一个学校项目,我必须在 java 中创建一个人脸,我的应用程序的用户可以编辑它。每个面部特征应该有几个选项,所以我尝试做的第一个是眼睛。但是,当我尝试在 eyeComponent 类中与用户交互时遇到了麻烦。
它在 JVM 中打印用户颜色选项 (1-4),并打开一个空白 JFrame 窗口,但在 JVM 中,它不允许用户响应。打印出颜色选项后,程序就结束了,我不确定为什么它不允许用户响应。我在下面发布了 EyeComponent 和 PersonViewer 类的代码。
EyeComponent
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
import java.util.Scanner;
public class EyeComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Scanner in = new Scanner(System.in);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double head = new Ellipse2D.Double(5,20,100,150);
System.out.println("What color would you like the eyes to be?");
System.out.println("Select \n1:blue \n2:red \n3:yellow \n4:green");
int response = in.nextInt();
if (response == 1)
{ g2.setColor(Color.BLUE);}
else if (response == 2)
{ g2.setColor(Color.RED);}
else if (response == 3)
{ g2.setColor(Color.YELLOW);}
else if (response == 4)
{ g2.setColor(Color.GREEN);}
g2.draw(head);
}
}
PersonViewer
import javax.swing.*;
import java.util.Scanner;
public class personViewer //creates class called engine of scope public
{
public static void main (String [] args) //main method for engine class
{
JFrame frame = new JFrame();
frame.setSize(150, 250);
frame.setTitle("Face");
EyeComponent component = new EyeComponent();
frame.add(component);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}