繁体   English   中英

是否可以在 JFrame 中添加图像,但 class 是用 JPanel 扩展的?

[英]Is it possible to add a image in JFrame but the class is extended with JPanel?

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

  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, 200);           
      add(img);
      frame.setVisible(true);
      frame.setSize(500,500);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

简单的答案是,是的,你应该这样做。 JPanel只是一种容器, JFrame是一种特殊类型的容器,因此许多概念是可以转移的。

简单的

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 class,这里我刚刚使用了JFrame作为顶级容器

通过阅读使用 JFC/Swing 教程创建 GUI会更好地回答此类问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM