将按钮添加到包含缓冲图像的JLabel时,按钮不会出现

时间:2018-07-22 18:39:52

标签: java swing jbutton jlabel layout-manager

因此,我已将缓冲的图像加载到JLabel上。

启动程序时,仅显示图像,但不显示按钮。

我尝试将JButtons直接添加到JLabel中,结果相同。但是,如果我将buttonPanel直接添加到框架,则按钮最终将可见。但是,如果我将JLabel直接添加到框架中,然后添加buttonPanel,则只有按钮可见。

public void setProp(){
    //frame properties
    mainFrame.setSize(1200, 845); //JFrame
    mainFrame.setVisible(false);
    mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    //layout properties
    buttonLayout.setHgap(100); //GridLayout
    buttonLayout.setColumns(1);
    buttonLayout.setRows(6);

    //panel properties
    buttonPanel.setLayout(buttonLayout);
    buttonPanel.setVisible(true);
    buttonPanel.setOpaque(false);


    //button properties
    newGame.setOpaque(false);
    newGame.setContentAreaFilled(false);
    newGame.setBorderPainted(false);
    newGame.setForeground(Color.WHITE);
    newGame.setFont(buttonFont);
    newGame.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            //launch designated method
        }
    });

    loadGame.setOpaque(false);
    loadGame.setContentAreaFilled(false);
    loadGame.setBorderPainted(false);
    loadGame.setForeground(Color.WHITE);
    loadGame.setFont(buttonFont);
    loadGame.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            //launch designated method
        }
    });

    credits.setOpaque(false);
    credits.setContentAreaFilled(false);
    credits.setBorderPainted(false);
    credits.setForeground(Color.WHITE);
    credits.setFont(buttonFont);
    credits.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            //launch designated method
        }
    });

    exit.setOpaque(false);
    exit.setContentAreaFilled(false);
    exit.setBorderPainted(false);
    exit.setForeground(Color.WHITE);
    exit.setFont(buttonFont);
    exit.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.exit(0);
        }
    });

    //background properties
    background = importPic("D:/programming rescources/strategy game/resources/images/mmpic.JPG");

    //adding components to mainFrame
    buttonPanel.add(newGame); //adding all buttons onto JPanel with GridLayout
    buttonPanel.add(loadGame);
    buttonPanel.add(credits);
    buttonPanel.add(exit);

    background.add(buttonPanel);//this is the JLabel with the buffered image

    mainFrame.add(background);
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我是通过将BorderLayout添加到backgorund(JLabel),然后将背景添加到JFrame来实现的。