0

I need to set a background image for a JFrame and to display a JLabel using a BorderLayout. After looking at other questions I wrote down the following code:

JFrame frame = new JFrame("My window");
JTextField username = new JTextField();
Button startGame = new Button("Enter");
JPanel bottomPanel = new JPanel();

bottomPanel.add(username);
bottomPanel.add(startGame);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setContentPane(new JLabel(background));
frame.pack();
frame.setVisible(true);

The problem is that bottomPanel, a JPanel containing a JButton and a JTextField, isn't shown on the GUI. I found out that using a GridBagLayout as shown in this answer (How to set a background picture in JPanel) actually works but it's not easy to set and I'd prefer to use the default BorderLayout.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Stefano Berti
  • 141
  • 1
  • 11
  • *"After looking at other questions.."* Which other questions? I ask because.. *"..I wrote down the following code:"* based on that 2 line code snippet, the answers could use a down vote, or at least an explanatory comment. A `JLabel` should not be used as a container of other components, and is therefore unsuited to being used to display a BG image. *"This is only the important part of the code."* Important? Most beginners don't know what's important and what isn't. The real problem is often in parts of the code not shown. For better help sooner, post a [MCVE]. – Andrew Thompson Jun 11 '17 at 17:23
  • Ok, I edited my question. For example in the first code snippet of the answer I linked the background is set by JLabel but using the `GridBagLayout` for some reason it works. – Stefano Berti Jun 11 '17 at 18:20
  • That's not an answer of what I'm trying to do – Stefano Berti Jun 11 '17 at 18:48
  • 1
    `That's not an answer of what I'm trying to do` - no idea what that comment relates to. `the first code snippet` - the snippet you posted makes no sense. First you add the "bottomPanel" to the frame, but then you set the content pane to the label, which means you lose the bottomPanel. `I found out that using a GridBagLayout actually works` - so you have a working example. There is no reason you can't change the layout to a BorderLayout, it just means the components you add to the panel will be displayed using the rules of the BorderLayout instead of the GridBagLayout. – camickr Jun 11 '17 at 19:23

0 Answers0