为什么getScaledInstance()不起作用?

2022-06-15 00:00:00 image java swing paint scaling

所以,我正在尝试创建一个垄断游戏。我正在尝试将(电路板的)图像加载到JPanel

我首先要将图像缩放为1024*1024图像。

我已经将图像显示在JPanel上(这样文件地址就可以工作了)。

但每当我使用getScaledInstance()方法时,图像都不显示

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.SystemColor;

//a class that represent the board (JFrame) and all of it components 
public class Board extends JFrame {
private final int SCALE;
private JPanel panel;

public Board(int scale) {
    getContentPane().setBackground(SystemColor.textHighlightText);
    // SCALE = scale;
    SCALE = 1;
    // set up the JFrame
    setResizable(false);
    setTitle("Monopoly");
    // set size to a scale of 1080p
    setSize(1920 * SCALE, 1080 * SCALE);
    getContentPane().setLayout(null);

    panel = new JPanel() {
        public void paint(Graphics g) {
            Image board = new ImageIcon(
                    "C:\Users\Standard\Pictures\Work\Monopoly 1.jpg")
                    .getImage();
            board = board.getScaledInstance(1022, 1024, java.awt.Image.SCALE_SMOOTH);

            g.drawImage(board, 0, 0, null);
        }
    };
    panel.setBounds(592, 0, 1024, 1024);
    getContentPane().add(panel);
}

public static void main(String[] args) {
    Board board = new Board(1);
    board.setVisible(true);
    board.panel.repaint();
 }
}

每当我删除board.getScaledInstance()代码行时,图像都会显示(虽然没有缩放),但当我添加代码行时,图像根本不显示。

为什么会发生这种情况?


解决方案

您做错了几件事:

相关文章