简体   繁体   中英

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

Here is my code, i can run it in class extended with JFrame. But now i need to add this code to a class extended with JPanel. Is it possible to add this in JPanel class? If cannot how can i add an image in 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);

Simple answer is, yes, and you should. A JPanel is just a type of container, a JFrame is a specialised type of container, so many of the concepts are transferable.

简单的

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"));
            }
        }

    }
}

Remember, in order to display any component, you need some kind of Window class, here I've just used a JFrame as the top level container

This kind of question would be better answer by reading through the Creating a GUI With JFC/Swing tutorials

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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