为什么这不起作用

为什么这不起作用

本文介绍了设置JFrame背景,为什么这不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的jFrame设置背景,我正在使用此代码:

I want to set a background to my jFrame, and I'm using this code:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DemoBackgroundSwing extends JPanel {

  private Image img;

  public DemoBackgroundSwing() {
      System.out.println("done");
    img = Toolkit.getDefaultToolkit().createImage("red.png");
    System.out.println("done");
    loadImage(img);
    System.out.println("done");
  }

  private void loadImage(Image img) {
    try {
      MediaTracker track = new MediaTracker(this);
      track.addImage(img, 0);
      track.waitForID(0);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  protected void paintComponent(Graphics g) {
    setOpaque(false);
    System.out.println("done");
    g.drawImage(img, 0, 0, null);
    super.paintComponent(g);
  }

  public static void main(String... argv) {
    JFrame frame = new JFrame("Demo Background Image");
    DemoBackgroundSwing back = new DemoBackgroundSwing();
    System.out.println("done");
    frame.getContentPane().add(back);
    frame.setSize(400, 287);
    frame.setVisible(true);
  }
}

当我执行它时,在系统输出中我有5个完成。所以这意味着所有任务都被执行了。
我不明白错误在哪里。请帮助我!

when I execute it, in system out I have 5 "done". so this means that all tasks are executed.I don't understand where's the error. Please Help me!

推荐答案

打印加载图像的宽度(如果为-1)则图像未正确加载。

Print the width of loaded image if it's -1 then image is not properly loaded.

img = Toolkit.getDefaultToolkit().createImage("red.png");
System.out.println(img.getWidth(null)); // check what it prints

值得阅读 Java Tutorial

您可以根据图像位置尝试任何一种。

You can try any one based on image location.

// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));

// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))

// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))

某些积分:


  • 在重写的 paintComponent的第一行调用 super.paintComponent(g); ( )方法。

  • call super.paintComponent(g); at first line in the overridden paintComponent() method.

使用 ImageIO 而不是工具包加载图片。

使用 frame.pack()而不是 frame.setSize()根据组件的首选大小调整组件。

Use frame.pack() instead of frame.setSize() that fits the components as per component's preferred size.

覆盖 getPreferredSize()在自定义绘画的情况下设置 JPanel 的首选大小。

Override getPreferredSize() to set the preferred size of the JPanel in case of custom painting.

使用或以确保已正确初始化。

Use SwingUtilities.invokeLater() or EventQueue.invokeLater() to make sure that EDT is initialized properly.

了解更多


这篇关于设置JFrame背景,为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 23:39