我尝试将一个图像添加到我的窗口并使其与窗口大小相同但项目不会运行且没有图像出现,当我使图像工作之前它不会是大小的屏幕甚至以为我使用WIDTH
和HEIGHT
这是我用于窗口的。
import javax.swing.*;
public class Main {
public static int WIDTH = 1000;
public static int HEIGHT = 368;
public static JFrame window = new JFrame();
public static void main(String[] args) {
CreateWindow();
}
public static void CreateWindow() {
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setSize(WIDTH, HEIGHT);
BackgroundImage();
window.setVisible(true);
}
public static void BackgroundImage() {
ImageIcon image = new ImageIcon("C:\\Users\\SamBr\\Pictures\\image.png");
window.add(image)
image.setSize(WIDTH, HEIGHT);
}
}
答案 0 :(得分:2)
使用JLabel
显示您的图片,使用getScaledInstance()
方法可以调整图片大小。
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Main {
public static int WIDTH = 1000;
public static int HEIGHT = 368;
public static JFrame window = new JFrame();
public static void main(String[] args) {
CreateWindow();
}
public static void CreateWindow() {
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setSize(WIDTH, HEIGHT);
BackgroundImage();
window.pack();
window.setVisible(true);
}
public static void BackgroundImage() {
ImageIcon imageIcon = new ImageIcon("C:\\Users\\SamBr\\Pictures\\image.png");
ImageIcon scaledImage = new ImageIcon(
imageIcon.getImage().getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH));
JLabel label = new JLabel();
label.setIcon(scaledImage);
window.add(label);
}
}