java怎么设置背景_如何在Java中设置背景图片?
小編典典
根據應用程序或小程序是使用AWT還是Swing,答案會略有不同。
(基本上,以J諸如JApplet和JFrame為開頭的類是Swing和Appletand Frame是AWT。)
無論哪種情況,基本步驟都是:
將圖像繪制或加載到Image對象中。
在要繪制背景的繪畫事件中繪制背景圖像Component。
步驟1.
可以通過使用Toolkit類或通過ImageIO類來加載圖像。
該Toolkit.createImage方法可用于Image從中指定的位置加載String:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
同樣,ImageIO可以使用:
Image img = ImageIO.read(new File("background.jpg");
第2步。Component應該獲取背景的繪畫方法將被覆蓋,并將其繪畫Image到組件上。
對于AWT,要覆蓋的paint方法是方法,并使用傳遞給該方法drawImage的Graphics對象的paint方法:
public void paint(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
對于Swing,要覆蓋的paintComponent方法是的方法JComponent,并Image使用在AWT中所做的繪制。
public void paintComponent(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
簡單組件示例
這是一個Panel在實例化時加載圖像文件并在其自身上繪制圖像的:
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel()
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage("background.jpg");
}
public void paint(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
}
}
有關繪畫的更多信息:
2020-09-16
總結
以上是生活随笔為你收集整理的java怎么设置背景_如何在Java中设置背景图片?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux程序无法获取cpu资源,Lin
- 下一篇: 获取php.ini配置信息,获得php所