是否可以在JFrame中添加图像,但使用JPanel扩展了该类?

问题描述

这是我的代码,我可以在JFrame扩展的类中运行它。但是现在我需要将此代码添加到使用JPanel扩展的类中。是否可以在JPanel类中添加它?如果不能,如何在JPanel类中添加图像?

  JLabel img; 
  String url = "image/Screenshot(295).png";  

  void Car() {
     
      frame=new JFrame("Malaysia Checker");
      frame.getContentPane().setBackground(Color.white);
      img = new JLabel();     
      ImageIcon icon = new ImageIcon(url); 
      img.setIcon(icon);  
      img.setBounds(200,200,200);           
      add(img);
      frame.setVisible(true);
      frame.setSize(500,500);
      frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);

解决方法

简单的答案是,是的,您应该这样做。 JPanel只是一种容器,JFrame是一种特殊的容器,因此许多概念都是可移植的。

Simple

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            setBackground(Color.WHITE);
            try {
                // Warning,this is a blocking call and my slow down the launch/presentation of the view
                BufferedImage background = ImageIO.read(new URL("https://upload.wikimedia.org/wikipedia/en/thumb/3/30/Java_programming_language_logo.svg/234px-Java_programming_language_logo.svg.png"));
                JLabel label = new JLabel(new ImageIcon(background));
                add(label);
            } catch (IOException ex) {
                ex.printStackTrace();
                add(new JLabel("Could not load background image"));
            }
        }

    }
}

请记住,为了显示任何组件,您需要某种Window类,这里我只是使用JFrame作为顶层容器

通过阅读Creating a GUI With JFC/Swing教程

,可以更好地回答此类问题。