1

重複の可能性:
Java Swing:ImageJFrameの取得

私は小さなドラッグアンドドロップのJavaGUIビルダーに取り組んでいます。これまでのところ機能しますが、ドラッグアンドドロップするウィジェットは、キャンバス上に動的に描画している単なる長方形です。

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

1 に答える 1

0

基本的に、コンポーネントを画像にペイントしてから、その画像を好きな場所にペイントします。この場合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);
    }
}
于 2012-08-15T15:18:27.173 に答える