[英]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.