在背景图象顶部的JFrame奇怪的白色条纹

时间:2017-05-13 09:23:44

标签: java image swing

我的背景图像上出现了一条奇怪的白色条纹(见下图)。代码很简单。如何摆脱白色条纹?

enter image description here

//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);
    } 
}

1 个答案:

答案 0 :(得分:1)

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

在下面的示例中,

  • JPanel的默认布局为FlowLayout,其默认为5个单位的水平和垂直间距。"轻轻一点Color.blue就可以突破这个差距;调整封闭框架的大小以查看行为。

  • 由于JFrame的默认布局为BorderLayout,您可能根本不需要borderLayoutPanel

  • 由于两个GridLayout面板没有内容,因此它们仍然不可见。向每个内容添加内容或覆盖每个内容中的getPreferredSize()以查看效果。

  • event dispatch thread上构建和操作仅的Swing GUI对象。

image

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);
    }
}