[英]How to draw a JPanel on a canvas?
是否有可能在Graphics(或Graphics2D)對象的特定位置上繪制JPanel? 我重寫了畫布的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);
}
大小對象已按照我的要求正確定義,所以這不是問題。 另外,pos在屏幕上包含正確的x和y。
您可能應該使用paintComponent
而不是paint
,因為后者是AWT方法,而前者是Swing方法。
關於Swing的paintComponent
一件好事是,傳遞的Graphics
實際上總是將是Graphics2D
,因此您可以:
Graphics2D g = (Graphics2D)lg;
現在,您可以使用getTransform
保存舊的變換,然后使用setTranform
或scale
, translate
和rotate
方法修改Graphics2D
的變換。 別忘了還原舊的transform ,否則您可能會誤解該上下文所繪制的下一件事。
我將視情況而定,將其繪制到BufferedImage可能是合適的。 您可以使用BufferedImage.getGraphics()獲得Graphics上下文。 然后,您可以通過適合您的任何方式繪制BufferedImage的上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.