我的背景图片上方出现一个奇怪的白色条纹(如下所示)。代码很简单。如何摆脱白色条纹?

java - JFrame在背景图片顶部出现奇怪的白色条纹-LMLPHP

//Graphics side of the game
public class GUI extends JFrame {

    private final int larghezza = 1280;
    private final int altezza = 720;
    private final String name = "Sette e Mezzo";

    private final ImageIcon backgroundImage;
    private JLabel bgImageLabel;
    private JPanel backgroundPanel, borderLayoutPanel, topGridLayout, botGridLayout;

    public GUI () {
        backgroundImage = new ImageIcon ("assets/background.png");

        bgImageLabel = new JLabel (backgroundImage);

        //Panels
        borderLayoutPanel = new JPanel (new BorderLayout ());
        topGridLayout = new JPanel (new GridLayout (1, 3));
        botGridLayout = new JPanel (new GridLayout (1, 3));
        backgroundPanel = new JPanel ();
        backgroundPanel.add (bgImageLabel);

        //Frame
        this.setName (name);
        this.setPreferredSize (new Dimension(larghezza, altezza));
        this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

        //Adding to frame and panels
        borderLayoutPanel.add (topGridLayout, BorderLayout.NORTH);
        borderLayoutPanel.add (botGridLayout, BorderLayout.SOUTH);

        this.add (borderLayoutPanel);
        this.add (backgroundPanel);

        this.pack ();
        this.setLocationRelativeTo (null);
        this.setVisible (true);
    }
}

最佳答案

当您真的要表示override setPreferredSize()时,请不要使用getPreferredSize()。在这种情况下,指定的Dimension可能与"assets/background.png"的大小完全不匹配。这样可以显示另一个面板的某些部分,也许是backgroundPanel

在下面的示例中,


JPanel的默认布局是FlowLayout,它具有“默认的5个单位的水平和垂直间距”。轻触Color.blue可使间隙突出。调整封闭框架的大小以查看行为。
由于JFrame的默认布局是BorderLayout,因此可能根本不需要borderLayoutPanel
因为这两个GridLayout面板没有内容,所以它们保持不可见。向每个内容添加内容或在每个内容中覆盖getPreferredSize()以查看效果。
仅在event dispatch thread上构造和操作Swing GUI对象。


java - JFrame在背景图片顶部出现奇怪的白色条纹-LMLPHP

import java.awt.*;
import java.net.URL;
import javax.swing.*;

public class GUI {

    private static final String TITLE = "Title";
    private static ImageIcon IMAGE_ICON;

    private void display() {
        //Panels
        JPanel topGridLayout = new JPanel(new GridLayout(1, 3));
        JPanel botGridLayout = new JPanel(new GridLayout(1, 3));
        JPanel backgroundPanel = new JPanel();
        backgroundPanel.setBackground(Color.blue);
        backgroundPanel.add(new JLabel(IMAGE_ICON));

        //Frame
        JFrame f = new JFrame(TITLE);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add components
        f.add(topGridLayout, BorderLayout.NORTH);
        f.add(backgroundPanel);
        f.add(botGridLayout, BorderLayout.SOUTH);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        IMAGE_ICON = new ImageIcon(new URL("http://i.imgur.com/mowekvC.jpg"));
        EventQueue.invokeLater(new GUI()::display);
    }
}

07-24 09:26