编程语言
首页 > 编程语言> > java-尽管位置为0,Jpanel第一项仍居中

java-尽管位置为0,Jpanel第一项仍居中

作者:互联网

我正在尝试以编程方式为我正在从事的项目创建背景网格.问题是我添加到jpanel的第一个项目始终绘制在jpanel的中心.我明确地试图将其放在右上角.我什至尝试过仅将虚拟jlabel放在首位并从那里开始,然后第二个和第三个元素彼此重叠.这个错误使我彻底傻眼了.任何帮助都会很棒.

 private void evalWindow(){
    window.removeAll();
    window.setBorder(BorderFactory.createLineBorder(Color.black));
    JLabel p = new JLabel(new ImageIcon(tiles[0][0].getImage()));
    p.setLocation(0,0);

    System.out.println("1: " + p.getLocation());
    p.setSize(64,64);
    window.add(p);
    System.out.println("2: " + p.getLocation());
    for(int i = 0; i < x; i++){
        for (int j = 0; j  < y; j++){
            JLabel piclabel = new JLabel(new ImageIcon(tiles[i][j].getImage()));
            piclabel.setSize(64,64);
            piclabel.setLocation(64*j, 64*i);

            System.out.println("1: " + piclabel.getLocation());
            window.add(piclabel);
        }
    }
}

样本图片:

https://i.stack.imgur.com/DlSgb.png

解决方法:

如其他地方提到的那样,GridLayout是布局网格位置的最简单方法.它可以很简单:

public void initUI(Image img) {
    ui = new JPanel(new GridLayout(0,8));

    ImageIcon icon = new ImageIcon(img);
    for (int ii=0; ii<32; ii++) {
        ui.add(new JLabel(icon));
    }
}

这是效果:

enter image description here

这是产生上述GUI的MCVE.将来,请以MVCE的形式发布代码.

import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import javax.swing.*;
import javax.imageio.*;
import java.net.URL;

public class ImageGrid {

    private JComponent ui = null;
    String imageURL = "https://i.stack.imgur.com/DlSgb.png";

    ImageGrid() {
        try {
            BufferedImage img = ImageIO.read(new URL(imageURL));
            BufferedImage subImg = img.getSubimage(2, 2, 64, 64);
            initUI(subImg);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    final public void initUI(Image img) {
        ui = new JPanel(new GridLayout(0,8));

        ImageIcon icon = new ImageIcon(img);
        for (int ii=0; ii<32; ii++) {
            ui.add(new JLabel(icon));
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            ImageGrid o = new ImageGrid();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

标签:swing,jpanel,layout-manager,java
来源: https://codeday.me/bug/20191025/1927992.html