我想添加一個背景圖像到java awt帆布,但仍然無法通過。任何機構都可以爲這個或任何代碼解決這個問題。代碼如下,添加圖像到java awt帆布背景
謝謝。
import java.awt.*;
import java.applet.*;
import java.util.Vector;
import java.util.Enumeration;
public class DiagramEditor extends Canvas {
private Vector diagrams = new Vector(16);
Diagram currentDiagram;
DiagramEditorControls controls;
Tool tool;
Image offscreen;
public final static int RECTANGLE = 0;
public final static int SELECTION = 3;
public String toolNames[] = {"Rectangle", "", "", "Selection"};
public DiagramEditor() {
setBackground(Color.white);
newDiagram();
}
public void setControls(DiagramEditorControls c) {
controls = c;
}
public void setTool(int t) {
switch (t) {
case RECTANGLE:
tool = new WrectangleTool(currentDiagram);
break;
case SELECTION:
tool = new SelectionTool(currentDiagram);
break;
}
repaint();
if (controls != null) {
controls.toolChoice.select(t);
}
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
Dimension canvasSize = size();
if (offscreen == null) {
offscreen = this.createImage(canvasSize.width, canvasSize.height);
}
Graphics og = offscreen.getGraphics();
og.setColor(getBackground());
og.fillRect(0, 0, canvasSize.width, canvasSize.height);
og.setColor(Color.black);
og.drawRect(0, 0, canvasSize.width - 1, canvasSize.height - 1);
og.setColor(Color.blue);
currentDiagram.draw(og);
tool.draw(og);
g.drawImage(offscreen, 0, 0, this);
}
public void deleteElements() {
tool.delete();
repaint();
}
public void nextDiagram() {
if (currentDiagram == diagrams.lastElement()) {
currentDiagram = (Diagram) diagrams.firstElement();
} else {
int diagramIndex = diagrams.indexOf(currentDiagram);
currentDiagram = (Diagram) diagrams.elementAt(diagramIndex + 1);
}
setTool(RECTANGLE);
}
public void newDiagram() {
currentDiagram = new Diagram();
diagrams.addElement(currentDiagram);
setTool(RECTANGLE);
}
public boolean mouseDown(Event e, int x, int y) {
tool.press();
repaint();
return true;
}
public boolean mouseDrag(Event e, int x, int y) {
tool.move(new Point(x, y));
repaint();
return true;
}
public boolean mouseMove(Event e, int x, int y) {
tool.move(new Point(x, y));
repaint();
return true;
}
public boolean mouseUp(Event e, int x, int y) {
tool.release();
repaint();
return true;
}
}
這是一個繪圖畫布。默認背景顏色是白色的..我希望它被改變成圖像...?
你能提供一個不爲你工作的代碼? – brimble2010
1)'DiagramEditor擴展Canvas'呃......這是第3個千禧年。有時間遷移到使用Swing。部分原因是大多數人從未使用AWT,而我們其他人忘記了細節。還有其他很好的理由。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 (例如,這個例子需要一個'main(String [])'把它放在屏幕上。) –