java - java - 如何在java中仅使用一种方法检测按键?
问题描述
我正在尝试绘制 6 种颜色、10 种形状、一个 jpeg 图像和 3 个在 java 中按下一个键时会发生变化的东西。
但是,我正在尝试用一种方法对所有这些进行编程。除了检测按键之外,我已经完成了其他所有操作。我看过很多例子,但它们都使用不同的方法或类来共同检测按键。但是我该如何检测按键并同时通过一种方法更改 JPanel 中的图片/图像。
我试图编写一些代码,但它不起作用(JPanel/屏幕上没有显示任何内容)这是我的代码到目前为止:
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, 1000, 1000);
BufferedImage photo = null;
try
{
File file = new File("holiday.jfif");
photo = ImageIO.read(file);
}
catch (IOException e)
{
g.drawString("Problem reading the file", 100, 100);
}
g.drawImage(photo,0,0,800,800,null);
g.setColor(Color.BLACK);
g.fillRect(120,300,100,100 );
g.setColor(Color.GREEN);
g.fillOval(270,130,50,100 );
g.setColor(Color.BLUE );
g.fillRect(350,200,100,150 );
g.setColor(Color.PINK);
g.fillOval(460, 270, 50, 50);
g.setColor(Color.GRAY);
g.fillArc(500, 300, 110, 100, 5, 150);
g.setColor(Color.YELLOW);
g.fillRect(500,450,100,100);
g.setColor(Color.YELLOW);
g.fillOval(550,500,100,100);
int[] xpoints = {50,150,20,180};
int[] ypoints = {500,500,550,550};
g.setColor(Color.BLACK);
g.drawPolygon(xpoints,ypoints,4);
int[] xpoint = {250,220,380,350};
int[] ypoint = {500,550,550,500};
g.drawPolygon(xpoint,ypoint,4);
int[] x = {600,500,700};
int[] y = {20,100,100};
g.drawPolygon(x,y,3);
g.setColor(Color.ORANGE);
g.fillRect(10,50,220,30);
g.fillRect(115,80,20,100);
Scanner input = new Scanner(System.in);
String press;
boolean stop = false;
while(!stop)
{
//Scanner input = new Scanner(System.in);
press = input.next();
if (press != null)
{
g.clearRect(115,80,20,100);
g.clearRect(500,450,100,100);
stop = true;
}
}
}
解决方案
推荐阅读
- ssh - 从客户端浏览器通过 SSH 连接到服务器,无需中间人服务器
- javascript - 如何在 JavaScript 中显示编号从 1 到 40 的数组的 40 项?
- sql-server - 如何使 VB.NET 代码从 SQL Server 表中检索单行的速度与 VB6 一样快
- python - 使用 tensorflow 计算高斯的拉普拉斯算子
- c# - URL 重写选项:如何排除文件和目录?
- node.js - NodeJS 和 Express:Express 路由器没有调用正确的路由
- python - 从以队列为参数的线程开始进程
- docker - 更改 Visual Studio Code 远程容器中的默认源代码目录
- php - 对于价格低于一定金额的产品,在 Woocommerce 购物车中隐藏价格
- php - 如何手动安装 PHP 项目的依赖项?