简体   繁体   English

如何在画布上绘制JPanel?

[英]How to draw a JPanel on a canvas?

is there a possibility to draw a JPanel on a specific location op a Graphics (or Graphics2D) object? 是否有可能在Graphics(或Graphics2D)对象的特定位置上绘制JPanel? I override the paint method of my canvas, and call panel.paint(g) in there, but it does not work the way I woul hope. 我重写了画布的paint方法,并在其中调用panel.paint(g),但是它无法实现我希望的方式。

@Override
public void paint(Graphics g){
  Dimension size = panel.getPreferredSize();
  panel.setBounds(pos.x, pos.y, size.width, size.height);
  panel.paint(g);
}

the size object is correctly defined as I would wish, so that's not the problem. 大小对象已按照我的要求正确定义,所以这不是问题。 Also, the pos contains a correct x and y on the screen. 另外,pos在屏幕上包含正确的x和y。

You should probably be using paintComponent instead of paint , since the latter is the AWT method, and the former is the Swing method. 您可能应该使用paintComponent而不是paint ,因为后者是AWT方法,而前者是Swing方法。

One nice thing about Swing's paintComponent is that the Graphics passed is actually always going to be a Graphics2D , so you can: 关于Swing的paintComponent一件好事是,传递的Graphics实际上总是将是Graphics2D ,因此您可以:

Graphics2D g = (Graphics2D)lg;

Now you can use the getTransform to save the old transform, then modify the transform of the Graphics2D using either setTranform or the scale , translate and rotate methods. 现在,您可以使用getTransform保存旧的变换,然后使用setTranformscaletranslaterotate方法修改Graphics2D的变换。 Don't forget to restore the old transform , or you'll likely fudge the next thing being drawn by that context. 别忘了还原旧的transform ,否则您可能会误解该上下文所绘制的下一件事。

I'll throw in that, depending on the circumstance, drawing to a BufferedImage might be appropriate. 我将视情况而定,将其绘制到BufferedImage可能是合适的。 You can get a Graphics context using BufferedImage.getGraphics(). 您可以使用BufferedImage.getGraphics()获得Graphics上下文。 Then you can draw the BufferedImage's context by whatever means suit you. 然后,您可以通过适合您的任何方式绘制BufferedImage的上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM