Java 如何添加缓冲图像作为JFrame的背景,然后在此图像上添加面板?
我在上计算机工程的第二学期 我的问题是如何添加JButton等。。。在背景图像上,您知道我已经编写了以下代码,请帮助我继续: 正如我所说的,我的JBotton不能显示在图片上,这就是问题所在Java 如何添加缓冲图像作为JFrame的背景,然后在此图像上添加面板?,java,image,swing,background,jframe,Java,Image,Swing,Background,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.IOExcepti
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
JComponent不使用布局管理器,因此添加按钮时不会显示 尝试在组件上使用
FlowLayout
另外,不要对帧使用setBounds()。您应该pack()
,然后使用setLocationByPlatform(true)
,以便以其首选大小显示帧
您需要为您的组件实现
getPreferredSize()
,这样才能正常工作 JComponent不使用布局管理器,因此添加按钮时不会显示
尝试在组件上使用FlowLayout
另外,不要对帧使用setBounds()。您应该pack()
,然后使用setLocationByPlatform(true)
,以便以其首选大小显示帧
您需要为您的组件实现
getPreferredSize()
,这样才能正常工作 调用super.paintComponent
会很高兴;)调用super.paintComponent
会很高兴;)一种简单的方法是使用JLabel
和LayoutManager
作为JFrame
的内容窗格。选中此项,一种简单的方法是使用JLabel
和LayoutManager
作为JFrame
的内容窗格。检查这个,然后