【问题标题】:How to add a picture to a JPanel using a JLabel如何使用 JLabel 将图片添加到 JPanel
【发布时间】:2016-07-16 05:57:43
【问题描述】:

当我尝试将我的图片图标添加到面板上的 JLabel 时,它根本不显示。有人可以告诉我我做错了什么吗?这是我的代码的一部分:

    public class GameWindow extends JFrame implements ActionListener
{
    ImageIcon myPicture = new ImageIcon("src/GUI/Images/Face copy.png");
    JLabel picLabel = new JLabel(myPicture);

public GameWindow()

{
    super("Game Window");
    this.setSize(1500, 800);
    this.setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    JPanel tryThis = new JPanel();
    tryThis.setLayout(new BorderLayout());
    this.add(tryThis, BorderLayout.CENTER);
    JPanel grid1 = new JPanel();
    tryThis.add(grid1);

    int e = 4;
    int f = 14;
    JPanel[][] grid = new JPanel[e][f];
    grid1.setLayout(new GridLayout(e,f));

    for(int g = 0; g < e; g++) {
       for(int h = 0; h < f; h++) {
          grid[g][h] = new JPanel();
          grid1.add(grid[g][h]);
          grid[g][h].setBorder(BorderFactory.createTitledBorder("Info"));
       }
    }

    grid[3][3].add(picLabel);

【问题讨论】:

  • 这就是你的全部代码吗?你是否创建了一个新的 GameWindow 实例?
  • 另外,当我尝试运行您的代码时,我有一个名为“tryThis”的未知变量
  • 这不是我的全部代码,但我确实在另一个类中创建了另一个实例。
  • 忘记添加那部分了,抱歉。
  • 运行你的代码后,这就是我得到的。 oi64.tinypic.com/2qvaxvr.jpg

标签: java swing jpanel jlabel imageicon


【解决方案1】:

好的,我稍微调整了你的代码,但我设法让它在网格 3,3 上显示图像(虽然我只能在稍微调整屏幕大小后才能看到图像)

public class GameWindow extends JFrame implements ActionListener {

    public GameWindow(){
        super("Game Window");

        setSize(1500, 800);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel tryThis = new JPanel();
        tryThis.setLayout(new BorderLayout());

        add(tryThis, BorderLayout.CENTER);

        JPanel grid1 = new JPanel();
        tryThis.add(grid1);

        int e = 4;
        int f = 14;
        JPanel[][] grid = new JPanel[e][f];
        grid1.setLayout(new GridLayout(e,f));

        for(int g = 0; g < e; g++) {
           for(int h = 0; h < f; h++) {
              grid[g][h] = new JPanel();
              grid1.add(grid[g][h]);
              grid[g][h].setBorder(BorderFactory.createTitledBorder("Info"));
           }
        }

        try {
            // Loads the image
            BufferedImage myPicture = ImageIO.read(MainClassNameGoesHere.class.getResource("/example.png"));
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));

            // Displays the image
            grid[3][3].add(picLabel);
        } catch (IOException exception) {
            exception.printStackTrace();
        }

    }

我更改的主要内容是您在图像中加载的方式。 我希望这会有所帮助,并随时提出任何问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2018-01-20
    相关资源
    最近更新 更多