我正在用Java實現一個顯示API。加載在一個單一的圖像的作品,但只要我想添加另一個第一個圖像消失,只繪製第二個。有想法該怎麼解決這個嗎?Swing只繪製兩個JPanel中的一個?
主類:
package com.lespaul.display;
import java.awt.Graphics;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Window extends JFrame {
private static final long serialVersionUID = 3716315131567381715L;
public Window() {
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(200, 200);
this.setVisible(true);
Image pane = new Image("floor.png");
Image pane2 = new Image("floor.png");
this.add(pane);
this.add(pane2);
pane2.setPosition(50,50);
this.revalidate();
}
public static void main(String[] args){
Window window = new Window();
}
}
這是實際的圖像...
package com.lespaul.display;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.io.IOException;
import java.net.URL;
import com.lespaul.position.*;
public class Image extends JPanel {
private static final long serialVersionUID = -5815516814733234713L;
public BufferedImage image;
public Vector2 position = new Vector2(0, 0);
public Image() {
}
public Image(String ref){
try {
this.addImage(ref);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setPosition(int x, int y){
Dimension size = this.getPreferredSize();
Insets insets = this.getInsets();
this.setBounds(x+insets.left,y+insets.top,size.width,size.height);
this.position.x = x;
this.position.y = y;
repaint();
}
public void addImage(String fileName) throws IOException {
URL url = this.getClass().getClassLoader().getResource(fileName);
image = ImageIO.read(url);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image,(int)position.x,(int)position.y, null);
}
}
1)爲了更好地提供幫助,請發佈[MCVE](http://stackoverflow.com/help/mcve)(最小完整和可驗證示例)。 2)獲取圖像的一種方法是通過熱鏈接到[本答案](http://stackoverflow.com/a/19209651/418556)中看到的圖像。 –
*「我需要它處於絕對位置」*絕對在哪裏? Java GUI可能需要在多種平臺上工作,使用不同的屏幕分辨率和使用不同的PLAF。因此,它們不利於組件的準確放置。爲了組織強大的圖形用戶界面,請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[空格]的佈局填充和邊框(http: //stackoverflow.com/q/17874717/418556)。 –