我已经调用paintComponent方法后如何在JPanel中绘制内容 [英] How do I draw something in a JPanel after I already called the paintComponent method

查看:64
本文介绍了我已经调用paintComponent方法后如何在JPanel中绘制内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用Java制作GUI还是陌生的.据我了解,有一个名为Graphics的类,它负责在JPanel中绘制图形.当我的应用程序启动时,我调用paintComponent方法,该方法绘制了我正在编程的游戏的棋盘,paintComponent方法将Graphics g作为输入.但是,稍后,我想更新棋盘,那么当用户执行类似单击操作时,如何告诉游戏开始时绘制棋盘的同一个g绘制其他东西呢?

I'm new to making GUIs in Java. As I understand, there's a class called Graphics which is in charge of drawing shapes in a JPanel. When my application starts, I call the paintComponent method, which draws the board of the game I'm programming, and the paintComponent method takes a Graphics g as input. However, later on, I want to update the board, so how do I tell the same g that drew the board at the start of the game to draw something else when the user does something like clicking?

我相信这应该有一个非常简单的答案.

I believe this should have a very simple answer.

推荐答案

每个JComponent(Swing组件)都有一个 repaint()方法,只需调用它即可告诉 DrawingManager 重绘您的组件.

Every JComponent (Swing component) has a repaint() method, just call it to tell the DrawingManager to redraw your component.

您所有的绘制代码都应使用 paintComponent 方法,这意味着您不会在其他任何地方绘制任何东西(只能在调用 paintComponent 的流程中进行绘制,您当然可以使用方法来构造绘图代码.)

All your drawing code should be in paintComponent method, that means that you don't draw anything anywhere else (you draw only in the flow of invocation of paintComponent, you can have drawing code structured in methods of course).

此方法需要访问指示应该绘制什么和绘制位置的状态.这是因为OS可以请求重新绘制,然后仅调用 JComponent 中的绘制方法.

This method needs to have access to the state that indicates what and where should be drawn. It is because the OS could request repainting, and then only the painting methods from JComponent are called.

当您在 JComponent 上调用 repaint()时,然后在很短的时间内,您请求的组件的 paintComponent()方法重新绘制将由绘图线程调用,您应该仅在该绘图线程中进行绘制.

When you invoke repaint() on your JComponent, then in short time the paintComponent() method of the component on which you requested repainting will be called by the drawing thread, and you should draw only in this drawing thread.

这篇关于我已经调用paintComponent方法后如何在JPanel中绘制内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆