如何在JFrame的paint()函数之外绘制图形 [英] How to draw graphics outside of the paint() function in a JFrame
问题描述
我希望能够在 JFrame
上绘制 Image
s,但是只要我想要(不在 JFrame.paint
方法。
对于我正在开发的项目,我有一个 class Bullseye extends BufferedImage
,并试图将它放到 JFrame
:
class DrawingFrame extends JFrame {
public void drawImage(Image img,int x,int y){
getGraphics()。drawImage(img,x,y,null );
repaint();
}
}
class Main {
public static void main(String [] args){
DrawingFrame frame = new DrawingFrame();
Bullseye bullseye = new Bullseye(20,20); //宽度,高度
//稍后
frame.setVisible(true);
frame.drawImage(bullseye,10,20);
frame.drawImage(bullseye,20,20);
frame.drawImage(bullseye,30,20);
}
}
然而, ws up。经过一番研究,显然这是行不通的,因为当我 repaint()
时,
我该怎么做?这甚至是正确的方法吗?
在Java中绘制屏幕(几乎)总是在paint()中完成。你需要的类是:
class DrawingFrame extends JFrame {
private Image bullseye = new牛眼(20,20); //宽度,高度
public void paint(Graphics g){
g.drawImage(bullseye,10,20);
g.drawImage(bullseye,20,20);
g.drawImage(bullseye,30,20);
$ b class Main {
public static void main(String [] args){
DrawingFrame frame = new DrawingFrame( );
//稍后
frame.setVisible(true);
$ b如果你需要开启bullseyes的绘图在特定的时间,在DrawingFrame对象上创建一个标志,并在需要时设置它。您需要在设置标志时调用repaint()。
I would like to be able to paint Image
s onto a JFrame
, but whenever I want (not in the JFrame.paint
method.
For the project I am working on, I have a class Bullseye extends BufferedImage
, and am trying to put it onto a JFrame
:
class DrawingFrame extends JFrame {
public void drawImage(Image img, int x, int y) {
getGraphics().drawImage(img,x,y,null);
repaint();
}
}
class Main {
public static void main(String[] args) {
DrawingFrame frame = new DrawingFrame();
Bullseye bullseye = new Bullseye(20,20); //width,height
// later
frame.setVisible(true);
frame.drawImage(bullseye,10,20);
frame.drawImage(bullseye,20,20);
frame.drawImage(bullseye,30,20);
}
}
However, nothing shows up. After some research, apparently this doesn't work because the changes to the graphics
object get cleared when I repaint()
.
How can I do this? Is this even the right approach?
解决方案 Drawing to the screen in Java is (almost) always done in paint(). What you need for your class is:
class DrawingFrame extends JFrame {
private Image bullseye = new Bullseye(20,20); //width,height
public void paint(Graphics g) {
g.drawImage(bullseye,10,20);
g.drawImage(bullseye,20,20);
g.drawImage(bullseye,30,20);
}
}
class Main {
public static void main(String[] args) {
DrawingFrame frame = new DrawingFrame();
// later
frame.setVisible(true);
}
}
If you need to turn on the drawing of bullseyes at a specific time, create a flag on the DrawingFrame object, and set it when you need them. You will need to call repaint() when the flag is set.
这篇关于如何在JFrame的paint()函数之外绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!