如何在 JPanel 中设置背景图片
在这段代码中,我们添加了一个名为 mainPanel 的 JPanel 来表示背景。这是更新后的代码:
<code class="java">import java.awt.*; import javax.swing.*; import java.awt.event.*; public class imagebut extends JFrame { public static void main(String args []) { imagebut w = new imagebut(); w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); w.setSize(300,300); w.setVisible(true); } public imagebut() { setLayout(null); // :-) PicPanel mainPanel = new PicPanel("picturename.jpg"); mainPanel.setBounds(0,0,500,500); add(mainPanel); } class PicPanel extends JPanel{ private BufferedImage image; private int w,h; public PicPanel(String fname){ //reads the image try { image = ImageIO.read(new File(fname)); w = image.getWidth(); h = image.getHeight(); } catch (IOException ioe) { System.out.println("Could not read in the pic"); //System.exit(0); } } public Dimension getPreferredSize() { return new Dimension(w,h); } //this will draw the image public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(image,0,0,this); } } }</code>
此代码现在会将背景图像设置到 JPanel,并且它将在框架中正确显示。
以上是如何在 Java 中为 JPanel 设置背景图像?的详细内容。更多信息请关注PHP中文网其他相关文章!