0

我想知道为什么我的按钮直到我将鼠标悬停在它所在的位置之后才显示在面板上?如果我调整窗口大小,它也会再次消失。MainMenuScreen 只是我用作背景图像的图像。

    //MainMenu setup
    JPanel card2 = new JPanel();
    card2.setLayout(new GridBagLayout());       
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(2,2,2,2);
    gbc.anchor = GridBagConstraints.CENTER;
    MainMenuScreen mms = new MainMenuScreen();
    mms.setLayout(new FlowLayout());
    card2.add(mms);
    card2.add(menuButton1, gbc);

这是我通过背景图像设置的方法。

public class MainMenuScreen extends JPanel{
    private static final long serialVersionUID = 1L;

    private BufferedImage background;

    public MainMenuScreen() {
        try {
            background = ImageIO.read(new File("M&M Arcade.png"));          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(800, 600);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (background != null) {
            int x = (getWidth() - background.getWidth());
            int y = (getHeight() - background.getHeight());
            g.drawImage(background, x, y, this);
        }

        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(Color.white);
    }
}
4

1 回答 1

1

JButton不会显示,因为您对组件和您的使用相同的GridBagConstraints值,即它们存在于同一位置。一旦调整了 的值,就会出现按钮。在添加到带有.MainMenuScreenJButton menuButton1gbcGridBagLayout

编辑:

关于如何在JPanel容器上实现背景图像已经有很多讨论。一个值得注意的是背景面板

于 2013-03-16T17:25:59.943 回答