找到你要的答案

Q:How to bring the Image in Java GUI To a new line?

Q:如何在java GUI带来的图像到一个新的行吗?

I am trying to make a simple gui window with images. Here's my code:

import java.awt.*;

import javax.swing.*;
public class Image extends JFrame
{
    private ImageIcon [] image = new ImageIcon[10];
    private JLabel [] label = new JLabel[10];

    Image()
    {
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();


        for(int i=0; i<10; i++)
        {
            for(int j = 0; j<10;j++)
            {
            image[i] = new ImageIcon(getClass().getResource((i+1) +".jpg"));
            label[i] = new JLabel (image[i]);
            c.fill = GridBagConstraints.REMAINDER;
            c.gridx = j;
            c.gridy = i;
            add(label[i]);
            }
        }
    }

    public static void main(String[] args)
    {
        Image i = new Image();
        i.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        i.setVisible(true);
        i.pack();
        i.setTitle("My Title");
    }

}

What I am trying to do is after the counter exits the inner loop, it should go on a new line in the window.

But i get the whole thing in the same line. Any suggestions?

I am trying to make a simple gui window with images. Here's my code:

import java.awt.*;

import javax.swing.*;
public class Image extends JFrame
{
    private ImageIcon [] image = new ImageIcon[10];
    private JLabel [] label = new JLabel[10];

    Image()
    {
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();


        for(int i=0; i<10; i++)
        {
            for(int j = 0; j<10;j++)
            {
            image[i] = new ImageIcon(getClass().getResource((i+1) +".jpg"));
            label[i] = new JLabel (image[i]);
            c.fill = GridBagConstraints.REMAINDER;
            c.gridx = j;
            c.gridy = i;
            add(label[i]);
            }
        }
    }

    public static void main(String[] args)
    {
        Image i = new Image();
        i.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        i.setVisible(true);
        i.pack();
        i.setTitle("My Title");
    }

}

我想做的是在柜台退出内部循环,它应该在一个新的行窗口。

但我得到了整个事情在同一行。有什么建议吗?

answer1: 回答1:

You need to pass the constraints as a parameter when adding the labels:

add(label[i], c);

instead of

add(label[i]);

Not directly related to the problem, but you should create the GUI in the event dispatch thread; also, call setVisible(true) on the frame only after it is otherwise ready.

当添加标签时,需要将约束作为参数传递:

add(label[i], c);

而不是

add(label[i]);

没有直接的关系,但你应该建立在事件派发线程GUI;同时,调用setVisible(true)在框架后才是其他准备。

java  swing  layout  awt  layout-manager