我在第二屆計算機工程專業。如何添加緩衝的圖像作爲JFrame的背景,然後在此圖像上添加面板?
我的問題是如何添加JButton等...在背景圖片上,你知道我寫了下面的代碼,請幫我繼續: 正如我所說我的JBotton不能顯示在圖像上,這是問題。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MyCalcFrame extends JFrame
{
private BufferedImage myImage;
private JPanel mypanel;
private JButton mybtn;
public MyCalcFrame()
{
this.setBounds(410, 110, 600, 450);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setAlwaysOnTop(true);
try
{
this.myImage=ImageIO.read(new File("D:\\1.jpg"));
}//end try
catch(IOException e)
{
JOptionPane.showMessageDialog(null, "Image dose not exist.","NO Image found",JOptionPane.ERROR_MESSAGE);
}//end catch
this.mypanel=new JPanel();
this.mypanel.setBackground(Color.black);
this.setContentPane(new ImagePanel(myImage));
mybtn=new JButton("hello");
this.getContentPane().add(mybtn);
this.setVisible(true);
}//end MyCalcFrame constructor
class ImagePanel extends JComponent
{
private Image image;
public ImagePanel(Image image)
{
this.image = image;
}//end constructor
@Override
protected void paintComponent(Graphics g)
{
g.drawImage(image, 0, 0, null);
}//en paintComponent
}//end ImagePanel
//################ End constructor ########################
//public void paint(Graphics g)
//{
// g.drawImage(myImage, 0, 0, this);
//}//end method paint
//@@@@@@@@@@@@@@@@@@@@@@@@ main @@@@@@@@@@@@@@@@@@@@@@@@@@@@
public static void main(String[] args)
{
//JFrame.setDefaultLookAndFeelDecorated(true);
new MyCalcFrame();
}//end method main
//@@@@@@@@@@@@@@@@@@@@@@@@ main @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
}//end class MyCalcFrame
執行此操作的一種簡單方法是將帶有'LayoutManager'的'JLabel'作爲JFrame的內容窗格。檢查這[與自定義組件]答案(http://stackoverflow.com/questions/13401109/java-add-background-image-to-frame/13401871#13401871)和[這個答案與'JLabel'](http :/ /stackoverflow.com/questions/16288303/best-example-for-creating-programmatically-splashscreen-with-text/16289376#16289376) – 2013-05-06 10:25:58