Robert Hume Robert Hume - 5 months ago 21
Java Question

how to get the image of a Swing widget?


Possible Duplicate:

Java Swing : Obtain
Image
of JFrame





I am working on a little drag-and-drop Java GUI builder. It works so far, but the widgets I'm dragging and dropping are just rectangles I'm dynamically drawing on a canvas.

If I have a rectangle that represents a widget like a JButton, is there a way for me to create a JButton, set the size and get the image of that JButton if it was drawn on the screen? Then I could paint the image to the screen instead of just my boring rectangle.

For example, I'm currently doing this to draw a (red) rectangle:

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);
}


How can I do something like:

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);
}

Answer

Basically, you'll paint your component to an image, and then paint that image wherever you want. In this case it's okay to call paint directly because you're not painting to the screen (but to a memory location).

If you wanted to optimize your code more than I've done here, you can save the image, and just repaint it in a different location whenever it's moved (instead of calculating the image from the button every time the screen repaints).

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);
    }
}