我一個小拖和下降的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);
}
我建議你直接在JPanel中拖動JButtons。 – 2012-08-15 14:17:12
@AndrewThompson你說得對!這個問題的答案描述了我想要做的事情。謝謝! – 2012-08-15 14:37:29
@丹感謝您的建議,但那不是我所需要的。 – 2012-08-15 14:37:50