2012-08-15 29 views
1

可能重複:
Java Swing : Obtain Image of JFrame如何獲取Swing小部件的圖像?

我一個小拖和下降的Java GUI構建工作。它到目前爲止工作正常,但我拖放的小部件只是我在畫布上動態繪製的矩形。

如果我有一個矩形表示一個像JButton一樣的構件,有沒有辦法讓我創建一個JButton,設置它的大小並獲取該JButton的圖像,如果它在屏幕上繪製的話?然後,我可以將圖像繪製到屏幕上,而不僅僅是我無聊的矩形。

例如,我正在這樣做是爲了繪製(紅色)矩形:

public void paint(Graphics graphics) { 
    int x = 100; 
    int y = 100; 
    int height = 100; 
    int width = 150; 

    graphics.setColor(Color.red); 
    graphics.drawRect(x, y, height, width); 
} 

我怎麼可以這樣做:

public void paint(Graphics graphics) { 
    int x = 100; 
    int y = 100; 
    int height = 100; 
    int width = 150; 

    JButton btn = new JButton(); 
    btn.setLabel("btn1"); 
    btn.setHeight(height); // or minHeight, or maxHeight, or preferredHeight, or whatever; swing is tricky ;) 
    btn.setWidth(width); 
    Image image = // get the image of what the button will look like on screen at size of 'height' and 'width' 

    drawImage(image, x, y, imageObserver); 
} 
+0

我建議你直接在JPanel中拖動JButtons。 – 2012-08-15 14:17:12

+0

@AndrewThompson你說得對!這個問題的答案描述了我想要做的事情。謝謝! – 2012-08-15 14:37:29

+0

@丹感謝您的建議,但那不是我所需要的。 – 2012-08-15 14:37:50

回答

1

基本上,你繪製你的組件到圖像,然後在任何你想要的位置上繪製該圖像。在這種情況下,可以直接調用paint,因爲您不是在屏幕上繪畫(而是繪製到內存位置)。

如果您想優化您的代碼比我在這裏做的更多,您可以保存圖像,並在移動時將其重新繪製在其他位置(而不是每次重新繪製屏幕時從按鈕計算圖像)。

import java.awt.*; 
import java.awt.image.BufferedImage; 

import javax.swing.*; 

public class MainPanel extends Box{ 

    public MainPanel(){ 
     super(BoxLayout.Y_AXIS); 
    } 

    @Override 
    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 

     // Create image to paint button to 
     BufferedImage buttonImage = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB); 
     final Graphics g2d = buttonImage.getGraphics(); 

     // Create button and paint it to your image 
     JButton button = new JButton("Click Me"); 
     button.setSize(button.getPreferredSize()); 
     button.paint(g2d); 

     // Draw image in desired location 
     g.drawImage(buttonImage, 100, 100, null); 
    } 

    public static void main(String[] args){ 
    final JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(new MainPanel()); 
    frame.pack(); 
    frame.setSize(400, 300); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
    } 
} 
+0

'g.drawImage(buttonImage,100,100,null);'不需要'null'。 'Box'是一個'ImageObserver'。 – 2012-08-15 22:37:03