In order to add a background Image , I work on JLabels instead of JPanel .
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label=new JLabel(new ImageIcon("bg.png"));
label.setLayout(new BoxLayout(label, BoxLayout.Y_AXIS));
for(int i=0;i<20;i++)
label.add(new JLabel(i.toString()));
frame.add(label);
the problem here is that only components that fit the background image will be shown (in my example only the 10 first JLabels)
I tried using a JScrollPane
JScrollPane scroll=new JScrollPane(l);
for(int i=0;i<20;i++)
label.add(new JLabel(i.toString()));
frame.add(scroll);
but it didn't change much , so I tried using a JPanel
JPanel panel=new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JScrollPane scroll=new JScrollPane(panel);
for(int i=0;i<20;i++)
panel.add(new JLabel(i.toString()));
label.add(scroll);
frame.add(label);
so I got the JScrollPane working properly but the JPanel has covered the background image
what should I do ?
Here's the result to adding JLabels to label:
The result after adding them to the scroll:
And after adding setOpaque(false)
to the JPanel
:
You can add the image as part of the
JPanel
'spaintComponent()
method, then add the labels above it, then put that pane inside aJScrollPane
and finally add it to theJFrame
, for example:Which gives the following output:
If you want the
JLabels
centered, you can change thefor
loop with:Which should look similar to this:
Note:
You can copy-paste the code above, it should work, just change the image path, and that code, is called a Minimal, Complete and Verifiable Example (MCVE), next time, please post one which demonstrates what you have tried, not only parts of it, this way you'll get more, better and faster answers. Help us to help you! :)