0

I want to add a JScrollPane to a panel but when I add the scroll pane to a panel, the background of the panel changes and becomes white. Why does this happen?

JPanel followingsName=new JPanel();
JScrollPane scrollPane2=new JScrollPane();
scrollPane2.add(followingsName);
scrollPane2.setBounds(430,190,370,250);
scrollPane2.setOpaque(false);
scrollPane2.setViewportView(followingsName);
scrollPane2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane2.setHorizontalScrollBar(null);

JPanel pp= new JPanel();
pp.setLayout(null);
pp.setBackground(Color.pink);
pp.add(scrollPane2);

JFrame frame=new JFrame();
frame.setLayout(null);
frame.setPreferredSize(new Dimension(900,590));
frame.setSize(frame.getPreferredSize());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setContentPane(pp);
frame.setVisible(true);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    First of all don't use a null layout. Swing was designed to be used with layout managers. The scroll panel will NOT work if you use a null layout. Don't add components to the scroll panel. Instead, the component should be added to the "viewport" of the scroll panel. Read the section from the Swing tutorial on [How to Use Text Fields](https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html) for a working example. Download the `TextDemo` example and modify it for your requirements as the tutorial will show you how to better structure your code. – camickr May 01 '21 at 18:06
  • thankyou. I add the panel to "viewport" of the scroll pane and my problem solved. – Zahra Heidarifar May 01 '21 at 18:23

0 Answers0