I have the following code to dynamically add panels to a container with a GridBagLayout. It should grow and display a vertical scrollbar, not horizontal.
But when I add text too long in JLabel in the parent JPanel, it displays a horizontal scroll bar, I want JLabel to interrupt the text when the container is compressed, and also grows as the container grows. I tried to set the maximum width, but GridBagLayout did not use it.
I also tried using something like this, but it makes the shortcut not growing when I resize the parent.
import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.border.MatteBorder; public class DynamicPanelList extends JPanel { private JPanel mainList; public DynamicPanelList() { setLayout(new BorderLayout()); mainList = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.weighty = 1; mainList.add(new JPanel(), gbc); add(new JScrollPane(mainList)); JButton add = new JButton("Add"); add.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JLabel lbl = new JLabel("<html>Hello world items lorem ipsum dolor sit amei blast it");

source share