Robert Hume Robert Hume - 1 year ago 87
Java Question

how to get the image of a Swing widget?

Possible Duplicate:

Java Swing : Obtain
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.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.setHeight(height); // or minHeight, or maxHeight, or preferredHeight, or whatever; swing is tricky ;)
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 Source

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(){

    public void paintComponent(Graphics 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");

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

    public static void main(String[] args){
     final JFrame frame = new JFrame();
     frame.add(new MainPanel());
     frame.setSize(400, 300);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download