除了CENTER之外,为什么我的图像不会加载到contentPane上?

时间:2022-11-10 15:10:45

I am currently still learning Java GUI and stumped on this problem. I just wonder why can't i load it anywhere except on center and how do i load my image anywhere else?

我目前仍在学习Java GUI并且难以解决这个问题。我只是想知道为什么我不能加载它除了在中心以外如何在其他地方加载我的图像?

import java.awt.*;

import javax.swing.*;

public class GUI {

    public static void main(String[] args) {
        GUI gui = new GUI();
        gui.go();
    }

    public void go() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        Player player = new Player();
        panel.setBackground(Color.darkGray);

        JButton button = new JButton("shock me");

        panel.add(button);

        frame.getContentPane().add(BorderLayout.EAST, panel);
        frame.getContentPane().add(BorderLayout.NORTH, player);


        //frame.getContentPane().add(BorderLayout.CENTER, player);

        frame.setSize(200,200);
        frame.setVisible(true);
    }
}

Here's my player class

这是我的球员类

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
import javax.swing.*;

public class Player extends JPanel{

    public void paintComponent(Graphics g) {
        Image image = new ImageIcon("Source/hero.jpg").getImage();
        g.drawImage(image, 3, 4 , this);
    }
}

1 个解决方案

#1


Player does not override getPreferredSize() to return a value. Since it does not do that, the BorderLayout will not assign it any height in the PAGE_START or PAGE_END constraints, and no width in the LINE_START and LINE_END constraints. The component is being added, it just has no width/height.

Player不会覆盖getPreferredSize()以返回值。由于它不会这样做,因此BorderLayout不会在PAGE_START或PAGE_END约束中为其指定任何高度,也不会在LINE_START和LINE_END约束中指定任何宽度。正在添加组件,它没有宽度/高度。

The CENTER will stretch both a component's width and height to the available space, that is why it is visible there.

CENTER会将组件的宽度和高度拉伸到可用空间,这就是它在那里可见的原因。

#1


Player does not override getPreferredSize() to return a value. Since it does not do that, the BorderLayout will not assign it any height in the PAGE_START or PAGE_END constraints, and no width in the LINE_START and LINE_END constraints. The component is being added, it just has no width/height.

Player不会覆盖getPreferredSize()以返回值。由于它不会这样做,因此BorderLayout不会在PAGE_START或PAGE_END约束中为其指定任何高度,也不会在LINE_START和LINE_END约束中指定任何宽度。正在添加组件,它没有宽度/高度。

The CENTER will stretch both a component's width and height to the available space, that is why it is visible there.

CENTER会将组件的宽度和高度拉伸到可用空间,这就是它在那里可见的原因。