0

I have a problem with my Swing app. If i start my application and place my mouse pointer where the button is going to be, the upper JLabel goes on the button.

This is a picture showing my problem

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

    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    defFont = new Font("Impact", Font.PLAIN, 32);

    JPanel mainpanel = new JPanel();
    mainpanel.setLayout(new BorderLayout());
    mainpanel.setPreferredSize(new Dimension(480, 320));
    mainpanel.setBackground(Color.white);

    JLabel title = new JLabel("-----Title-----");
    title.setFont(defFont);
    title.setHorizontalAlignment(JLabel.CENTER);

    JLabel footer = new JLabel("Footer");
    footer.setFont(defFont.deriveFont(Font.TRUETYPE_FONT, 14f));

    JPanel midPanel = new JPanel();
    midPanel.setBackground(Color.GRAY);
    midPanel.setLayout(new GridBagLayout());

    JButton startGameButton = new JButton("New Game");
    applySettings(startGameButton);

    midPanel.add(startGameButton);

    mainpanel.add(title, BorderLayout.NORTH);
    mainpanel.add(midPanel, BorderLayout.CENTER);
    mainpanel.add(footer, BorderLayout.PAGE_END);

    add(mainpanel);
    pack();
    setVisible(true);

EDIT: Forget to paste in the applySettings method. The button has some styling on it, maybe the function, that makes it transparent is the problem.

I've tested the code a bit, and when i try to set the background color, it brokes.

private void applySettings(JButton button)
{
    button.setPreferredSize(new Dimension(200, 100));
    button.setFont(defFont.deriveFont(Font.TRUETYPE_FONT, 24f));
    button.setBorder(BorderFactory.createLineBorder(Color.black, 2, true));

    button.setFocusPainted(false);
    button.setBackground(new Color(255, 255, 255, 100));
    button.setContentAreaFilled(true);
}
  • Post your [mcve] that demonstrates the problem. That is we should be able to copy/paste/compile/test the code. For example we have no idea what `applySettings(...)` does. I suggest if the code is not relevant to the problem then comment out the code and retest. – camickr May 03 '18 at 21:13
  • Sorry for that mistake. It seems ".setBackground(new Color(255, 255, 255, 100));" does the glitch. – user3820214 May 03 '18 at 21:29
  • Kept only the size and the background setter methods, and still happening – user3820214 May 03 '18 at 21:37
  • `Sorry for that mistake. It seems ".setBackground(new Color(255, 255, 255, 100));" does the glitch.` - and that is we need a proper [mcve] with every question. And you still haven't posted a proper MCVE". How can we compile that code??? It is in two pieces. There is no main() method or JFrame. – camickr May 03 '18 at 22:32

1 Answers1

1

Found this solution online, and it solves the problem.

Ref: Backgrounds With Transparency

camickr
  • 321,443
  • 19
  • 166
  • 288