2015-02-24 67 views
0

我是Java初學者,Java在彼此上顯示圖像並將其移動到

而且我必須構建一個程序來在海上移動一條船。

我的想法是插入一個圖像作爲背景屏幕,然後把另一個圖像,代表船。

我不知道如何做到這一點。

如何可以把圖像上的所有的JFrame作爲背景圖像, 我怎麼可以把對另一圖像,以及如何移動第二圖像這樣的背景

感謝。

+2

您可以使用背景面板類[閱讀本(https://tips4java.wordpress.com/2008/10/12/background-panel/) – 2015-02-24 14:14:05

回答

3

如何可以把圖像上的所有的JFrame作爲背景圖像,...

避免在以下方面思考JFrame,而你的Swing GUI工作應該集中在創建和使用JPanels。然後可以在JFrame(或JDialog或其他JPanel或...)中顯示它。通過在JPanel的paintComponent(Graphics g)方法內調用g.drawImage(myImage, 0, 0, null),可以輕鬆地在JPanel中顯示背景圖像。

,我怎麼可以把對另一圖像,我怎麼可以移動這樣的背景

  1. 簡單地使用在同一paintComponent(Graphics g)方法中繪製的第二BufferedImage的第二圖像,但後繪製第一張圖片。您將使用相同的g.drawImage(mySprite, x, y, null),但會使用字段(這裏是x和y)來更改精靈圖像的位置。通常情況下,更改發生在Swing Timer中。
  2. 或者您可以在JLabel中顯示的ImageIcon中顯示精靈圖像,並將JLabel的位置移動到擺動定時器中。

編輯你問:

我怎麼能調整圖片大小,因爲當我將其插入它把所有的框架?

它可能是最好創建一個新的BufferedImage,一個你想要的大小,得到新的圖像Graphics對象,繪製原畫成使用新的一個圖形對象和drawImage(...)重載允許重新調整大小,然後處理Graphics對象。例如

double scale = 0.5; // make it half as wide and high as big image 
    int smallImageWidth = (int) (bigImage.getWidth() * scale); 
    int smallImageHeight = (int) (bigImage.getHeight() * scale); 

    BufferedImage smallImage = new BufferedImage(smallImageWidth, smallImageHeight, BufferedImage.TYPE_INT_ARGB); 
    // get a Graphics object from this image 
    Graphics g = smallImage.getGraphics(); 

    // draw in the large image, scaling it 
    g.drawImage(bigImage, 0, 0, smallImageWidth, smallImageHeight, null); 

    // get rid of the Graphics object to save resources 
    g.dispose(); // never do this with Graphics objects given you by the JVM 
+0

謝謝,我會嘗試它,如果我成功,我驗證你的答案謝謝, – shmoolki 2015-02-24 14:41:07

+0

我如何調整圖片,因爲當我插入它採取所有的框架? – shmoolki 2015-02-24 16:32:37

+0

@shmoolki:查看編輯 – 2015-02-24 17:18:45

1

你可以使用Draggable,使你的船拖動

Image background = ...; 
Image boat = ...; 
JPanel bgPanel = new JPanel() { 
    public void paintComponent(Graphics g) { 
    g.drawImage(background,0,0,null); 
    } 
} 
JLabel boatLbl = new JLabel(new ImageIcon(boat)); 
bgPanel.setLayout(null); 
new Draggable(boatLbl); 
bgPanel.add(boatLbl); 
+0

您應該指出,可拖動的是一個第三方類,而不是Java類。 – 2015-02-24 17:25:35

相關問題